mfp-mcp 0.1.0__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.
@@ -0,0 +1,18 @@
1
+ # All variables are optional. Run `myfitnesspal-mcp auth` for the guided setup instead.
2
+
3
+ # MyFitnessPal session cookie: either the full Cookie header from a logged-in
4
+ # browser request, or just the value of __Secure-next-auth.session-token.
5
+ # MFP_COOKIE=
6
+
7
+ # Your MyFitnessPal username (not email). Only needed if MFP's profile endpoint
8
+ # fails for your account (the server will tell you).
9
+ # MFP_USERNAME=
10
+
11
+ # Browser fingerprint for Cloudflare. Try chrome124 etc. if you get 403s.
12
+ # MFP_IMPERSONATE=chrome
13
+
14
+ # How many days back to gap-fill the local cache (default 30).
15
+ # MFP_SYNC_DAYS=30
16
+
17
+ # Where to keep the local SQLite cache (default: platform data dir).
18
+ # MFP_MCP_DATA_DIR=
@@ -0,0 +1,19 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python-version: ["3.10", "3.13"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: astral-sh/setup-uv@v5
17
+ with:
18
+ python-version: ${{ matrix.python-version }}
19
+ - run: uv run pytest
@@ -0,0 +1,17 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ id-token: write
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: astral-sh/setup-uv@v5
16
+ - run: uv build
17
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .env
8
+ .env.*
9
+ !.env.example
10
+ *.db
11
+ cookies*
12
+ .pytest_cache/
13
+ uv.lock
mfp_mcp-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mason Levy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
mfp_mcp-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.4
2
+ Name: mfp-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for MyFitnessPal: log, search, and analyze your food diary from any MCP client
5
+ Project-URL: Repository, https://github.com/Mason-Levyy/myfitnesspal-mcp
6
+ Author: Mason Levy
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: mcp,model-context-protocol,myfitnesspal,nutrition
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Utilities
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: curl-cffi<0.16,>=0.15
15
+ Requires-Dist: lxml<6,>=5
16
+ Requires-Dist: mcp<2,>=1.10
17
+ Requires-Dist: myfitnesspal==2.1.2
18
+ Requires-Dist: platformdirs>=4
19
+ Provides-Extra: autorefresh
20
+ Requires-Dist: playwright>=1.40; extra == 'autorefresh'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # myfitnesspal-mcp
24
+
25
+ Connect MyFitnessPal to Claude or any MCP client. Log meals by talking, search
26
+ the food database with macros, track trends, and export your nutrition history —
27
+ all against your real MyFitnessPal diary.
28
+
29
+ Published on PyPI as [`mfp-mcp`](https://pypi.org/project/mfp-mcp/).
30
+
31
+ > **Unofficial.** MyFitnessPal has no public API; this reverse-engineers the
32
+ > web app's own endpoints. It can break whenever MFP changes their site. Use at
33
+ > your own risk, with your own account.
34
+
35
+ ## Why this one?
36
+
37
+ MyFitnessPal moved behind Cloudflare + NextAuth, which broke the
38
+ username/password login that most existing integrations rely on. This server:
39
+
40
+ - **Authenticates with your browser session cookie** over a real Chrome TLS
41
+ fingerprint ([curl_cffi](https://github.com/lexiforest/curl_cffi)), which
42
+ passes Cloudflare.
43
+ - **Auto-refreshes the session** (optional): a headless browser profile rotates
44
+ the token when it expires, and failed calls retry automatically.
45
+ - **Writes, not just reads**: log, modify, and delete real diary entries.
46
+ - **Search-then-log**: get candidates with macros, then log the exact item.
47
+
48
+ ## Quickstart
49
+
50
+ 1. Connect your account (one-time; prompts you to paste a cookie — see
51
+ [Authentication](#authentication)):
52
+
53
+ ```bash
54
+ uvx mfp-mcp auth
55
+ ```
56
+
57
+ 2. Add the server to your client.
58
+
59
+ **Claude Code**
60
+
61
+ ```bash
62
+ claude mcp add myfitnesspal -- uvx mfp-mcp
63
+ ```
64
+
65
+ **Claude Desktop** (`claude_desktop_config.json`)
66
+
67
+ ```json
68
+ {
69
+ "mcpServers": {
70
+ "myfitnesspal": {
71
+ "command": "uvx",
72
+ "args": ["mfp-mcp"]
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ 3. Talk to it: *"log a banana as a snack"*, *"what did I eat yesterday?"*,
79
+ *"chart my weight this month"*.
80
+
81
+ Requires [uv](https://docs.astral.sh/uv/). Any MCP client that speaks stdio or
82
+ streamable HTTP works, not just Claude.
83
+
84
+ ## Authentication
85
+
86
+ MyFitnessPal killed headless password login, so this uses your browser's
87
+ session cookie:
88
+
89
+ 1. Log in at [myfitnesspal.com](https://www.myfitnesspal.com).
90
+ 2. Open DevTools (F12) → **Application** (Chrome) or **Storage** (Firefox) →
91
+ **Cookies** → `https://www.myfitnesspal.com`.
92
+ 3. Copy the value of `__Secure-next-auth.session-token`.
93
+ 4. Paste it into the `mfp-mcp auth` prompt (input is hidden).
94
+
95
+ Pasting the entire `Cookie:` header from any request in the Network tab also
96
+ works. Cookies are stored with owner-only permissions in your platform config
97
+ dir, or supply them via the `MFP_COOKIE` environment variable instead.
98
+
99
+ Sessions last around 30 days. When one expires, either re-run `auth` — or
100
+ enable auto-refresh so you never have to.
101
+
102
+ ### Auto-refresh (recommended)
103
+
104
+ With the `autorefresh` extra, `auth` also seeds a persistent headless browser
105
+ profile. When MyFitnessPal rejects the session mid-call, the server tells your
106
+ client it is retrying, boots the profile headlessly, lets MyFitnessPal rotate
107
+ the session token, saves the fresh cookie, and retries the call.
108
+
109
+ ```bash
110
+ uvx --from 'mfp-mcp[autorefresh]' playwright install chromium
111
+ uvx --from 'mfp-mcp[autorefresh]' mfp-mcp auth
112
+ ```
113
+
114
+ Then use the same `--from 'mfp-mcp[autorefresh]'` form in your client config
115
+ (e.g. `uvx --from 'mfp-mcp[autorefresh]' mfp-mcp`).
116
+
117
+ ## Tools
118
+
119
+ | Tool | What it does |
120
+ | --- | --- |
121
+ | `fitness_get_day` | Nutrition totals, diary entries, and feel note for a day |
122
+ | `fitness_search_food` | Candidate matches with brand, calories, macros, serving, and ids |
123
+ | `fitness_log_food` | Log a food to the real diary (top match, or an exact search candidate) |
124
+ | `fitness_delete_food` | Remove a diary entry by name match |
125
+ | `fitness_modify_food` | Replace an entry (or change its quantity) |
126
+ | `fitness_log_weight` | Log a weight measurement (updates the same day on re-log) |
127
+ | `fitness_get_exercise` | Read the exercise diary (cardio + strength) |
128
+ | `fitness_log_feel` | Save a subjective "how I feel" note (stored locally, never sent to MFP) |
129
+ | `fitness_get_trends` | One metric over a date range: weight, calories_in, protein, carbs, fat |
130
+ | `fitness_bulk_export` | Whole date range in one call, for analysis |
131
+
132
+ The high-accuracy logging flow: `fitness_search_food("greek yogurt")` returns
133
+ candidates with macros and a `food_id`/`weight_id`; pass those to
134
+ `fitness_log_food` to log exactly that item instead of trusting the top match.
135
+
136
+ Day summaries and trends read from a local SQLite cache that gap-fills from
137
+ MyFitnessPal (first call on a fresh install fetches up to 30 days, one request
138
+ per day — subsequent calls are fast).
139
+
140
+ Water intake is read-only (it appears in day summaries): MyFitnessPal's water
141
+ *write* isn't exposed on any endpoint we've found — `/food/water` accepts POSTs
142
+ but ignores them. If you capture the real call in your browser, a PR is very
143
+ welcome.
144
+
145
+ ## Remote / HTTP mode
146
+
147
+ The default transport is stdio. For network clients:
148
+
149
+ ```bash
150
+ mfp-mcp --http --host 127.0.0.1 --port 8484
151
+ ```
152
+
153
+ This serves streamable HTTP at `/mcp`. **There is no built-in authentication —
154
+ never expose it to the internet.** Bind to localhost and front it with
155
+ something that authenticates for you: a VPN/tailnet (e.g. `tailscale serve`),
156
+ an authenticating reverse proxy, or an OAuth-aware MCP gateway.
157
+
158
+ ## Configuration
159
+
160
+ | Variable | Purpose | Default |
161
+ | --- | --- | --- |
162
+ | `MFP_COOKIE` | Session cookie (full header or bare token); overrides the saved file | – |
163
+ | `MFP_USERNAME` | Your MFP username (not email); only needed if profile lookup fails | auto-detected |
164
+ | `MFP_IMPERSONATE` | curl_cffi browser fingerprint (try `chrome124` on 403s) | `chrome` |
165
+ | `MFP_SYNC_DAYS` | Gap-fill lookback window in days | `30` |
166
+ | `MFP_MCP_DATA_DIR` | Where the SQLite cache + browser profile live | platform data dir |
167
+
168
+ ## Troubleshooting
169
+
170
+ - **403 / Cloudflare blocked**: try `MFP_IMPERSONATE=chrome124` (or another
171
+ [curl_cffi target](https://github.com/lexiforest/curl_cffi#supported-browsers)).
172
+ Datacenter IPs get challenged far more than residential ones.
173
+ - **"Session expired"**: re-run `mfp-mcp auth`, or set up
174
+ [auto-refresh](#auto-refresh-recommended).
175
+ - **"couldn't read your MyFitnessPal profile"**: MFP's profile endpoint 500s
176
+ for some accounts. Set `MFP_USERNAME` to your username (not your email).
177
+ - **curl_cffi install issues**: prebuilt wheels cover Linux/macOS/Windows;
178
+ musl (Alpine) builds from source.
179
+
180
+ ## How it works
181
+
182
+ - [python-myfitnesspal](https://github.com/coddingtonbear/python-myfitnesspal)
183
+ parses the diary, measurements, and exercise pages — run over a `curl_cffi`
184
+ session that impersonates Chrome's TLS fingerprint so Cloudflare lets it
185
+ through with just the NextAuth session cookie.
186
+ - Writes replicate the web app's own XHR calls: the legacy food-search page
187
+ supplies the `food_id`/`weight_id` that `/food/add` accepts, and deletes go
188
+ through `/food/remove` with the page CSRF token.
189
+ - Day summaries, trends, and exports read a local SQLite cache that gap-fills
190
+ missing days; feel notes are local-only.
191
+
192
+ ## Development
193
+
194
+ ```bash
195
+ git clone https://github.com/Mason-Levyy/myfitnesspal-mcp
196
+ cd myfitnesspal-mcp
197
+ uv sync --extra autorefresh
198
+ uv run pytest
199
+ ```
200
+
201
+ Tests run against synthetic MyFitnessPal HTML/JSON fixtures — no account
202
+ needed.
203
+
204
+ ## License
205
+
206
+ [MIT](LICENSE)
@@ -0,0 +1,184 @@
1
+ # myfitnesspal-mcp
2
+
3
+ Connect MyFitnessPal to Claude or any MCP client. Log meals by talking, search
4
+ the food database with macros, track trends, and export your nutrition history —
5
+ all against your real MyFitnessPal diary.
6
+
7
+ Published on PyPI as [`mfp-mcp`](https://pypi.org/project/mfp-mcp/).
8
+
9
+ > **Unofficial.** MyFitnessPal has no public API; this reverse-engineers the
10
+ > web app's own endpoints. It can break whenever MFP changes their site. Use at
11
+ > your own risk, with your own account.
12
+
13
+ ## Why this one?
14
+
15
+ MyFitnessPal moved behind Cloudflare + NextAuth, which broke the
16
+ username/password login that most existing integrations rely on. This server:
17
+
18
+ - **Authenticates with your browser session cookie** over a real Chrome TLS
19
+ fingerprint ([curl_cffi](https://github.com/lexiforest/curl_cffi)), which
20
+ passes Cloudflare.
21
+ - **Auto-refreshes the session** (optional): a headless browser profile rotates
22
+ the token when it expires, and failed calls retry automatically.
23
+ - **Writes, not just reads**: log, modify, and delete real diary entries.
24
+ - **Search-then-log**: get candidates with macros, then log the exact item.
25
+
26
+ ## Quickstart
27
+
28
+ 1. Connect your account (one-time; prompts you to paste a cookie — see
29
+ [Authentication](#authentication)):
30
+
31
+ ```bash
32
+ uvx mfp-mcp auth
33
+ ```
34
+
35
+ 2. Add the server to your client.
36
+
37
+ **Claude Code**
38
+
39
+ ```bash
40
+ claude mcp add myfitnesspal -- uvx mfp-mcp
41
+ ```
42
+
43
+ **Claude Desktop** (`claude_desktop_config.json`)
44
+
45
+ ```json
46
+ {
47
+ "mcpServers": {
48
+ "myfitnesspal": {
49
+ "command": "uvx",
50
+ "args": ["mfp-mcp"]
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ 3. Talk to it: *"log a banana as a snack"*, *"what did I eat yesterday?"*,
57
+ *"chart my weight this month"*.
58
+
59
+ Requires [uv](https://docs.astral.sh/uv/). Any MCP client that speaks stdio or
60
+ streamable HTTP works, not just Claude.
61
+
62
+ ## Authentication
63
+
64
+ MyFitnessPal killed headless password login, so this uses your browser's
65
+ session cookie:
66
+
67
+ 1. Log in at [myfitnesspal.com](https://www.myfitnesspal.com).
68
+ 2. Open DevTools (F12) → **Application** (Chrome) or **Storage** (Firefox) →
69
+ **Cookies** → `https://www.myfitnesspal.com`.
70
+ 3. Copy the value of `__Secure-next-auth.session-token`.
71
+ 4. Paste it into the `mfp-mcp auth` prompt (input is hidden).
72
+
73
+ Pasting the entire `Cookie:` header from any request in the Network tab also
74
+ works. Cookies are stored with owner-only permissions in your platform config
75
+ dir, or supply them via the `MFP_COOKIE` environment variable instead.
76
+
77
+ Sessions last around 30 days. When one expires, either re-run `auth` — or
78
+ enable auto-refresh so you never have to.
79
+
80
+ ### Auto-refresh (recommended)
81
+
82
+ With the `autorefresh` extra, `auth` also seeds a persistent headless browser
83
+ profile. When MyFitnessPal rejects the session mid-call, the server tells your
84
+ client it is retrying, boots the profile headlessly, lets MyFitnessPal rotate
85
+ the session token, saves the fresh cookie, and retries the call.
86
+
87
+ ```bash
88
+ uvx --from 'mfp-mcp[autorefresh]' playwright install chromium
89
+ uvx --from 'mfp-mcp[autorefresh]' mfp-mcp auth
90
+ ```
91
+
92
+ Then use the same `--from 'mfp-mcp[autorefresh]'` form in your client config
93
+ (e.g. `uvx --from 'mfp-mcp[autorefresh]' mfp-mcp`).
94
+
95
+ ## Tools
96
+
97
+ | Tool | What it does |
98
+ | --- | --- |
99
+ | `fitness_get_day` | Nutrition totals, diary entries, and feel note for a day |
100
+ | `fitness_search_food` | Candidate matches with brand, calories, macros, serving, and ids |
101
+ | `fitness_log_food` | Log a food to the real diary (top match, or an exact search candidate) |
102
+ | `fitness_delete_food` | Remove a diary entry by name match |
103
+ | `fitness_modify_food` | Replace an entry (or change its quantity) |
104
+ | `fitness_log_weight` | Log a weight measurement (updates the same day on re-log) |
105
+ | `fitness_get_exercise` | Read the exercise diary (cardio + strength) |
106
+ | `fitness_log_feel` | Save a subjective "how I feel" note (stored locally, never sent to MFP) |
107
+ | `fitness_get_trends` | One metric over a date range: weight, calories_in, protein, carbs, fat |
108
+ | `fitness_bulk_export` | Whole date range in one call, for analysis |
109
+
110
+ The high-accuracy logging flow: `fitness_search_food("greek yogurt")` returns
111
+ candidates with macros and a `food_id`/`weight_id`; pass those to
112
+ `fitness_log_food` to log exactly that item instead of trusting the top match.
113
+
114
+ Day summaries and trends read from a local SQLite cache that gap-fills from
115
+ MyFitnessPal (first call on a fresh install fetches up to 30 days, one request
116
+ per day — subsequent calls are fast).
117
+
118
+ Water intake is read-only (it appears in day summaries): MyFitnessPal's water
119
+ *write* isn't exposed on any endpoint we've found — `/food/water` accepts POSTs
120
+ but ignores them. If you capture the real call in your browser, a PR is very
121
+ welcome.
122
+
123
+ ## Remote / HTTP mode
124
+
125
+ The default transport is stdio. For network clients:
126
+
127
+ ```bash
128
+ mfp-mcp --http --host 127.0.0.1 --port 8484
129
+ ```
130
+
131
+ This serves streamable HTTP at `/mcp`. **There is no built-in authentication —
132
+ never expose it to the internet.** Bind to localhost and front it with
133
+ something that authenticates for you: a VPN/tailnet (e.g. `tailscale serve`),
134
+ an authenticating reverse proxy, or an OAuth-aware MCP gateway.
135
+
136
+ ## Configuration
137
+
138
+ | Variable | Purpose | Default |
139
+ | --- | --- | --- |
140
+ | `MFP_COOKIE` | Session cookie (full header or bare token); overrides the saved file | – |
141
+ | `MFP_USERNAME` | Your MFP username (not email); only needed if profile lookup fails | auto-detected |
142
+ | `MFP_IMPERSONATE` | curl_cffi browser fingerprint (try `chrome124` on 403s) | `chrome` |
143
+ | `MFP_SYNC_DAYS` | Gap-fill lookback window in days | `30` |
144
+ | `MFP_MCP_DATA_DIR` | Where the SQLite cache + browser profile live | platform data dir |
145
+
146
+ ## Troubleshooting
147
+
148
+ - **403 / Cloudflare blocked**: try `MFP_IMPERSONATE=chrome124` (or another
149
+ [curl_cffi target](https://github.com/lexiforest/curl_cffi#supported-browsers)).
150
+ Datacenter IPs get challenged far more than residential ones.
151
+ - **"Session expired"**: re-run `mfp-mcp auth`, or set up
152
+ [auto-refresh](#auto-refresh-recommended).
153
+ - **"couldn't read your MyFitnessPal profile"**: MFP's profile endpoint 500s
154
+ for some accounts. Set `MFP_USERNAME` to your username (not your email).
155
+ - **curl_cffi install issues**: prebuilt wheels cover Linux/macOS/Windows;
156
+ musl (Alpine) builds from source.
157
+
158
+ ## How it works
159
+
160
+ - [python-myfitnesspal](https://github.com/coddingtonbear/python-myfitnesspal)
161
+ parses the diary, measurements, and exercise pages — run over a `curl_cffi`
162
+ session that impersonates Chrome's TLS fingerprint so Cloudflare lets it
163
+ through with just the NextAuth session cookie.
164
+ - Writes replicate the web app's own XHR calls: the legacy food-search page
165
+ supplies the `food_id`/`weight_id` that `/food/add` accepts, and deletes go
166
+ through `/food/remove` with the page CSRF token.
167
+ - Day summaries, trends, and exports read a local SQLite cache that gap-fills
168
+ missing days; feel notes are local-only.
169
+
170
+ ## Development
171
+
172
+ ```bash
173
+ git clone https://github.com/Mason-Levyy/myfitnesspal-mcp
174
+ cd myfitnesspal-mcp
175
+ uv sync --extra autorefresh
176
+ uv run pytest
177
+ ```
178
+
179
+ Tests run against synthetic MyFitnessPal HTML/JSON fixtures — no account
180
+ needed.
181
+
182
+ ## License
183
+
184
+ [MIT](LICENSE)
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "mfp-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for MyFitnessPal: log, search, and analyze your food diary from any MCP client"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ authors = [{ name = "Mason Levy" }]
9
+ keywords = ["mcp", "myfitnesspal", "nutrition", "model-context-protocol"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Utilities",
14
+ ]
15
+ dependencies = [
16
+ "mcp>=1.10,<2",
17
+ "myfitnesspal==2.1.2",
18
+ "curl-cffi>=0.15,<0.16",
19
+ "lxml>=5,<6",
20
+ "platformdirs>=4",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ autorefresh = ["playwright>=1.40"]
25
+
26
+ [project.urls]
27
+ Repository = "https://github.com/Mason-Levyy/myfitnesspal-mcp"
28
+
29
+ [project.scripts]
30
+ mfp-mcp = "myfitnesspal_mcp.cli:main"
31
+ myfitnesspal-mcp = "myfitnesspal_mcp.cli:main"
32
+
33
+ [dependency-groups]
34
+ dev = ["pytest>=8"]
35
+
36
+ [build-system]
37
+ requires = ["hatchling"]
38
+ build-backend = "hatchling.build"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/myfitnesspal_mcp"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,145 @@
1
+ import getpass
2
+ import json
3
+ import sys
4
+
5
+ from . import config
6
+
7
+ SESSION_COOKIE = "__Secure-next-auth.session-token"
8
+
9
+ INSTRUCTIONS = """\
10
+ Connect your MyFitnessPal account
11
+ ---------------------------------
12
+ 1. Log in at https://www.myfitnesspal.com in your browser.
13
+ 2. Open DevTools (F12) -> Application (Chrome) or Storage (Firefox) -> Cookies.
14
+ 3. Copy the value of the '__Secure-next-auth.session-token' cookie.
15
+ (Pasting the entire Cookie header from any request also works.)
16
+ """
17
+
18
+
19
+ def parse_cookie_input(text: str) -> dict[str, str]:
20
+ text = text.strip()
21
+ if text.lower().startswith("cookie:"):
22
+ text = text[len("cookie:"):].strip()
23
+ if "=" not in text:
24
+ return {SESSION_COOKIE: text}
25
+ cookies = {}
26
+ for part in text.split(";"):
27
+ if "=" in part:
28
+ name, value = part.strip().split("=", 1)
29
+ cookies[name.strip()] = value.strip()
30
+ return cookies
31
+
32
+
33
+ def _read_saved() -> dict:
34
+ path = config.cookies_path()
35
+ if not path.exists():
36
+ return {}
37
+ return json.loads(path.read_text())
38
+
39
+
40
+ def load_cookies() -> dict[str, str] | None:
41
+ env = config.cookie_env()
42
+ if env:
43
+ return parse_cookie_input(env)
44
+ saved = _read_saved().get("cookies")
45
+ if saved:
46
+ return saved
47
+ return None
48
+
49
+
50
+ def saved_username() -> str | None:
51
+ if config.username_env():
52
+ return config.username_env()
53
+ return _read_saved().get("username")
54
+
55
+
56
+ def save_cookies(cookies: dict[str, str], username: str | None = None) -> None:
57
+ saved = _read_saved()
58
+ saved["cookies"] = cookies
59
+ if username:
60
+ saved["username"] = username
61
+ path = config.cookies_path()
62
+ path.write_text(json.dumps(saved, indent=2))
63
+ path.chmod(0o600)
64
+
65
+
66
+ def read_cookie_paste() -> str:
67
+ if sys.stdin.isatty():
68
+ return getpass.getpass("Paste cookie (input hidden): ")
69
+ print("(no terminal detected — reading the cookie from stdin)", file=sys.stderr)
70
+ return sys.stdin.readline()
71
+
72
+
73
+ def _validate(cookies: dict[str, str]):
74
+ """Builds a client from the cookies; when only the profile lookup fails (a
75
+ known MFP issue for accounts that log in by email), asks for the username
76
+ and retries instead of failing the whole flow."""
77
+ from myfitnesspal.exceptions import MyfitnesspalLoginError
78
+
79
+ from . import mfp_client
80
+
81
+ try:
82
+ return mfp_client.build_client(cookies)
83
+ except MyfitnesspalLoginError as exc:
84
+ if "profile" not in str(exc):
85
+ raise
86
+ if not sys.stdin.isatty():
87
+ raise
88
+ print(
89
+ "\nYour cookie works, but MyFitnessPal couldn't return your profile "
90
+ "(a known issue for some accounts)."
91
+ )
92
+ username = input("Your MyFitnessPal username (not email): ").strip()
93
+ if not username:
94
+ raise
95
+ save_cookies(cookies, username=username)
96
+ return mfp_client.build_client(cookies)
97
+
98
+
99
+ def run_auth_flow() -> int:
100
+ from . import mfp_client, refresh
101
+
102
+ print(INSTRUCTIONS, flush=True)
103
+ try:
104
+ pasted = read_cookie_paste()
105
+ except EOFError:
106
+ pasted = ""
107
+ if not pasted.strip():
108
+ print(
109
+ "No cookie received. Run this in an interactive terminal, or pipe "
110
+ "the token in: myfitnesspal-mcp auth < token.txt",
111
+ file=sys.stderr,
112
+ )
113
+ return 1
114
+
115
+ cookies = parse_cookie_input(pasted)
116
+ print("Validating with MyFitnessPal...")
117
+ try:
118
+ client = _validate(cookies)
119
+ except Exception as exc:
120
+ print(f"Those cookies didn't authenticate: {exc}", file=sys.stderr)
121
+ print(
122
+ "If this mentions Cloudflare or a 403, try MFP_IMPERSONATE=chrome124 "
123
+ "or run from a residential IP.",
124
+ file=sys.stderr,
125
+ )
126
+ return 1
127
+
128
+ save_cookies(cookies, username=client.effective_username)
129
+ mfp_client.reset()
130
+ print(f"Connected as {client.effective_username}. Cookies saved to {config.cookies_path()}")
131
+
132
+ if refresh.available():
133
+ print("Seeding the browser profile for automatic session refresh...")
134
+ try:
135
+ refresh.seed_profile(cookies)
136
+ print(f"Auto-refresh ready (profile at {refresh.profile_dir()}).")
137
+ except Exception as exc:
138
+ print(f"Could not seed the auto-refresh browser profile: {exc}", file=sys.stderr)
139
+ print("The server still works; sessions just need a manual re-auth when they expire.")
140
+ else:
141
+ print(
142
+ "Optional: install with the [autorefresh] extra and run auth again to "
143
+ "enable automatic session refresh via a headless browser."
144
+ )
145
+ return 0