bestpred-mcp 0.2.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bestpred_mcp-0.2.1/.gitignore +7 -0
- bestpred_mcp-0.2.1/Dockerfile +11 -0
- bestpred_mcp-0.2.1/PKG-INFO +77 -0
- bestpred_mcp-0.2.1/README.md +62 -0
- bestpred_mcp-0.2.1/pyproject.toml +33 -0
- bestpred_mcp-0.2.1/src/bestpred_mcp/__init__.py +3 -0
- bestpred_mcp-0.2.1/src/bestpred_mcp/__main__.py +32 -0
- bestpred_mcp-0.2.1/src/bestpred_mcp/herd.py +244 -0
- bestpred_mcp-0.2.1/src/bestpred_mcp/hosted.py +93 -0
- bestpred_mcp-0.2.1/src/bestpred_mcp/server.py +185 -0
- bestpred_mcp-0.2.1/tests/test_server.py +137 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# The hosted service. Build from the repository root: docker build -f mcp/Dockerfile -t bestpred-mcp .
|
|
2
|
+
FROM python:3.12-slim
|
|
3
|
+
WORKDIR /app
|
|
4
|
+
COPY pyproject.toml README.md LICENSE NOTICE ./
|
|
5
|
+
COPY src ./src
|
|
6
|
+
COPY mcp ./mcp
|
|
7
|
+
RUN pip install --no-cache-dir ./ ./mcp && useradd --create-home bestpred
|
|
8
|
+
USER bestpred
|
|
9
|
+
ENV PORT=8080
|
|
10
|
+
EXPOSE 8080
|
|
11
|
+
CMD ["bestpred-mcp", "--http", "--host", "0.0.0.0"]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: bestpred-mcp
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: USDA's best prediction of dairy lactation yields (BESTPRED) as tools any AI agent can call: an MCP server for Claude, ChatGPT, Codex, Cursor, VS Code and Gemini CLI.
|
|
5
|
+
Project-URL: Homepage, https://github.com/padge01/bestpred-python
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Keywords: ai agents,best prediction,dairy,dhi,lactation,mcp
|
|
8
|
+
Classifier: Intended Audience :: Science/Research
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Requires-Dist: bestpred>=0.2.1
|
|
13
|
+
Requires-Dist: mcp<3,>=2.3
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# bestpred-mcp
|
|
17
|
+
|
|
18
|
+
<!-- mcp-name: io.github.padge01/bestpred -->
|
|
19
|
+
|
|
20
|
+
USDA's best prediction of dairy lactation yields ([bestpred](https://github.com/padge01/bestpred-python), the
|
|
21
|
+
Python port of BESTPRED 2.0rc7) as tools any AI agent can call. An agent can't work out a lactation record in its head;
|
|
22
|
+
with this it runs the method USDA uses for official records, and reports the numbers it gets back.
|
|
23
|
+
|
|
24
|
+
It is an MCP server. MCP is the open standard agents use for tools, so the same server works in Claude, ChatGPT and
|
|
25
|
+
Codex, Cursor, VS Code and Gemini CLI.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
You need [uv](https://docs.astral.sh/uv/) (it runs the server; nothing else to install).
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
uvx bestpred-mcp
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- **Claude Code:** `claude mcp add bestpred -- uvx bestpred-mcp`
|
|
36
|
+
- **Claude Desktop, Cursor, Gemini CLI:** add to the app's MCP settings file:
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{ "mcpServers": { "bestpred": { "command": "uvx", "args": ["bestpred-mcp"] } } }
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
- **VS Code** (`.vscode/mcp.json`): `{ "servers": { "bestpred": { "command": "uvx", "args": ["bestpred-mcp"] } } }`
|
|
43
|
+
- **Codex plugin** (with the skill): `codex plugin marketplace add padge01/bestpred-python`, then install BESTPRED from
|
|
44
|
+
the Plugins tab.
|
|
45
|
+
- **Codex, the server alone** (`~/.codex/config.toml`):
|
|
46
|
+
|
|
47
|
+
```toml
|
|
48
|
+
[mcp_servers.bestpred]
|
|
49
|
+
command = "uvx"
|
|
50
|
+
args = ["bestpred-mcp"]
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Then ask your agent, for example: "Work out 305-day milk for every cow in `tests.csv`".
|
|
54
|
+
|
|
55
|
+
## The tools
|
|
56
|
+
|
|
57
|
+
| Tool | What it does |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `herd_lactations` | A herd's test-day export (CSV, one row per cow per test) to a record for every lactation: a summary by parity, the least persistent cows, and the full table written to a new file beside the input. Columns are matched loosely: `ID`, `LACT`, `FDAT`, `DIM` (or `TDAT`), `MILK`, `PCTF`, `PCTP`, `SCS`; `AGE` in months adds mature equivalent. |
|
|
60
|
+
| `lactation` | One cow's test days to 305-day and 365-day milk, fat and protein, mature equivalent (with her age), reliability, persistency and data collection rating. |
|
|
61
|
+
| `expected_curve` | A cow's expected daily milk to day 305 from her test days, to compare with what she is giving. |
|
|
62
|
+
| `mature_equivalent_factors` | USDA's age factors for a breed, age at calving, calving month, parity, state and previous days open. |
|
|
63
|
+
|
|
64
|
+
Pounds by default; pass `units: "kg"` for kilograms. With no herd average given, the breed average is used.
|
|
65
|
+
|
|
66
|
+
## What stays on your computer
|
|
67
|
+
|
|
68
|
+
Run this way, the server runs on your computer: your files are read there and the table is written there. What your
|
|
69
|
+
agent shows the AI model (the summary it reads back) goes to that model's company, as everything in a chat does.
|
|
70
|
+
|
|
71
|
+
`bestpred-mcp --http` serves the same tools over HTTP for hosting. Hosted, it reads no files, keeps nothing, and takes
|
|
72
|
+
at most 5,000 lactations a call.
|
|
73
|
+
|
|
74
|
+
## Licence
|
|
75
|
+
|
|
76
|
+
Apache-2.0. BESTPRED is USDA-ARS public-domain work (VanRaden; Cole and VanRaden); this is not affiliated with or
|
|
77
|
+
endorsed by USDA. See the main repository's NOTICE.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# bestpred-mcp
|
|
2
|
+
|
|
3
|
+
<!-- mcp-name: io.github.padge01/bestpred -->
|
|
4
|
+
|
|
5
|
+
USDA's best prediction of dairy lactation yields ([bestpred](https://github.com/padge01/bestpred-python), the
|
|
6
|
+
Python port of BESTPRED 2.0rc7) as tools any AI agent can call. An agent can't work out a lactation record in its head;
|
|
7
|
+
with this it runs the method USDA uses for official records, and reports the numbers it gets back.
|
|
8
|
+
|
|
9
|
+
It is an MCP server. MCP is the open standard agents use for tools, so the same server works in Claude, ChatGPT and
|
|
10
|
+
Codex, Cursor, VS Code and Gemini CLI.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
You need [uv](https://docs.astral.sh/uv/) (it runs the server; nothing else to install).
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
uvx bestpred-mcp
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- **Claude Code:** `claude mcp add bestpred -- uvx bestpred-mcp`
|
|
21
|
+
- **Claude Desktop, Cursor, Gemini CLI:** add to the app's MCP settings file:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{ "mcpServers": { "bestpred": { "command": "uvx", "args": ["bestpred-mcp"] } } }
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- **VS Code** (`.vscode/mcp.json`): `{ "servers": { "bestpred": { "command": "uvx", "args": ["bestpred-mcp"] } } }`
|
|
28
|
+
- **Codex plugin** (with the skill): `codex plugin marketplace add padge01/bestpred-python`, then install BESTPRED from
|
|
29
|
+
the Plugins tab.
|
|
30
|
+
- **Codex, the server alone** (`~/.codex/config.toml`):
|
|
31
|
+
|
|
32
|
+
```toml
|
|
33
|
+
[mcp_servers.bestpred]
|
|
34
|
+
command = "uvx"
|
|
35
|
+
args = ["bestpred-mcp"]
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Then ask your agent, for example: "Work out 305-day milk for every cow in `tests.csv`".
|
|
39
|
+
|
|
40
|
+
## The tools
|
|
41
|
+
|
|
42
|
+
| Tool | What it does |
|
|
43
|
+
|---|---|
|
|
44
|
+
| `herd_lactations` | A herd's test-day export (CSV, one row per cow per test) to a record for every lactation: a summary by parity, the least persistent cows, and the full table written to a new file beside the input. Columns are matched loosely: `ID`, `LACT`, `FDAT`, `DIM` (or `TDAT`), `MILK`, `PCTF`, `PCTP`, `SCS`; `AGE` in months adds mature equivalent. |
|
|
45
|
+
| `lactation` | One cow's test days to 305-day and 365-day milk, fat and protein, mature equivalent (with her age), reliability, persistency and data collection rating. |
|
|
46
|
+
| `expected_curve` | A cow's expected daily milk to day 305 from her test days, to compare with what she is giving. |
|
|
47
|
+
| `mature_equivalent_factors` | USDA's age factors for a breed, age at calving, calving month, parity, state and previous days open. |
|
|
48
|
+
|
|
49
|
+
Pounds by default; pass `units: "kg"` for kilograms. With no herd average given, the breed average is used.
|
|
50
|
+
|
|
51
|
+
## What stays on your computer
|
|
52
|
+
|
|
53
|
+
Run this way, the server runs on your computer: your files are read there and the table is written there. What your
|
|
54
|
+
agent shows the AI model (the summary it reads back) goes to that model's company, as everything in a chat does.
|
|
55
|
+
|
|
56
|
+
`bestpred-mcp --http` serves the same tools over HTTP for hosting. Hosted, it reads no files, keeps nothing, and takes
|
|
57
|
+
at most 5,000 lactations a call.
|
|
58
|
+
|
|
59
|
+
## Licence
|
|
60
|
+
|
|
61
|
+
Apache-2.0. BESTPRED is USDA-ARS public-domain work (VanRaden; Cole and VanRaden); this is not affiliated with or
|
|
62
|
+
endorsed by USDA. See the main repository's NOTICE.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bestpred-mcp"
|
|
3
|
+
version = "0.2.1"
|
|
4
|
+
description = "USDA's best prediction of dairy lactation yields (BESTPRED) as tools any AI agent can call: an MCP server for Claude, ChatGPT, Codex, Cursor, VS Code and Gemini CLI."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
dependencies = ["bestpred>=0.2.1", "mcp>=2.3,<3"]
|
|
9
|
+
keywords = ["dairy", "lactation", "best prediction", "dhi", "mcp", "ai agents"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Programming Language :: Python :: 3",
|
|
12
|
+
"Topic :: Scientific/Engineering",
|
|
13
|
+
"Intended Audience :: Science/Research",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
bestpred-mcp = "bestpred_mcp.__main__:main"
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/padge01/bestpred-python"
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["hatchling"]
|
|
24
|
+
build-backend = "hatchling.build"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/bestpred_mcp"]
|
|
28
|
+
|
|
29
|
+
[tool.uv.sources]
|
|
30
|
+
bestpred = { workspace = true }
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""bestpred-mcp: run the server over stdio for an agent on this computer, or over HTTP to host it."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main(argv=None) -> int:
|
|
8
|
+
ap = argparse.ArgumentParser(prog='bestpred-mcp', description=__doc__)
|
|
9
|
+
ap.add_argument('--http', action='store_true',
|
|
10
|
+
help='serve it hosted: /mcp plus its pages, no file paths, capped input, nothing kept ($PORT wins)')
|
|
11
|
+
ap.add_argument('--host', default='127.0.0.1')
|
|
12
|
+
ap.add_argument('--port', type=int, default=8000)
|
|
13
|
+
args = ap.parse_args(argv)
|
|
14
|
+
from .server import build_server
|
|
15
|
+
|
|
16
|
+
if args.http:
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
import uvicorn
|
|
20
|
+
|
|
21
|
+
from .hosted import hosted_app
|
|
22
|
+
|
|
23
|
+
hosts = [h.strip() for h in os.environ.get('BESTPRED_ALLOWED_HOSTS', '').split(',') if h.strip()]
|
|
24
|
+
uvicorn.run(hosted_app(hosts), host=args.host, port=int(os.environ.get('PORT', args.port)),
|
|
25
|
+
proxy_headers=True, forwarded_allow_ips='*')
|
|
26
|
+
else:
|
|
27
|
+
build_server(hosted=False).run(transport='stdio')
|
|
28
|
+
return 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == '__main__':
|
|
32
|
+
sys.exit(main())
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Turn the inputs an agent has (a cow's test days, or a herd's test-day export) into bestpred calls, and the results
|
|
2
|
+
into short summaries. Nothing here is a new calculation: every figure comes from bestpred()."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import csv
|
|
7
|
+
import io
|
|
8
|
+
import statistics
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
|
|
12
|
+
from bestpred import Settings, TestDay, age_factors, bestpred
|
|
13
|
+
|
|
14
|
+
# USDA's 2-digit state codes (BESTPRED's ClimateRegions file), by postal code.
|
|
15
|
+
STATES = {
|
|
16
|
+
'ME': 11, 'NH': 12, 'VT': 13, 'MA': 14, 'RI': 15, 'CT': 16, 'NY': 21, 'NJ': 22, 'PA': 23, 'OH': 31, 'IN': 32,
|
|
17
|
+
'IL': 33, 'MI': 34, 'WI': 35, 'MN': 41, 'IA': 42, 'MO': 43, 'ND': 45, 'SD': 46, 'NE': 47, 'KS': 48, 'DE': 50,
|
|
18
|
+
'MD': 51, 'VA': 52, 'WV': 54, 'NC': 55, 'SC': 56, 'GA': 57, 'FL': 58, 'KY': 61, 'TN': 63, 'AL': 64, 'MS': 65,
|
|
19
|
+
'AR': 71, 'LA': 72, 'OK': 73, 'TX': 74, 'MT': 81, 'ID': 82, 'WY': 83, 'CO': 84, 'NM': 85, 'AZ': 86, 'UT': 87,
|
|
20
|
+
'NV': 88, 'WA': 91, 'OR': 92, 'CA': 93, 'PR': 94, 'HI': 95, 'AK': 96,
|
|
21
|
+
}
|
|
22
|
+
BREEDS = {'A': 'Ayrshire', 'B': 'Brown Swiss', 'G': 'Guernsey', 'H': 'Holstein', 'J': 'Jersey', 'M': 'Milking Shorthorn'}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class InputProblem(ValueError):
|
|
26
|
+
"""Something in the input the agent should fix; the message says what."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def state_code(state: str | int | None) -> int:
|
|
30
|
+
"""A state as USDA's 2-digit code, from a postal code ('CA') or the code itself (93). 0 when not given."""
|
|
31
|
+
if state is None or state == '':
|
|
32
|
+
return 0
|
|
33
|
+
text = str(state).strip().upper()
|
|
34
|
+
if text.isdigit():
|
|
35
|
+
code = int(text)
|
|
36
|
+
if not 0 <= code <= 96:
|
|
37
|
+
raise InputProblem(f'State code {code} is outside USDA\'s table (0-96).')
|
|
38
|
+
return code
|
|
39
|
+
if text in STATES:
|
|
40
|
+
return STATES[text]
|
|
41
|
+
raise InputProblem(f"Unknown state '{state}'. Give a 2-letter postal code (CA, WI, ...) or USDA's 2-digit code.")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parse_date(text: str) -> date:
|
|
45
|
+
"""A calving or test date as YYYY-MM-DD, YYYYMMDD, MM/DD/YY or MM/DD/YYYY (DairyComp writes MM/DD/YY)."""
|
|
46
|
+
t = str(text).strip()
|
|
47
|
+
for fmt in ('%Y-%m-%d', '%Y%m%d', '%m/%d/%y', '%m/%d/%Y'):
|
|
48
|
+
try:
|
|
49
|
+
return datetime.strptime(t, fmt).date()
|
|
50
|
+
except ValueError:
|
|
51
|
+
continue
|
|
52
|
+
raise InputProblem(f"Can't read the date '{text}'. Use YYYY-MM-DD or MM/DD/YY.")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def breed_letter(breed: str | None) -> str:
|
|
56
|
+
b = (breed or 'H').strip().upper()[:1]
|
|
57
|
+
if b not in BREEDS:
|
|
58
|
+
raise InputProblem(f"Unknown breed '{breed}'. Use one of {', '.join(f'{k} ({v})' for k, v in BREEDS.items())}.")
|
|
59
|
+
return b
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Lactation:
|
|
64
|
+
"""One cow's lactation as bestpred needs it."""
|
|
65
|
+
|
|
66
|
+
cow: str
|
|
67
|
+
parity: int
|
|
68
|
+
fresh: date
|
|
69
|
+
tests: list[TestDay]
|
|
70
|
+
breed: str = 'H'
|
|
71
|
+
age_months: int | None = None
|
|
72
|
+
prev_days_open: int = 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def settings(units: str) -> Settings:
|
|
76
|
+
u = units.strip().lower()
|
|
77
|
+
if u not in ('lb', 'kg'):
|
|
78
|
+
raise InputProblem("Units must be 'lb' or 'kg'.")
|
|
79
|
+
p = 'P' if u == 'lb' else 'K'
|
|
80
|
+
return Settings(units_in=p, units_out=p)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run(lac: Lactation, herd_avg: tuple[float, float, float, float], units: str, state: int):
|
|
84
|
+
"""bestpred() for one lactation, with USDA's mature-equivalent factors when the cow's age and state are known."""
|
|
85
|
+
if not lac.tests:
|
|
86
|
+
raise InputProblem(f'Cow {lac.cow} has no usable test days (each needs days in milk above 0 and milk above 0).')
|
|
87
|
+
if lac.parity < 1:
|
|
88
|
+
raise InputProblem(f'Cow {lac.cow}: parity must be 1 or more.')
|
|
89
|
+
# USDA's age factors need the state (its region) as well as the age; without both, actual yields only.
|
|
90
|
+
me_known = lac.age_months is not None and state > 0
|
|
91
|
+
if me_known:
|
|
92
|
+
agefac = age_factors(lac.breed, int(lac.age_months), lac.fresh.year, lac.fresh.month, lac.parity, state,
|
|
93
|
+
int(lac.prev_days_open))
|
|
94
|
+
else:
|
|
95
|
+
agefac = (1.0, 1.0, 1.0, 1.0)
|
|
96
|
+
res = bestpred(lac.tests, herdavg=herd_avg, agefac=agefac, cowid=lac.breed, fresh=lac.fresh.strftime('%Y%m%d'),
|
|
97
|
+
parity=lac.parity, herdstate=f'{state:02d}', settings=settings(units))
|
|
98
|
+
return res, me_known
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def summary(lac: Lactation, res, me_known: bool, units: str) -> dict:
|
|
102
|
+
"""The figures an agent should report, rounded as a DHI sheet shows them."""
|
|
103
|
+
act, me = res.yields('actual'), res.yields('me')
|
|
104
|
+
out = {
|
|
105
|
+
'cow': lac.cow, 'parity': lac.parity, 'fresh': lac.fresh.isoformat(), 'tests': int(res.ntests[0]),
|
|
106
|
+
'last_test_dim': max(t.dim for t in lac.tests), 'units': units,
|
|
107
|
+
'milk_305': round(act['milk']['305']), 'fat_305': round(act['fat']['305']),
|
|
108
|
+
'protein_305': round(act['protein']['305']), 'milk_365': round(act['milk']['365']),
|
|
109
|
+
'milk_to_date': round(act['milk']['to_date']),
|
|
110
|
+
'reliability_milk_pct': round(100 * float(res.rel_yield[0])),
|
|
111
|
+
'persistency_milk': round(float(res.persistency[0]), 2),
|
|
112
|
+
'data_collection_rating': round(float(res.dcr_milk)),
|
|
113
|
+
}
|
|
114
|
+
if me_known:
|
|
115
|
+
out.update({'milk_305_me': round(me['milk']['305']), 'fat_305_me': round(me['fat']['305']),
|
|
116
|
+
'protein_305_me': round(me['protein']['305'])})
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def curve(res, every: int = 7, through: int = 305) -> list[dict]:
|
|
121
|
+
"""The cow's expected daily milk (actual basis): her herd curve plus her own deviation, every `every` days."""
|
|
122
|
+
herd, own = res.daily_herd[1, 0], res.daily_bp[1, 0]
|
|
123
|
+
return [{'dim': d, 'milk': round(float(herd[d] + own[d]), 1)} for d in range(every, through + 1, every)]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# A herd's test-day export: one row per cow per test. Column names are matched loosely, as DHI and DairyComp exports
|
|
127
|
+
# name them differently.
|
|
128
|
+
COLUMNS = {
|
|
129
|
+
'cow': ('cow', 'id', 'cowid', 'cow_id', 'animal'),
|
|
130
|
+
'parity': ('parity', 'lact', 'lactation', 'lacno'),
|
|
131
|
+
'fresh': ('fresh', 'fdat', 'fresh_date', 'calving', 'calving_date'),
|
|
132
|
+
'dim': ('dim', 'days_in_milk'),
|
|
133
|
+
'test_date': ('test_date', 'tdat', 'date'),
|
|
134
|
+
'milk': ('milk', 'milk_lb', 'milk_kg'),
|
|
135
|
+
'fat': ('fat', 'fat_pct', 'pctf', 'fat%'),
|
|
136
|
+
'protein': ('protein', 'protein_pct', 'pctp', 'prot', 'protein%'),
|
|
137
|
+
'scs': ('scs', 'linear_score', 'ls'),
|
|
138
|
+
'breed': ('breed', 'cbrd'),
|
|
139
|
+
'age_months': ('age_months', 'age'),
|
|
140
|
+
'prev_days_open': ('prev_days_open', 'pdopn', 'previous_days_open'),
|
|
141
|
+
}
|
|
142
|
+
NEEDED = ('cow', 'parity', 'fresh', 'milk')
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _header_map(fields: list[str]) -> dict[str, str]:
|
|
146
|
+
norm = {f.strip().lower().replace(' ', '_'): f for f in fields if f}
|
|
147
|
+
found = {}
|
|
148
|
+
for key, names in COLUMNS.items():
|
|
149
|
+
for n in names:
|
|
150
|
+
if n in norm:
|
|
151
|
+
found[key] = norm[n]
|
|
152
|
+
break
|
|
153
|
+
missing = [k for k in NEEDED if k not in found]
|
|
154
|
+
if 'dim' not in found and 'test_date' not in found:
|
|
155
|
+
missing.append('dim (or test_date)')
|
|
156
|
+
if missing:
|
|
157
|
+
raise InputProblem(f"The test-day file needs columns for: {', '.join(missing)}. Found: {', '.join(fields)}.")
|
|
158
|
+
return found
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _num(row: dict, col: str | None, default: float = 0.0) -> float:
|
|
162
|
+
if not col:
|
|
163
|
+
return default
|
|
164
|
+
v = (row.get(col) or '').strip()
|
|
165
|
+
if not v:
|
|
166
|
+
return default
|
|
167
|
+
try:
|
|
168
|
+
return float(v)
|
|
169
|
+
except ValueError:
|
|
170
|
+
return default
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def read_herd(text: str) -> tuple[list[Lactation], int]:
|
|
174
|
+
"""Group a test-day CSV into lactations (cow, parity, fresh date). Returns them and the count of rows skipped."""
|
|
175
|
+
reader = csv.DictReader(io.StringIO(text.lstrip('')))
|
|
176
|
+
cols = _header_map(reader.fieldnames or [])
|
|
177
|
+
groups: dict[tuple, Lactation] = {}
|
|
178
|
+
skipped = 0
|
|
179
|
+
for row in reader:
|
|
180
|
+
cow = (row.get(cols['cow']) or '').strip()
|
|
181
|
+
if not cow:
|
|
182
|
+
skipped += 1
|
|
183
|
+
continue
|
|
184
|
+
try:
|
|
185
|
+
fresh = parse_date(row[cols['fresh']])
|
|
186
|
+
parity = int(_num(row, cols['parity']))
|
|
187
|
+
except (InputProblem, KeyError):
|
|
188
|
+
skipped += 1
|
|
189
|
+
continue
|
|
190
|
+
if 'dim' in cols:
|
|
191
|
+
dim = int(_num(row, cols['dim']))
|
|
192
|
+
else:
|
|
193
|
+
try:
|
|
194
|
+
dim = (parse_date(row[cols['test_date']]) - fresh).days
|
|
195
|
+
except InputProblem:
|
|
196
|
+
skipped += 1
|
|
197
|
+
continue
|
|
198
|
+
milk = _num(row, cols['milk'])
|
|
199
|
+
if dim <= 0 or milk <= 0 or parity < 1:
|
|
200
|
+
skipped += 1
|
|
201
|
+
continue
|
|
202
|
+
key = (cow, parity, fresh)
|
|
203
|
+
if key not in groups:
|
|
204
|
+
age = row.get(cols.get('age_months', ''), '') if 'age_months' in cols else ''
|
|
205
|
+
groups[key] = Lactation(cow=cow, parity=parity, fresh=fresh, tests=[],
|
|
206
|
+
breed=breed_letter(row.get(cols['breed']) if 'breed' in cols else 'H'),
|
|
207
|
+
age_months=int(float(age)) if str(age).strip() else None,
|
|
208
|
+
prev_days_open=int(_num(row, cols.get('prev_days_open'))))
|
|
209
|
+
groups[key].tests.append(TestDay(dim=dim, milk=milk, fat=_num(row, cols.get('fat')),
|
|
210
|
+
protein=_num(row, cols.get('protein')), scs=_num(row, cols.get('scs'))))
|
|
211
|
+
lacs = list(groups.values())
|
|
212
|
+
for lac in lacs:
|
|
213
|
+
lac.tests.sort(key=lambda t: t.dim)
|
|
214
|
+
return lacs, skipped
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def herd_summary(rows: list[dict]) -> dict:
|
|
218
|
+
"""By parity group (1, 2, 3 and later): cows, median 305-day milk, reliability and persistency; the five cows with the
|
|
219
|
+
least persistent lactations."""
|
|
220
|
+
groups = {}
|
|
221
|
+
for label, test in (('1', lambda p: p == 1), ('2', lambda p: p == 2), ('3+', lambda p: p >= 3)):
|
|
222
|
+
g = [r for r in rows if test(r['parity'])]
|
|
223
|
+
if g:
|
|
224
|
+
groups[label] = {
|
|
225
|
+
'lactations': len(g),
|
|
226
|
+
'median_milk_305': round(statistics.median(r['milk_305'] for r in g)),
|
|
227
|
+
'median_reliability_pct': round(statistics.median(r['reliability_milk_pct'] for r in g)),
|
|
228
|
+
'median_persistency': round(statistics.median(r['persistency_milk'] for r in g), 2),
|
|
229
|
+
}
|
|
230
|
+
least = sorted(rows, key=lambda r: r['persistency_milk'])[:5]
|
|
231
|
+
return {'by_parity': groups,
|
|
232
|
+
'least_persistent': [{'cow': r['cow'], 'parity': r['parity'], 'persistency_milk': r['persistency_milk']}
|
|
233
|
+
for r in least]}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def rows_to_csv(rows: list[dict]) -> str:
|
|
237
|
+
keys: list[str] = []
|
|
238
|
+
for r in rows:
|
|
239
|
+
keys += [k for k in r if k not in keys]
|
|
240
|
+
buf = io.StringIO()
|
|
241
|
+
w = csv.DictWriter(buf, fieldnames=keys, lineterminator='\n')
|
|
242
|
+
w.writeheader()
|
|
243
|
+
w.writerows(rows)
|
|
244
|
+
return buf.getvalue()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""The server as a hosted web service: the MCP endpoint at /mcp, and the pages the Claude and OpenAI directories ask
|
|
2
|
+
for (what it is, privacy, llms.txt, OpenAI's domain check). Stateless: every call computes and forgets."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from mcp.server.transport_security import TransportSecuritySettings
|
|
9
|
+
from starlette.applications import Starlette
|
|
10
|
+
from starlette.requests import Request
|
|
11
|
+
from starlette.responses import HTMLResponse, PlainTextResponse, Response
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .server import HOSTED_MAX_LACTATIONS, build_server
|
|
15
|
+
|
|
16
|
+
MAX_BODY = 5 * 1024 * 1024
|
|
17
|
+
SOURCE = 'https://github.com/padge01/bestpred-python'
|
|
18
|
+
ISSUES = SOURCE + '/issues'
|
|
19
|
+
|
|
20
|
+
PAGE = f"""<!doctype html><html lang="en"><meta charset="utf-8">
|
|
21
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"><title>BESTPRED for agents</title>
|
|
22
|
+
<style>body{{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#1a1a1a}}
|
|
23
|
+
code{{background:#f2f2f0;padding:.1em .3em;border-radius:4px}}</style>
|
|
24
|
+
<h1>BESTPRED for agents</h1>
|
|
25
|
+
<p>USDA's best prediction of dairy lactation yields (BESTPRED 2.0rc7, ported to Python and checked against USDA's own
|
|
26
|
+
program), as tools an AI agent can call: 305-day and mature-equivalent milk, fat and protein, reliability and
|
|
27
|
+
persistency from a cow's or a herd's test days.</p>
|
|
28
|
+
<p>MCP endpoint: <code>/mcp</code> (streamable HTTP, no sign-in). Tools: <code>herd_lactations</code>,
|
|
29
|
+
<code>lactation</code>, <code>expected_curve</code>, <code>mature_equivalent_factors</code>.</p>
|
|
30
|
+
<p>To keep your test days on your own computer, run it there instead: <code>uvx bestpred-mcp</code>.</p>
|
|
31
|
+
<p><a href="/privacy">Privacy</a> · <a href="{SOURCE}">Source and install lines</a> · <a href="{ISSUES}">Support</a>
|
|
32
|
+
· version {__version__}</p></html>"""
|
|
33
|
+
|
|
34
|
+
PRIVACY = f"""Privacy: BESTPRED for agents (hosted)
|
|
35
|
+
|
|
36
|
+
What is sent: the test days your agent sends with a tool call (days in milk, milk, fat %, protein %, somatic cell score,
|
|
37
|
+
parity, calving date, and optionally cow IDs, breed, age and state), and the request's ordinary network details.
|
|
38
|
+
|
|
39
|
+
How it is used: only to compute the records you asked for, in memory, during that call. The answer goes back to your
|
|
40
|
+
agent.
|
|
41
|
+
|
|
42
|
+
What is kept: nothing. Test days and results are not written to disk, logged or kept after the call. The hosting
|
|
43
|
+
provider keeps standard request logs (time, size, status), not the request's contents.
|
|
44
|
+
|
|
45
|
+
Shared with: no one. No third parties, no analytics, no advertising, no training.
|
|
46
|
+
|
|
47
|
+
Limits: at most {HOSTED_MAX_LACTATIONS:,} lactations and 5 MB a call.
|
|
48
|
+
|
|
49
|
+
To keep your data on your own computer entirely, run the same tools locally: uvx bestpred-mcp
|
|
50
|
+
|
|
51
|
+
Contact: {ISSUES}
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
LLMS = """# BESTPRED for agents (hosted)
|
|
55
|
+
|
|
56
|
+
> USDA's best prediction of dairy lactation yields as MCP tools. Endpoint: /mcp (streamable HTTP, no sign-in).
|
|
57
|
+
|
|
58
|
+
- herd_lactations: a herd's test-day CSV (csv_text; ID, LACT, FDAT, DIM or TDAT, MILK, PCTF, PCTP, SCS, AGE) to a
|
|
59
|
+
record per lactation, a summary by parity and the least persistent cows
|
|
60
|
+
- lactation: one cow's test days to her record
|
|
61
|
+
- expected_curve: a cow's expected daily milk to day 305
|
|
62
|
+
- mature_equivalent_factors: USDA's age factors
|
|
63
|
+
|
|
64
|
+
Report the numbers the tools return as they are; never estimate a lactation record. Run locally instead: uvx bestpred-mcp
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def hosted_app(allowed_hosts: list[str] | None = None) -> Starlette:
|
|
69
|
+
"""The hosted service. `allowed_hosts` (e.g. ['bestpred.example.com']) turns on the Host header check; behind a
|
|
70
|
+
proxy that already checks it, leave it empty."""
|
|
71
|
+
mcp = build_server(hosted=True)
|
|
72
|
+
|
|
73
|
+
@mcp.custom_route('/', methods=['GET'])
|
|
74
|
+
async def home(_: Request) -> Response:
|
|
75
|
+
return HTMLResponse(PAGE)
|
|
76
|
+
|
|
77
|
+
@mcp.custom_route('/privacy', methods=['GET'])
|
|
78
|
+
async def privacy(_: Request) -> Response:
|
|
79
|
+
return PlainTextResponse(PRIVACY)
|
|
80
|
+
|
|
81
|
+
@mcp.custom_route('/llms.txt', methods=['GET'])
|
|
82
|
+
async def llms(_: Request) -> Response:
|
|
83
|
+
return PlainTextResponse(LLMS)
|
|
84
|
+
|
|
85
|
+
@mcp.custom_route('/.well-known/openai-apps-challenge', methods=['GET'])
|
|
86
|
+
async def challenge(_: Request) -> Response:
|
|
87
|
+
token = os.environ.get('OPENAI_APPS_CHALLENGE', '').strip()
|
|
88
|
+
return PlainTextResponse(token) if token else PlainTextResponse('', status_code=404)
|
|
89
|
+
|
|
90
|
+
security = TransportSecuritySettings(enable_dns_rebinding_protection=bool(allowed_hosts),
|
|
91
|
+
allowed_hosts=list(allowed_hosts or []))
|
|
92
|
+
return mcp.streamable_http_app(json_response=True, stateless_http=True, max_request_body_size=MAX_BODY,
|
|
93
|
+
transport_security=security, host='0.0.0.0')
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""BESTPRED for agents: USDA's best prediction of lactation yields as MCP tools any agent can call.
|
|
2
|
+
|
|
3
|
+
Run on your own computer over stdio (`bestpred-mcp`), or hosted over streamable HTTP (`bestpred-mcp --http`). Hosted,
|
|
4
|
+
it computes only on what it is sent, keeps nothing and reads no files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Annotated
|
|
11
|
+
|
|
12
|
+
from mcp.server.mcpserver import MCPServer
|
|
13
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
14
|
+
from mcp.types import ToolAnnotations
|
|
15
|
+
from pydantic import BaseModel, Field
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .herd import (InputProblem, Lactation, breed_letter, curve, herd_summary, parse_date, read_herd, rows_to_csv, run,
|
|
19
|
+
state_code, summary)
|
|
20
|
+
from bestpred import TestDay, age_factors
|
|
21
|
+
|
|
22
|
+
REPORT = (' Report these numbers as they are: they come from USDA\'s best prediction method (BESTPRED 2.0rc7), checked '
|
|
23
|
+
'against USDA\'s own program. Never estimate a lactation yourself.')
|
|
24
|
+
INSTRUCTIONS = (
|
|
25
|
+
"USDA's best prediction (BESTPRED) of dairy lactation yields: 305-day and 365-day milk, fat and protein, mature "
|
|
26
|
+
'equivalent when the age is known, reliability and persistency, from a cow\'s test days. Use herd_lactations for a '
|
|
27
|
+
"herd's test-day export, lactation for one cow, expected_curve for a cow's expected daily milk, and "
|
|
28
|
+
'mature_equivalent_factors for USDA\'s age factors. Pounds unless the user works in kilograms.' + REPORT
|
|
29
|
+
)
|
|
30
|
+
READ_ONLY = dict(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
|
|
31
|
+
# Local herd_lactations writes its table to a new file and never overwrites one.
|
|
32
|
+
WRITES_NEW_FILE = dict(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)
|
|
33
|
+
HOSTED_MAX_LACTATIONS = 5000
|
|
34
|
+
HOSTED_TABLE_ROWS = 300
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MilkTest(BaseModel):
|
|
38
|
+
"""One test day."""
|
|
39
|
+
|
|
40
|
+
dim: int = Field(description='Days in milk on the test day')
|
|
41
|
+
milk: float = Field(description='Milk that day, lb (or kg)')
|
|
42
|
+
fat: float = Field(0.0, description='Fat %, 0 if not tested')
|
|
43
|
+
protein: float = Field(0.0, description='Protein %, 0 if not tested')
|
|
44
|
+
scs: float = Field(0.0, description='Somatic cell score (linear score, 0-9.9), 0 if not tested')
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
HerdAverage = Annotated[float, Field(description="The herd's 305-day mature-equivalent average; 0 if unknown (the "
|
|
48
|
+
'breed average is used)')]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _lactation(tests: list[MilkTest], parity: int, fresh: str, breed: str, age_months: int | None,
|
|
52
|
+
prev_days_open: int) -> Lactation:
|
|
53
|
+
usable = [TestDay(dim=t.dim, milk=t.milk, fat=t.fat, protein=t.protein, scs=t.scs) for t in tests
|
|
54
|
+
if t.dim > 0 and t.milk > 0]
|
|
55
|
+
return Lactation(cow='this cow', parity=parity, fresh=parse_date(fresh), tests=sorted(usable, key=lambda t: t.dim),
|
|
56
|
+
breed=breed_letter(breed), age_months=age_months, prev_days_open=prev_days_open)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _new_file(path: Path) -> Path:
|
|
60
|
+
"""`path`, or the same name with -2, -3 ... when a file is already there: an existing file is never replaced."""
|
|
61
|
+
n, candidate = 2, path
|
|
62
|
+
while candidate.exists():
|
|
63
|
+
candidate = path.with_name(f'{path.stem}-{n}{path.suffix}')
|
|
64
|
+
n += 1
|
|
65
|
+
return candidate
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def build_server(hosted: bool = False) -> MCPServer:
|
|
69
|
+
"""The server. `hosted` drops the file path inputs and caps what one call may send."""
|
|
70
|
+
mcp = MCPServer('bestpred', title='BESTPRED lactation records', instructions=INSTRUCTIONS, version=__version__,
|
|
71
|
+
website_url='https://github.com/padge01/bestpred-python')
|
|
72
|
+
|
|
73
|
+
@mcp.tool(title='One cow\'s lactation record', annotations=ToolAnnotations(**READ_ONLY),
|
|
74
|
+
description='Best prediction for one cow from her test days: 305-day and 365-day milk, fat and protein '
|
|
75
|
+
'(and mature equivalent when age_months is given), reliability, persistency and data '
|
|
76
|
+
'collection rating.' + REPORT)
|
|
77
|
+
def lactation(tests: list[MilkTest], parity: int, fresh: str, breed: str = 'H', age_months: int | None = None,
|
|
78
|
+
prev_days_open: int = 0, state: str = '', herd_milk: HerdAverage = 0, herd_fat: HerdAverage = 0,
|
|
79
|
+
herd_protein: HerdAverage = 0, herd_scs: HerdAverage = 0, units: str = 'lb') -> dict:
|
|
80
|
+
try:
|
|
81
|
+
lac = _lactation(tests, parity, fresh, breed, age_months, prev_days_open)
|
|
82
|
+
res, me_known = run(lac, (herd_milk, herd_fat, herd_protein, herd_scs), units, state_code(state))
|
|
83
|
+
except (InputProblem, ValueError) as e:
|
|
84
|
+
raise ToolError(str(e)) from e
|
|
85
|
+
out = summary(lac, res, me_known, units)
|
|
86
|
+
out.pop('cow')
|
|
87
|
+
if not me_known:
|
|
88
|
+
out['note'] = 'Mature equivalent not given: it needs age_months and state.'
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
@mcp.tool(title='A cow\'s expected daily milk', annotations=ToolAnnotations(**READ_ONLY),
|
|
92
|
+
description='A cow\'s expected daily milk to day 305 from her test days (her herd curve plus her own '
|
|
93
|
+
'deviation), one point every `every` days, to compare with what she is giving.' + REPORT)
|
|
94
|
+
def expected_curve(tests: list[MilkTest], parity: int, fresh: str, breed: str = 'H', every: int = 7,
|
|
95
|
+
herd_milk: HerdAverage = 0, units: str = 'lb') -> dict:
|
|
96
|
+
try:
|
|
97
|
+
lac = _lactation(tests, parity, fresh, breed, None, 0)
|
|
98
|
+
res, _ = run(lac, (herd_milk, 0, 0, 0), units, 0)
|
|
99
|
+
except (InputProblem, ValueError) as e:
|
|
100
|
+
raise ToolError(str(e)) from e
|
|
101
|
+
return {'units': units, 'points': curve(res, every=max(1, min(int(every), 30)))}
|
|
102
|
+
|
|
103
|
+
@mcp.tool(title='Mature-equivalent factors', annotations=ToolAnnotations(**READ_ONLY),
|
|
104
|
+
description="USDA's factors that turn a cow's actual 305-day milk, fat and protein into mature "
|
|
105
|
+
'equivalent, for her breed, age at calving, calving month, parity, state and previous days '
|
|
106
|
+
'open.' + REPORT)
|
|
107
|
+
def mature_equivalent_factors(age_months: int, fresh: str, parity: int, state: str, breed: str = 'H',
|
|
108
|
+
prev_days_open: int = 0) -> dict:
|
|
109
|
+
try:
|
|
110
|
+
d = parse_date(fresh)
|
|
111
|
+
f = age_factors(breed_letter(breed), int(age_months), d.year, d.month, parity, state_code(state),
|
|
112
|
+
int(prev_days_open))
|
|
113
|
+
except (InputProblem, ValueError) as e:
|
|
114
|
+
raise ToolError(str(e)) from e
|
|
115
|
+
return {'milk': round(float(f[0]), 4), 'fat': round(float(f[1]), 4), 'protein': round(float(f[2]), 4)}
|
|
116
|
+
|
|
117
|
+
herd_doc = ("Best prediction for every lactation in a herd's test-day export (CSV, one row per cow per test; DHI or "
|
|
118
|
+
'DairyComp columns such as ID, LACT, FDAT, DIM or TDAT, MILK, PCTF, PCTP, SCS; AGE in months adds '
|
|
119
|
+
'mature equivalent). Returns a summary by parity and the least persistent cows')
|
|
120
|
+
|
|
121
|
+
def herd(lacs: list[Lactation], skipped: int, herd_avg, units: str, state: int) -> tuple[list[dict], dict]:
|
|
122
|
+
rows, problems = [], []
|
|
123
|
+
for lac in lacs:
|
|
124
|
+
try:
|
|
125
|
+
res, me_known = run(lac, herd_avg, units, state)
|
|
126
|
+
rows.append(summary(lac, res, me_known, units))
|
|
127
|
+
except (InputProblem, ValueError) as e:
|
|
128
|
+
problems.append(f'{lac.cow}: {e}')
|
|
129
|
+
if not rows:
|
|
130
|
+
raise ToolError('No lactation could be computed. ' + ' '.join(problems[:3]))
|
|
131
|
+
out = {'lactations': len(rows), 'rows_skipped': skipped, 'units': units, **herd_summary(rows)}
|
|
132
|
+
if not state and any(lac.age_months is not None for lac in lacs):
|
|
133
|
+
out['note'] = 'Ages were given but no state: mature equivalent needs the state too.'
|
|
134
|
+
if problems:
|
|
135
|
+
out['not_computed'] = problems[:10]
|
|
136
|
+
return rows, out
|
|
137
|
+
|
|
138
|
+
if hosted:
|
|
139
|
+
@mcp.tool(title='A herd\'s lactation records', annotations=ToolAnnotations(**READ_ONLY),
|
|
140
|
+
description=herd_doc + '; with the full table when the herd is small.' + REPORT)
|
|
141
|
+
def herd_lactations(csv_text: str, state: str = '', herd_milk: HerdAverage = 0, herd_fat: HerdAverage = 0,
|
|
142
|
+
herd_protein: HerdAverage = 0, herd_scs: HerdAverage = 0, units: str = 'lb') -> dict:
|
|
143
|
+
try:
|
|
144
|
+
lacs, skipped = read_herd(csv_text)
|
|
145
|
+
if len(lacs) > HOSTED_MAX_LACTATIONS:
|
|
146
|
+
raise InputProblem(f'{len(lacs):,} lactations is more than the hosted limit of '
|
|
147
|
+
f'{HOSTED_MAX_LACTATIONS:,}. Install it locally: uvx bestpred-mcp')
|
|
148
|
+
rows, out = herd(lacs, skipped, (herd_milk, herd_fat, herd_protein, herd_scs), units,
|
|
149
|
+
state_code(state))
|
|
150
|
+
except (InputProblem, ValueError) as e:
|
|
151
|
+
raise ToolError(str(e)) from e
|
|
152
|
+
if len(rows) <= HOSTED_TABLE_ROWS:
|
|
153
|
+
out['table_csv'] = rows_to_csv(rows)
|
|
154
|
+
else:
|
|
155
|
+
out['table'] = f'{len(rows):,} rows: too many to send back here. Installed locally, it writes a file.'
|
|
156
|
+
return out
|
|
157
|
+
else:
|
|
158
|
+
@mcp.tool(title='A herd\'s lactation records', annotations=ToolAnnotations(**WRITES_NEW_FILE),
|
|
159
|
+
description=herd_doc + '; the full table is written to a new file beside the input (or `out_path`).'
|
|
160
|
+
+ ' Give `path` to a CSV on this computer, or `csv_text`.' + REPORT)
|
|
161
|
+
def herd_lactations(path: str = '', csv_text: str = '', out_path: str = '', state: str = '',
|
|
162
|
+
herd_milk: HerdAverage = 0, herd_fat: HerdAverage = 0, herd_protein: HerdAverage = 0,
|
|
163
|
+
herd_scs: HerdAverage = 0, units: str = 'lb') -> dict:
|
|
164
|
+
try:
|
|
165
|
+
if path:
|
|
166
|
+
src = Path(path).expanduser()
|
|
167
|
+
if not src.is_file():
|
|
168
|
+
raise InputProblem(f'No file at {src}.')
|
|
169
|
+
text = src.read_text(encoding='utf-8-sig', errors='replace')
|
|
170
|
+
elif csv_text:
|
|
171
|
+
src, text = None, csv_text
|
|
172
|
+
else:
|
|
173
|
+
raise InputProblem('Give `path` to a test-day CSV, or `csv_text`.')
|
|
174
|
+
lacs, skipped = read_herd(text)
|
|
175
|
+
rows, out = herd(lacs, skipped, (herd_milk, herd_fat, herd_protein, herd_scs), units,
|
|
176
|
+
state_code(state))
|
|
177
|
+
dest = _new_file(Path(out_path).expanduser() if out_path else (
|
|
178
|
+
src.with_name(src.stem + '-bestpred.csv') if src else Path.cwd() / 'bestpred-lactations.csv'))
|
|
179
|
+
dest.write_text(rows_to_csv(rows), encoding='utf-8')
|
|
180
|
+
except (InputProblem, ValueError, OSError) as e:
|
|
181
|
+
raise ToolError(str(e)) from e
|
|
182
|
+
out['table_file'] = str(dest)
|
|
183
|
+
return out
|
|
184
|
+
|
|
185
|
+
return mcp
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""The MCP server, called as an agent would call it (the SDK's in-process client)."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from mcp import Client
|
|
7
|
+
|
|
8
|
+
from bestpred import TestDay, bestpred
|
|
9
|
+
from bestpred_mcp.server import build_server
|
|
10
|
+
|
|
11
|
+
pytestmark = pytest.mark.anyio
|
|
12
|
+
|
|
13
|
+
TESTS = [{'dim': 12, 'milk': 78.0, 'fat': 4.4, 'protein': 3.2, 'scs': 3.1},
|
|
14
|
+
{'dim': 43, 'milk': 96.5, 'fat': 3.7, 'protein': 2.9, 'scs': 2.0},
|
|
15
|
+
{'dim': 71, 'milk': 99.0, 'fat': 3.5, 'protein': 3.0, 'scs': 1.8},
|
|
16
|
+
{'dim': 104, 'milk': 94.2, 'fat': 3.6, 'protein': 3.1, 'scs': 2.4}]
|
|
17
|
+
HERD = """ID,LACT,FDAT,DIM,MILK,PCTF,PCTP,SCS,AGE
|
|
18
|
+
101,1,03/01/26,15,62.0,3.9,3.1,2.4,24
|
|
19
|
+
101,1,03/01/26,45,75.5,3.6,3.0,2.1,24
|
|
20
|
+
101,1,03/01/26,76,78.0,3.5,3.0,2.0,24
|
|
21
|
+
202,3,02/10/26,20,98.0,3.8,3.0,2.9,
|
|
22
|
+
202,3,02/10/26,52,112.0,3.4,2.9,2.5,
|
|
23
|
+
202,3,02/10/26,80,108.5,3.5,3.0,2.6,
|
|
24
|
+
303,2,,30,90.0,3.6,3.0,2.2,
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture
|
|
29
|
+
def anyio_backend():
|
|
30
|
+
return 'asyncio'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def data(result) -> dict:
|
|
34
|
+
assert not result.is_error, result.content
|
|
35
|
+
return result.structured_content if result.structured_content else json.loads(result.content[0].text)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def test_the_tools_are_listed_with_titles_and_hints():
|
|
39
|
+
async with Client(build_server()) as c:
|
|
40
|
+
tools = {t.name: t for t in (await c.list_tools()).tools}
|
|
41
|
+
assert set(tools) == {'lactation', 'expected_curve', 'mature_equivalent_factors', 'herd_lactations'}
|
|
42
|
+
for name, tool in tools.items():
|
|
43
|
+
assert tool.title, name
|
|
44
|
+
assert tool.annotations is not None and tool.annotations.destructive_hint is False, name
|
|
45
|
+
assert 'Never estimate a lactation yourself' in tool.description, name
|
|
46
|
+
assert tools['lactation'].annotations.read_only_hint is True
|
|
47
|
+
assert tools['herd_lactations'].annotations.read_only_hint is False # local: it writes a new file
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def test_one_cow_matches_bestpred_called_directly():
|
|
51
|
+
direct = bestpred([TestDay(**t) for t in TESTS], herdavg=(0, 0, 0, 0), agefac=(1, 1, 1, 1), cowid='H', parity=2,
|
|
52
|
+
fresh='20260301')
|
|
53
|
+
async with Client(build_server()) as c:
|
|
54
|
+
got = data(await c.call_tool('lactation', {'tests': TESTS, 'parity': 2, 'fresh': '2026-03-01'}))
|
|
55
|
+
assert got['milk_305'] == round(direct.yields('actual')['milk']['305'])
|
|
56
|
+
assert got['reliability_milk_pct'] == round(100 * float(direct.rel_yield[0]))
|
|
57
|
+
assert 'milk_305_me' not in got and 'age_months and state' in got['note']
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
async def test_age_gives_mature_equivalent():
|
|
61
|
+
async with Client(build_server()) as c:
|
|
62
|
+
got = data(await c.call_tool('lactation', {'tests': TESTS, 'parity': 1, 'fresh': '2026-03-01',
|
|
63
|
+
'age_months': 24, 'state': 'CA'}))
|
|
64
|
+
assert got['milk_305_me'] > got['milk_305'] # a two-year-old's mature equivalent is above her actual
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def test_expected_curve_is_weekly_to_305():
|
|
68
|
+
async with Client(build_server()) as c:
|
|
69
|
+
got = data(await c.call_tool('expected_curve', {'tests': TESTS, 'parity': 2, 'fresh': '2026-03-01'}))
|
|
70
|
+
pts = got['points']
|
|
71
|
+
assert pts[0]['dim'] == 7 and pts[-1]['dim'] == 301 and all(p['milk'] > 0 for p in pts)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def test_mature_equivalent_factors():
|
|
75
|
+
async with Client(build_server()) as c:
|
|
76
|
+
got = data(await c.call_tool('mature_equivalent_factors', {'age_months': 24, 'fresh': '2026-03-01',
|
|
77
|
+
'parity': 1, 'state': 'CA'}))
|
|
78
|
+
assert got['milk'] > 1.0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def test_a_herd_file_round_trip(tmp_path):
|
|
82
|
+
src = tmp_path / 'tests.csv'
|
|
83
|
+
src.write_text(HERD, encoding='utf-8')
|
|
84
|
+
async with Client(build_server()) as c:
|
|
85
|
+
got = data(await c.call_tool('herd_lactations', {'path': str(src), 'state': 'CA'}))
|
|
86
|
+
again = data(await c.call_tool('herd_lactations', {'path': str(src)}))
|
|
87
|
+
assert got['lactations'] == 2 and got['rows_skipped'] == 1 # cow 303 has no fresh date
|
|
88
|
+
assert set(got['by_parity']) == {'1', '3+'}
|
|
89
|
+
table = (tmp_path / 'tests-bestpred.csv').read_text(encoding='utf-8').splitlines()
|
|
90
|
+
assert table[0].startswith('cow,parity,fresh') and len(table) == 3
|
|
91
|
+
assert 'milk_305_me' in table[0] # cow 101 has her age
|
|
92
|
+
assert again['table_file'].endswith('tests-bestpred-2.csv') # the first file is never replaced
|
|
93
|
+
assert 'no state' in again['note'] # ages without a state: actual yields, and it says why
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def test_bad_input_is_a_message_not_a_crash():
|
|
97
|
+
async with Client(build_server()) as c:
|
|
98
|
+
r = await c.call_tool('lactation', {'tests': TESTS, 'parity': 2, 'fresh': 'last spring'})
|
|
99
|
+
h = await c.call_tool('herd_lactations', {'csv_text': 'a,b\n1,2\n'})
|
|
100
|
+
assert r.is_error and "Can't read the date" in r.content[0].text
|
|
101
|
+
assert h.is_error and 'needs columns' in h.content[0].text
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
async def test_hosted_reads_no_files_and_returns_the_table():
|
|
105
|
+
async with Client(build_server(hosted=True)) as c:
|
|
106
|
+
tools = {t.name: t for t in (await c.list_tools()).tools}
|
|
107
|
+
got = data(await c.call_tool('herd_lactations', {'csv_text': HERD}))
|
|
108
|
+
assert 'path' not in tools['herd_lactations'].input_schema['properties']
|
|
109
|
+
assert tools['herd_lactations'].annotations.read_only_hint is True
|
|
110
|
+
assert got['table_csv'].splitlines()[0].startswith('cow,parity,fresh')
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_the_hosted_service_has_its_pages(monkeypatch):
|
|
114
|
+
from starlette.testclient import TestClient
|
|
115
|
+
|
|
116
|
+
from bestpred_mcp.hosted import hosted_app
|
|
117
|
+
|
|
118
|
+
monkeypatch.delenv('OPENAI_APPS_CHALLENGE', raising=False)
|
|
119
|
+
with TestClient(hosted_app()) as web:
|
|
120
|
+
assert web.get('/').status_code == 200 and 'uvx bestpred-mcp' in web.get('/').text
|
|
121
|
+
assert 'not written to disk' in web.get('/privacy').text
|
|
122
|
+
assert 'herd_lactations' in web.get('/llms.txt').text
|
|
123
|
+
assert web.get('/.well-known/openai-apps-challenge').status_code == 404
|
|
124
|
+
monkeypatch.setenv('OPENAI_APPS_CHALLENGE', 'token-123')
|
|
125
|
+
with TestClient(hosted_app()) as web:
|
|
126
|
+
assert web.get('/.well-known/openai-apps-challenge').text == 'token-123'
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_the_hosted_service_refuses_an_oversized_call():
|
|
130
|
+
from starlette.testclient import TestClient
|
|
131
|
+
|
|
132
|
+
from bestpred_mcp.hosted import hosted_app
|
|
133
|
+
|
|
134
|
+
with TestClient(hosted_app()) as web:
|
|
135
|
+
r = web.post('/mcp', content=b'x' * (6 * 1024 * 1024),
|
|
136
|
+
headers={'content-type': 'application/json', 'accept': 'application/json, text/event-stream'})
|
|
137
|
+
assert r.status_code == 413
|