polar-mcp 0.5.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,20 @@
1
+ # credentials — never commit
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+ *.token
6
+ secrets.*
7
+
8
+ # exported exercise files (personal data)
9
+ exports/
10
+
11
+ # python / uv
12
+ .venv/
13
+ __pycache__/
14
+ *.pyc
15
+ .pytest_cache/
16
+ .ruff_cache/
17
+ .mypy_cache/
18
+ dist/
19
+ .login-state
20
+ dist/
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.5.0] - 2026-12-03
8
+
9
+ First public release.
10
+
11
+ ### Added
12
+ - 15 read-only tools over the Polar AccessLink v3 API: profile, workouts (with FIT/TCX/GPX
13
+ export), cardio load, daily activity (any range up to 365 days), 24/7 heart rate (per-day
14
+ summary or raw), sleep, Nightly Recharge and SleepWise.
15
+ - Automatic account linking: the first tool call (or one after a 401) opens Polar Flow and
16
+ completes the OAuth flow on a localhost listener.
17
+ - `polar-mcp setup | login | status | logout` commands.
18
+ - Credentials from the environment, Claude plugin settings, or `~/.config/polar-mcp/.env`.
19
+ - Distribution as a PyPI package, a Claude plugin marketplace, a `.mcpb` Desktop extension
20
+ and an MCP Registry entry.
21
+
22
+ [0.5.0]: https://github.com/kayaman/polar-mcp/releases/tag/v0.5.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marco Antonio Gonzalez Junior
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.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.5
2
+ Name: polar-mcp
3
+ Version: 0.5.0
4
+ Summary: MCP server for the Polar AccessLink API: let Claude (or any MCP client) read your Polar workouts, sleep, Nightly Recharge, HRV and daily activity.
5
+ Project-URL: Homepage, https://github.com/kayaman/polar-mcp
6
+ Project-URL: Repository, https://github.com/kayaman/polar-mcp
7
+ Project-URL: Issues, https://github.com/kayaman/polar-mcp/issues
8
+ Project-URL: Changelog, https://github.com/kayaman/polar-mcp/blob/main/CHANGELOG.md
9
+ Author: Marco Antonio Gonzalez Junior
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: accesslink,claude,fitness,hrv,mcp,model-context-protocol,polar,sleep,wearables
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: End Users/Desktop
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Utilities
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Requires-Dist: httpx>=0.27
27
+ Requires-Dist: mcp<2,>=1.10
28
+ Description-Content-Type: text/markdown
29
+
30
+ # polar-mcp
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/polar-mcp)](https://pypi.org/project/polar-mcp/)
33
+ [![CI](https://github.com/kayaman/polar-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/kayaman/polar-mcp/actions/workflows/ci.yml)
34
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
35
+
36
+ An [MCP](https://modelcontextprotocol.io) server that lets Claude, or any MCP client,
37
+ read your **Polar** watch data through the
38
+ [Polar AccessLink API](https://www.polar.com/accesslink-api/): workouts, sleep, Nightly
39
+ Recharge and HRV, cardio load, daily activity and 24/7 heart rate.
40
+
41
+ > Ask *"How did I sleep this week?"*, *"Am I recovered enough for intervals today?"* or
42
+ > *"Compare my training load to last month"*. The first time, Polar Flow opens in your
43
+ > browser; click **Approve** and you're linked.
44
+
45
+ Read-only. Unofficial: not affiliated with or endorsed by Polar Electro Oy.
46
+
47
+ <!-- mcp-name: io.github.kayaman/polar-mcp -->
48
+
49
+ ## 1. Create your Polar API client (once, ~2 minutes)
50
+
51
+ Polar requires every app to have its own API client, so you create one for yourself:
52
+
53
+ 1. Sign in at [admin.polaraccesslink.com](https://admin.polaraccesslink.com) with your
54
+ Polar Flow account and create a client.
55
+ 2. Set its **redirect URL** to exactly `http://localhost:8765/callback`.
56
+ 3. Keep the **client ID** and **client secret** at hand for the next step.
57
+
58
+ ## 2. Install
59
+
60
+ ### Claude Desktop or Claude Code: plugin (recommended)
61
+
62
+ Add this repository as a plugin marketplace and install `polar`. In Claude Code:
63
+
64
+ ```
65
+ /plugin marketplace add kayaman/polar-mcp
66
+ /plugin install polar --marketplace kayaman/polar-mcp
67
+ ```
68
+
69
+ In Claude Desktop, add the `kayaman/polar-mcp` marketplace under **Settings → Plugins**,
70
+ or upload `polar-plugin.zip` from the [latest release](https://github.com/kayaman/polar-mcp/releases/latest).
71
+ Enter your client ID and secret when the plugin asks for them. If it doesn't, run
72
+ `uvx polar-mcp setup` once in a terminal. The plugin needs [uv](https://docs.astral.sh/uv/)
73
+ and runs on macOS and Linux; on Windows use the extension below.
74
+
75
+ ### Claude Desktop: extension
76
+
77
+ Download `polar-mcp.mcpb` from the [latest release](https://github.com/kayaman/polar-mcp/releases/latest),
78
+ open it with Claude Desktop (**Settings → Extensions**), and enter your client ID and secret.
79
+
80
+ ### Claude Code, or any MCP client
81
+
82
+ ```sh
83
+ uvx polar-mcp setup # saves your client ID/secret, then links your account
84
+ claude mcp add polar -s user -- uvx polar-mcp
85
+ ```
86
+
87
+ Other clients: run `uvx polar-mcp` as a stdio server. Credentials can also come from the
88
+ `POLAR_CLIENT_ID` and `POLAR_CLIENT_SECRET` environment variables.
89
+
90
+ ## 3. Use it
91
+
92
+ Just ask. When a tool needs your account and it isn't linked yet (or the token, which
93
+ lasts about a year, has expired), Polar Flow opens in your browser. Approve, the tab
94
+ says *"Polar linked"*, and Claude carries on. If you take longer than ~45 seconds,
95
+ Claude asks you to try again; the link is saved in the background either way.
96
+
97
+ Polar only serves recent data, and this server keeps no copy of it:
98
+
99
+ | Data | Tools | How far back |
100
+ |---|---|---|
101
+ | Workouts | `polar_list_exercises`, `polar_get_exercise`, `polar_export_exercise` | 30 days, **uploaded after you linked** |
102
+ | Sleep | `polar_list_sleep`, `polar_get_sleep` | 28 nights |
103
+ | Nightly Recharge (HRV, overnight HR, breathing) | `polar_list_nightly_recharge`, `polar_get_nightly_recharge` | 28 days |
104
+ | Cardio load (strain, tolerance) | `polar_list_cardio_load` | 28 days |
105
+ | SleepWise (alertness, bedtime) | `polar_sleepwise_alertness`, `polar_sleepwise_circadian_bedtime` | 28 days |
106
+ | Daily activity (steps, calories, active time) | `polar_list_activities` | up to 365 days, any range |
107
+ | 24/7 heart rate | `polar_get_continuous_hr` (per-day summary or raw) | per date |
108
+ | Profile | `polar_get_user` | |
109
+
110
+ `polar_login_start` and `polar_login_finish` exist for re-linking on request, and for
111
+ the case where your client's redirect URL isn't on localhost. Then you paste the
112
+ address the browser ends on into the chat.
113
+
114
+ ## Command line
115
+
116
+ ```
117
+ polar-mcp run the MCP server on stdio (what MCP clients launch)
118
+ polar-mcp setup save your client ID/secret, then link your account
119
+ polar-mcp login link or re-link in the browser (--redirected URL to finish by hand)
120
+ polar-mcp status what's configured, whether you're linked, token expiry
121
+ polar-mcp logout forget the token (keeps the client credentials)
122
+ ```
123
+
124
+ ## Privacy
125
+
126
+ - Data flows only between your machine and Polar. There's no server in between and no
127
+ telemetry.
128
+ - Your client secret and Polar token are stored in `~/.config/polar-mcp/.env`, readable
129
+ only by you. Workouts you export go to `~/Downloads/polar` (override with
130
+ `POLAR_EXPORT_DIR`).
131
+ - What you ask about is sent to your AI client's model provider as part of the
132
+ conversation, like any other tool result.
133
+
134
+ See [SECURITY.md](SECURITY.md) for details and how to report a vulnerability.
135
+
136
+ ## Configuration
137
+
138
+ | Variable | Default | |
139
+ |---|---|---|
140
+ | `POLAR_CLIENT_ID`, `POLAR_CLIENT_SECRET` | from plugin settings or the env file | your API client |
141
+ | `POLAR_REDIRECT_PORT` | `8765` | must match the client's redirect URL |
142
+ | `POLAR_REDIRECT_URI` | unset | pin the redirect URI; unset lets Polar use the registered one |
143
+ | `POLAR_ENV_FILE` | `~/.config/polar-mcp/.env` | where credentials and the token live |
144
+ | `POLAR_EXPORT_DIR` | `~/Downloads/polar` | where exported workouts go |
145
+
146
+ ## Development
147
+
148
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Polar and AccessLink are trademarks of Polar
149
+ Electro Oy. Licensed under [MIT](LICENSE).
@@ -0,0 +1,120 @@
1
+ # polar-mcp
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/polar-mcp)](https://pypi.org/project/polar-mcp/)
4
+ [![CI](https://github.com/kayaman/polar-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/kayaman/polar-mcp/actions/workflows/ci.yml)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
+
7
+ An [MCP](https://modelcontextprotocol.io) server that lets Claude, or any MCP client,
8
+ read your **Polar** watch data through the
9
+ [Polar AccessLink API](https://www.polar.com/accesslink-api/): workouts, sleep, Nightly
10
+ Recharge and HRV, cardio load, daily activity and 24/7 heart rate.
11
+
12
+ > Ask *"How did I sleep this week?"*, *"Am I recovered enough for intervals today?"* or
13
+ > *"Compare my training load to last month"*. The first time, Polar Flow opens in your
14
+ > browser; click **Approve** and you're linked.
15
+
16
+ Read-only. Unofficial: not affiliated with or endorsed by Polar Electro Oy.
17
+
18
+ <!-- mcp-name: io.github.kayaman/polar-mcp -->
19
+
20
+ ## 1. Create your Polar API client (once, ~2 minutes)
21
+
22
+ Polar requires every app to have its own API client, so you create one for yourself:
23
+
24
+ 1. Sign in at [admin.polaraccesslink.com](https://admin.polaraccesslink.com) with your
25
+ Polar Flow account and create a client.
26
+ 2. Set its **redirect URL** to exactly `http://localhost:8765/callback`.
27
+ 3. Keep the **client ID** and **client secret** at hand for the next step.
28
+
29
+ ## 2. Install
30
+
31
+ ### Claude Desktop or Claude Code: plugin (recommended)
32
+
33
+ Add this repository as a plugin marketplace and install `polar`. In Claude Code:
34
+
35
+ ```
36
+ /plugin marketplace add kayaman/polar-mcp
37
+ /plugin install polar --marketplace kayaman/polar-mcp
38
+ ```
39
+
40
+ In Claude Desktop, add the `kayaman/polar-mcp` marketplace under **Settings → Plugins**,
41
+ or upload `polar-plugin.zip` from the [latest release](https://github.com/kayaman/polar-mcp/releases/latest).
42
+ Enter your client ID and secret when the plugin asks for them. If it doesn't, run
43
+ `uvx polar-mcp setup` once in a terminal. The plugin needs [uv](https://docs.astral.sh/uv/)
44
+ and runs on macOS and Linux; on Windows use the extension below.
45
+
46
+ ### Claude Desktop: extension
47
+
48
+ Download `polar-mcp.mcpb` from the [latest release](https://github.com/kayaman/polar-mcp/releases/latest),
49
+ open it with Claude Desktop (**Settings → Extensions**), and enter your client ID and secret.
50
+
51
+ ### Claude Code, or any MCP client
52
+
53
+ ```sh
54
+ uvx polar-mcp setup # saves your client ID/secret, then links your account
55
+ claude mcp add polar -s user -- uvx polar-mcp
56
+ ```
57
+
58
+ Other clients: run `uvx polar-mcp` as a stdio server. Credentials can also come from the
59
+ `POLAR_CLIENT_ID` and `POLAR_CLIENT_SECRET` environment variables.
60
+
61
+ ## 3. Use it
62
+
63
+ Just ask. When a tool needs your account and it isn't linked yet (or the token, which
64
+ lasts about a year, has expired), Polar Flow opens in your browser. Approve, the tab
65
+ says *"Polar linked"*, and Claude carries on. If you take longer than ~45 seconds,
66
+ Claude asks you to try again; the link is saved in the background either way.
67
+
68
+ Polar only serves recent data, and this server keeps no copy of it:
69
+
70
+ | Data | Tools | How far back |
71
+ |---|---|---|
72
+ | Workouts | `polar_list_exercises`, `polar_get_exercise`, `polar_export_exercise` | 30 days, **uploaded after you linked** |
73
+ | Sleep | `polar_list_sleep`, `polar_get_sleep` | 28 nights |
74
+ | Nightly Recharge (HRV, overnight HR, breathing) | `polar_list_nightly_recharge`, `polar_get_nightly_recharge` | 28 days |
75
+ | Cardio load (strain, tolerance) | `polar_list_cardio_load` | 28 days |
76
+ | SleepWise (alertness, bedtime) | `polar_sleepwise_alertness`, `polar_sleepwise_circadian_bedtime` | 28 days |
77
+ | Daily activity (steps, calories, active time) | `polar_list_activities` | up to 365 days, any range |
78
+ | 24/7 heart rate | `polar_get_continuous_hr` (per-day summary or raw) | per date |
79
+ | Profile | `polar_get_user` | |
80
+
81
+ `polar_login_start` and `polar_login_finish` exist for re-linking on request, and for
82
+ the case where your client's redirect URL isn't on localhost. Then you paste the
83
+ address the browser ends on into the chat.
84
+
85
+ ## Command line
86
+
87
+ ```
88
+ polar-mcp run the MCP server on stdio (what MCP clients launch)
89
+ polar-mcp setup save your client ID/secret, then link your account
90
+ polar-mcp login link or re-link in the browser (--redirected URL to finish by hand)
91
+ polar-mcp status what's configured, whether you're linked, token expiry
92
+ polar-mcp logout forget the token (keeps the client credentials)
93
+ ```
94
+
95
+ ## Privacy
96
+
97
+ - Data flows only between your machine and Polar. There's no server in between and no
98
+ telemetry.
99
+ - Your client secret and Polar token are stored in `~/.config/polar-mcp/.env`, readable
100
+ only by you. Workouts you export go to `~/Downloads/polar` (override with
101
+ `POLAR_EXPORT_DIR`).
102
+ - What you ask about is sent to your AI client's model provider as part of the
103
+ conversation, like any other tool result.
104
+
105
+ See [SECURITY.md](SECURITY.md) for details and how to report a vulnerability.
106
+
107
+ ## Configuration
108
+
109
+ | Variable | Default | |
110
+ |---|---|---|
111
+ | `POLAR_CLIENT_ID`, `POLAR_CLIENT_SECRET` | from plugin settings or the env file | your API client |
112
+ | `POLAR_REDIRECT_PORT` | `8765` | must match the client's redirect URL |
113
+ | `POLAR_REDIRECT_URI` | unset | pin the redirect URI; unset lets Polar use the registered one |
114
+ | `POLAR_ENV_FILE` | `~/.config/polar-mcp/.env` | where credentials and the token live |
115
+ | `POLAR_EXPORT_DIR` | `~/Downloads/polar` | where exported workouts go |
116
+
117
+ ## Development
118
+
119
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Polar and AccessLink are trademarks of Polar
120
+ Electro Oy. Licensed under [MIT](LICENSE).
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "polar-mcp"
3
+ version = "0.5.0"
4
+ description = "MCP server for the Polar AccessLink API: let Claude (or any MCP client) read your Polar workouts, sleep, Nightly Recharge, HRV and daily activity."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "Marco Antonio Gonzalez Junior" }]
10
+ keywords = ["mcp", "model-context-protocol", "polar", "accesslink", "claude", "fitness", "sleep", "hrv", "wearables"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Environment :: Console",
14
+ "Intended Audience :: End Users/Desktop",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Topic :: Utilities",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = [
26
+ # <2: the 2.x SDK removed mcp.server.fastmcp
27
+ "mcp>=1.10,<2",
28
+ "httpx>=0.27",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/kayaman/polar-mcp"
33
+ Repository = "https://github.com/kayaman/polar-mcp"
34
+ Issues = "https://github.com/kayaman/polar-mcp/issues"
35
+ Changelog = "https://github.com/kayaman/polar-mcp/blob/main/CHANGELOG.md"
36
+
37
+ [project.scripts]
38
+ polar-mcp = "polar_mcp.cli:main"
39
+
40
+ [dependency-groups]
41
+ dev = [
42
+ "mcp[cli]>=1.10,<2",
43
+ "pytest>=8",
44
+ "pytest-asyncio>=0.24",
45
+ "respx>=0.21",
46
+ "ruff>=0.6",
47
+ "mypy>=1.11",
48
+ ]
49
+
50
+ [build-system]
51
+ requires = ["hatchling>=1.27"]
52
+ build-backend = "hatchling.build"
53
+
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["src/polar_mcp"]
56
+
57
+ [tool.hatch.build.targets.sdist]
58
+ include = ["src", "tests", "README.md", "LICENSE", "CHANGELOG.md", "pyproject.toml"]
59
+
60
+ [tool.pytest.ini_options]
61
+ asyncio_mode = "auto"
62
+ asyncio_default_fixture_loop_scope = "function"
63
+
64
+ [tool.ruff]
65
+ line-length = 100
66
+ target-version = "py311"
67
+
68
+ [tool.ruff.lint]
69
+ select = ["E", "F", "I", "B", "UP", "SIM", "RUF"]
70
+ ignore = ["E501"]
71
+
72
+ [tool.mypy]
73
+ python_version = "3.11"
74
+ files = ["src/polar_mcp"]
75
+ check_untyped_defs = true
76
+ warn_unused_ignores = true
77
+ warn_redundant_casts = true
78
+ show_error_codes = true
@@ -0,0 +1,8 @@
1
+ """polar-mcp: an MCP server for the Polar AccessLink API."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("polar-mcp")
7
+ except PackageNotFoundError: # running from a source tree that isn't installed
8
+ __version__ = "0.0.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,130 @@
1
+ """Thin async client for Polar AccessLink v3.
2
+
3
+ Every request goes to API_BASE + a path that passes `check_path`, so the bearer
4
+ token can't be sent anywhere else. Only the non-transactional (read-and-keep)
5
+ endpoints are used: nothing here ever commits a transaction, so asking Claude
6
+ about your data never consumes it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from datetime import UTC, datetime, timedelta
13
+ from typing import Any
14
+
15
+ import httpx
16
+
17
+ from .config import API_BASE, USER_AGENT, Settings
18
+
19
+ EXPIRY_WARN_DAYS = 14
20
+
21
+ _SAFE_PATH = re.compile(r"^[A-Za-z0-9_\-/]+$")
22
+ _SAFE_ID = re.compile(r"^[A-Za-z0-9]+$")
23
+
24
+
25
+ class PolarError(Exception):
26
+ """A failure Claude should see as a tool error, with a hint on how to fix it."""
27
+
28
+
29
+ class AuthRequired(PolarError):
30
+ """No token yet, or Polar rejected it (401): the account has to be (re)linked."""
31
+
32
+
33
+ class NoData(Exception):
34
+ """Polar answered, but there is nothing for that date/range (204/404)."""
35
+
36
+
37
+ def check_path(path: str) -> str:
38
+ """Only allow relative API paths like 'users/sleep' or 'exercises/abc123'."""
39
+ path = path.strip().strip("/")
40
+ if not path or not _SAFE_PATH.fullmatch(path) or ".." in path:
41
+ raise ValueError(f"invalid API path {path!r}")
42
+ return path
43
+
44
+
45
+ def check_id(value: str) -> str:
46
+ if not _SAFE_ID.fullmatch(value or ""):
47
+ raise ValueError(
48
+ f"invalid exercise id {value!r}: expected the hashed id from polar_list_exercises"
49
+ )
50
+ return value
51
+
52
+
53
+ class PolarClient:
54
+ def __init__(self, settings: Settings, transport: httpx.AsyncBaseTransport | None = None):
55
+ self.settings = settings
56
+ self._http = httpx.AsyncClient(
57
+ base_url=API_BASE,
58
+ headers={
59
+ "Authorization": f"Bearer {settings.access_token}",
60
+ "Accept": "application/json",
61
+ "User-Agent": USER_AGENT,
62
+ },
63
+ timeout=60,
64
+ transport=transport,
65
+ )
66
+
67
+ @property
68
+ def user_id(self) -> str:
69
+ if not self.settings.user_id:
70
+ raise AuthRequired("Polar account not linked: call polar_login_start")
71
+ return self.settings.user_id
72
+
73
+ def expiry_warning(self, now: datetime | None = None) -> str | None:
74
+ exp = self.settings.token_expires_at
75
+ if exp is None:
76
+ return None
77
+ now = now or datetime.now(UTC)
78
+ left = exp - now
79
+ if left <= timedelta(0):
80
+ return "Polar token has expired: call polar_login_start to re-link"
81
+ if left <= timedelta(days=EXPIRY_WARN_DAYS):
82
+ return f"Polar token expires in {left.days} day(s): call polar_login_start soon"
83
+ return None
84
+
85
+ async def _request(self, path: str, params: dict | None, accept: str | None) -> httpx.Response:
86
+ if not self.settings.access_token:
87
+ raise AuthRequired("No Polar token yet: call polar_login_start")
88
+ headers = {"Accept": accept} if accept else None
89
+ try:
90
+ r = await self._http.get(check_path(path), params=params, headers=headers)
91
+ except httpx.HTTPError as e:
92
+ raise PolarError(f"Could not reach Polar AccessLink: {e}") from e
93
+ if r.status_code in (204, 404):
94
+ raise NoData()
95
+ if r.status_code == 401:
96
+ raise AuthRequired(
97
+ "Polar rejected the token (401): it expired or was revoked. Call polar_login_start to re-link."
98
+ )
99
+ if r.status_code == 403:
100
+ raise PolarError(
101
+ "Polar says not all mandatory consents are accepted (403). Open Polar Flow, accept them, then retry."
102
+ )
103
+ if r.status_code == 429:
104
+ raise PolarError("Polar rate limit hit (429). Wait a few minutes and retry.")
105
+ if r.status_code >= 400:
106
+ raise PolarError(f"Polar returned {r.status_code}: {r.text[:500]}")
107
+ return r
108
+
109
+ async def get_json(self, path: str, params: dict | None = None) -> Any:
110
+ r = await self._request(path, _clean(params), None)
111
+ return r.json()
112
+
113
+ async def get_bytes(self, path: str, accept: str) -> bytes:
114
+ r = await self._request(path, None, accept)
115
+ return r.content
116
+
117
+ async def aclose(self) -> None:
118
+ await self._http.aclose()
119
+
120
+
121
+ def _clean(params: dict | None) -> dict | None:
122
+ """Drop unset params and send booleans the way AccessLink expects ('true')."""
123
+ if not params:
124
+ return None
125
+ out = {}
126
+ for k, v in params.items():
127
+ if v is None or v is False:
128
+ continue
129
+ out[k] = "true" if v is True else str(v)
130
+ return out or None