supercarto 0.3.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,21 @@
1
+ node_modules/
2
+ dist/
3
+ *.tsbuildinfo
4
+ .DS_Store
5
+ .vitest/
6
+ coverage/
7
+ tmp/
8
+ test-dist/
9
+ smoke/
10
+
11
+ # Python
12
+ __pycache__/
13
+ *.py[cod]
14
+ .pytest_cache/
15
+ .mypy_cache/
16
+ .ruff_cache/
17
+ *.egg-info/
18
+ python/build/
19
+ python/dist/
20
+ .venv/
21
+ venv/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.5
2
+ Name: supercarto
3
+ Version: 0.3.0
4
+ Summary: LLM-native spatial middleware. Give an AI agent a map of any location on earth as a token-budgeted topological graph, with indoor floors, weather, and traffic.
5
+ Project-URL: Homepage, https://github.com/supercarto/supercarto
6
+ Project-URL: Repository, https://github.com/supercarto/supercarto
7
+ Project-URL: Issues, https://github.com/supercarto/supercarto/issues
8
+ Project-URL: Benchmark, https://github.com/supercarto/supercarto/blob/main/docs/benchmark.md
9
+ Author: supercarto contributors
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,geospatial,gis,indoor-maps,llm,mcp,openstreetmap,routing,token-efficiency,topology,traffic,weather
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: GIS
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.11; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
27
+ Requires-Dist: pytest>=8.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.6; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # supercarto (Python)
32
+
33
+ LLM-native spatial middleware for Python. Give an AI agent a map of any
34
+ location on earth as a token-budgeted topological graph it can reason over.
35
+
36
+ ```bash
37
+ pip install supercarto
38
+ ```
39
+
40
+ This package is a **client**. The map compilation, token budgeting, topology
41
+ work, and indoor graph live in the Node library, and this speaks MCP to it over
42
+ stdio. That is deliberate: those algorithms are the product, and a second
43
+ implementation in a second language would be a second thing to keep correct.
44
+
45
+ **Node 20 or newer is required to call anything.** `pip install` alone will
46
+ succeed; the error when you call will tell you exactly what to install.
47
+
48
+ ```bash
49
+ npm install -g supercarto # or: npx supercarto mcp
50
+ ```
51
+
52
+ ---
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ import asyncio
58
+ from supercarto import SuperCarto
59
+
60
+ async def main():
61
+ async with SuperCarto() as carto:
62
+ m = await carto.maplet(lat=35.6833, lon=139.7620, radius_m=400, budget=1500)
63
+ print(m.yaml)
64
+ print(f"{m.tokens} tokens, from {m.fetched_from}")
65
+
66
+ asyncio.run(main())
67
+ ```
68
+
69
+ ```
70
+ map:
71
+ center: "35.6833, 139.762"
72
+ radius: 400m
73
+ nodes:
74
+ n8: {type: transit, name: 芝浦ふ頭, tags: [station]}
75
+ edges:
76
+ n1->n2: {dist: 120m, dir: east, path: road}
77
+ omitted:
78
+ - {layer: feature, count: 1754}
79
+ ```
80
+
81
+ The budget holds. The server measures its own output and cuts until it fits, so
82
+ `m.tokens` will not exceed `m.budget`.
83
+
84
+ ### Routing
85
+
86
+ ```python
87
+ r = await carto.route(37.7749, -122.4194, 37.7849, -122.4194, mode="walk")
88
+
89
+ r.distance_m, r.duration_s
90
+ r.steps # ["1. head onto Mission St (120m)", ...]
91
+ r.source # "osrm", or "straight-line" for the labelled approximation
92
+ ```
93
+
94
+ ### Weather
95
+
96
+ No API key needed.
97
+
98
+ ```python
99
+ w = await carto.weather(35.6833, 139.7620, hours=12)
100
+
101
+ w.summary # "heavy rain"
102
+ w.precipitation # "rain" | "snow" | "sleet" | "hail" | "drizzle"
103
+ w.feels_like_c # what a person actually feels
104
+ w.advisory # prose, in the vocabulary of the decision
105
+ ```
106
+
107
+ ### Traffic
108
+
109
+ Needs `TOMTOM_API_KEY` or `HERE_API_KEY` in the environment.
110
+
111
+ ```python
112
+ t = await carto.traffic(37.7749, -122.4194, 37.7849, -122.4194)
113
+
114
+ if t.free_flow_only:
115
+ # No credential. The duration ignores congestion entirely. Do not quote it
116
+ # as an arrival time.
117
+ ...
118
+
119
+ t.worst_level # the segment that actually makes someone late
120
+ ```
121
+
122
+ `traffic()` raises `ToolError` when no credential is configured. That is on
123
+ purpose: a free-flow number returned as if it were live is the failure this
124
+ library exists to avoid.
125
+
126
+ ### Checking what is available
127
+
128
+ ```python
129
+ tools = await carto.tools()
130
+ ```
131
+
132
+ Worth doing before a loop. `get_traffic` is **absent** unless a flow credential
133
+ is present, and `get_weather` is **present** by default because its source needs
134
+ no key. A maplet lists exactly the tools this deployment can answer.
135
+
136
+ ---
137
+
138
+ ## In an agent framework
139
+
140
+ Any MCP client works; this package is for when you want the typed results.
141
+
142
+ ```python
143
+ # LangChain-style MCP config
144
+ {
145
+ "mcpServers": {
146
+ "supercarto": {"command": "npx", "args": ["supercarto", "mcp"]}
147
+ }
148
+ }
149
+ ```
150
+
151
+ ---
152
+
153
+ ## Configuration
154
+
155
+ Read from the environment by the server, so nothing is needed on the Python side.
156
+
157
+ ```
158
+ SUPERCARTO_PMTILES PMTiles archive; the production data source
159
+ OVERPASS_ENDPOINT your own Overpass instance
160
+ TOMTOM_API_KEY enables live traffic
161
+ HERE_API_KEY enables live traffic
162
+ ```
163
+
164
+ Point at a specific binary with `SUPERCARTO_SERVER_CMD`, or pass `command=[...]`
165
+ to the constructor. A relative or absolute path both work:
166
+
167
+ ```python
168
+ carto = SuperCarto(command=["node", "/opt/sc/dist/cli/main.js", "mcp"])
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Errors
174
+
175
+ | Exception | Meaning |
176
+ |---|---|
177
+ | `SuperCartoConnectionError` | The server could not start or did not respond. Your problem. |
178
+ | `ToolError` | The tool ran and reported a failure. Usually a real answer, like "traffic is not configured". |
179
+
180
+ They are deliberately distinct. Conflating them would make a retry loop hammer
181
+ a server that is behaving correctly.
182
+
183
+ ---
184
+
185
+ ## Zero dependencies
186
+
187
+ This package has no runtime dependencies, on purpose.
188
+
189
+ The `mcp` SDK pulls in httpx, pydantic, and their transitive trees. An agent
190
+ framework that already depends on any of those should not get a second copy at a
191
+ different version. Three JSON-RPC methods and one line-delimited framing are
192
+ small enough to implement directly, which is what `client.py` does.
193
+
194
+ The trade: `pip install supercarto` does not bring Node with it. Calling anything
195
+ raises a `SuperCartoConnectionError` that says so, with the fix, in one sentence.
196
+
197
+ ---
198
+
199
+ ## Links
200
+
201
+ - **npm:** https://www.npmjs.com/package/supercarto
202
+ - **Repository:** https://github.com/supercarto/supercarto
203
+ - **Benchmark:** https://github.com/supercarto/supercarto/blob/main/docs/benchmark.md
204
+
205
+ Apache-2.0
@@ -0,0 +1,175 @@
1
+ # supercarto (Python)
2
+
3
+ LLM-native spatial middleware for Python. Give an AI agent a map of any
4
+ location on earth as a token-budgeted topological graph it can reason over.
5
+
6
+ ```bash
7
+ pip install supercarto
8
+ ```
9
+
10
+ This package is a **client**. The map compilation, token budgeting, topology
11
+ work, and indoor graph live in the Node library, and this speaks MCP to it over
12
+ stdio. That is deliberate: those algorithms are the product, and a second
13
+ implementation in a second language would be a second thing to keep correct.
14
+
15
+ **Node 20 or newer is required to call anything.** `pip install` alone will
16
+ succeed; the error when you call will tell you exactly what to install.
17
+
18
+ ```bash
19
+ npm install -g supercarto # or: npx supercarto mcp
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Use
25
+
26
+ ```python
27
+ import asyncio
28
+ from supercarto import SuperCarto
29
+
30
+ async def main():
31
+ async with SuperCarto() as carto:
32
+ m = await carto.maplet(lat=35.6833, lon=139.7620, radius_m=400, budget=1500)
33
+ print(m.yaml)
34
+ print(f"{m.tokens} tokens, from {m.fetched_from}")
35
+
36
+ asyncio.run(main())
37
+ ```
38
+
39
+ ```
40
+ map:
41
+ center: "35.6833, 139.762"
42
+ radius: 400m
43
+ nodes:
44
+ n8: {type: transit, name: 芝浦ふ頭, tags: [station]}
45
+ edges:
46
+ n1->n2: {dist: 120m, dir: east, path: road}
47
+ omitted:
48
+ - {layer: feature, count: 1754}
49
+ ```
50
+
51
+ The budget holds. The server measures its own output and cuts until it fits, so
52
+ `m.tokens` will not exceed `m.budget`.
53
+
54
+ ### Routing
55
+
56
+ ```python
57
+ r = await carto.route(37.7749, -122.4194, 37.7849, -122.4194, mode="walk")
58
+
59
+ r.distance_m, r.duration_s
60
+ r.steps # ["1. head onto Mission St (120m)", ...]
61
+ r.source # "osrm", or "straight-line" for the labelled approximation
62
+ ```
63
+
64
+ ### Weather
65
+
66
+ No API key needed.
67
+
68
+ ```python
69
+ w = await carto.weather(35.6833, 139.7620, hours=12)
70
+
71
+ w.summary # "heavy rain"
72
+ w.precipitation # "rain" | "snow" | "sleet" | "hail" | "drizzle"
73
+ w.feels_like_c # what a person actually feels
74
+ w.advisory # prose, in the vocabulary of the decision
75
+ ```
76
+
77
+ ### Traffic
78
+
79
+ Needs `TOMTOM_API_KEY` or `HERE_API_KEY` in the environment.
80
+
81
+ ```python
82
+ t = await carto.traffic(37.7749, -122.4194, 37.7849, -122.4194)
83
+
84
+ if t.free_flow_only:
85
+ # No credential. The duration ignores congestion entirely. Do not quote it
86
+ # as an arrival time.
87
+ ...
88
+
89
+ t.worst_level # the segment that actually makes someone late
90
+ ```
91
+
92
+ `traffic()` raises `ToolError` when no credential is configured. That is on
93
+ purpose: a free-flow number returned as if it were live is the failure this
94
+ library exists to avoid.
95
+
96
+ ### Checking what is available
97
+
98
+ ```python
99
+ tools = await carto.tools()
100
+ ```
101
+
102
+ Worth doing before a loop. `get_traffic` is **absent** unless a flow credential
103
+ is present, and `get_weather` is **present** by default because its source needs
104
+ no key. A maplet lists exactly the tools this deployment can answer.
105
+
106
+ ---
107
+
108
+ ## In an agent framework
109
+
110
+ Any MCP client works; this package is for when you want the typed results.
111
+
112
+ ```python
113
+ # LangChain-style MCP config
114
+ {
115
+ "mcpServers": {
116
+ "supercarto": {"command": "npx", "args": ["supercarto", "mcp"]}
117
+ }
118
+ }
119
+ ```
120
+
121
+ ---
122
+
123
+ ## Configuration
124
+
125
+ Read from the environment by the server, so nothing is needed on the Python side.
126
+
127
+ ```
128
+ SUPERCARTO_PMTILES PMTiles archive; the production data source
129
+ OVERPASS_ENDPOINT your own Overpass instance
130
+ TOMTOM_API_KEY enables live traffic
131
+ HERE_API_KEY enables live traffic
132
+ ```
133
+
134
+ Point at a specific binary with `SUPERCARTO_SERVER_CMD`, or pass `command=[...]`
135
+ to the constructor. A relative or absolute path both work:
136
+
137
+ ```python
138
+ carto = SuperCarto(command=["node", "/opt/sc/dist/cli/main.js", "mcp"])
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Errors
144
+
145
+ | Exception | Meaning |
146
+ |---|---|
147
+ | `SuperCartoConnectionError` | The server could not start or did not respond. Your problem. |
148
+ | `ToolError` | The tool ran and reported a failure. Usually a real answer, like "traffic is not configured". |
149
+
150
+ They are deliberately distinct. Conflating them would make a retry loop hammer
151
+ a server that is behaving correctly.
152
+
153
+ ---
154
+
155
+ ## Zero dependencies
156
+
157
+ This package has no runtime dependencies, on purpose.
158
+
159
+ The `mcp` SDK pulls in httpx, pydantic, and their transitive trees. An agent
160
+ framework that already depends on any of those should not get a second copy at a
161
+ different version. Three JSON-RPC methods and one line-delimited framing are
162
+ small enough to implement directly, which is what `client.py` does.
163
+
164
+ The trade: `pip install supercarto` does not bring Node with it. Calling anything
165
+ raises a `SuperCartoConnectionError` that says so, with the fix, in one sentence.
166
+
167
+ ---
168
+
169
+ ## Links
170
+
171
+ - **npm:** https://www.npmjs.com/package/supercarto
172
+ - **Repository:** https://github.com/supercarto/supercarto
173
+ - **Benchmark:** https://github.com/supercarto/supercarto/blob/main/docs/benchmark.md
174
+
175
+ Apache-2.0
@@ -0,0 +1,77 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "supercarto"
7
+ version = "0.3.0"
8
+ description = "LLM-native spatial middleware. Give an AI agent a map of any location on earth as a token-budgeted topological graph, with indoor floors, weather, and traffic."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "supercarto contributors" }]
13
+ keywords = [
14
+ "llm",
15
+ "agents",
16
+ "mcp",
17
+ "geospatial",
18
+ "gis",
19
+ "openstreetmap",
20
+ "topology",
21
+ "token-efficiency",
22
+ "indoor-maps",
23
+ "routing",
24
+ "weather",
25
+ "traffic",
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Intended Audience :: Developers",
30
+ "License :: OSI Approved :: Apache Software License",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Programming Language :: Python :: 3.11",
34
+ "Programming Language :: Python :: 3.12",
35
+ "Programming Language :: Python :: 3.13",
36
+ "Topic :: Scientific/Engineering :: GIS",
37
+ "Topic :: Software Development :: Libraries",
38
+ ]
39
+
40
+ # Intentionally zero runtime dependencies.
41
+ #
42
+ # The Python package is a client for the Node MCP server over stdio. It speaks
43
+ # JSON-RPC itself rather than importing the `mcp` SDK, because that SDK pulls in
44
+ # httpx, pydantic, and their transitive trees, and an agent framework that
45
+ # already depends on any of them should not get a second copy.
46
+ #
47
+ # The consequence is that `pip install supercarto` does not require Node. Calling
48
+ # anything raises a clear error telling you to install it. That is a deliberate
49
+ # trade: one subprocess the agent already knows how to spawn, in exchange for an
50
+ # install that cannot conflict with anything.
51
+ dependencies = []
52
+
53
+ [project.optional-dependencies]
54
+ dev = ["pytest>=8.0", "pytest-asyncio>=0.24", "mypy>=1.11", "ruff>=0.6"]
55
+
56
+ [project.urls]
57
+ Homepage = "https://github.com/supercarto/supercarto"
58
+ Repository = "https://github.com/supercarto/supercarto"
59
+ Issues = "https://github.com/supercarto/supercarto/issues"
60
+ "Benchmark" = "https://github.com/supercarto/supercarto/blob/main/docs/benchmark.md"
61
+
62
+ [tool.hatch.build.targets.wheel]
63
+ packages = ["src/supercarto"]
64
+
65
+ [tool.hatch.build.targets.sdist]
66
+ include = ["src/supercarto", "README.md", "LICENSE"]
67
+
68
+ [tool.pytest.ini_options]
69
+ asyncio_mode = "auto"
70
+
71
+ [tool.ruff]
72
+ line-length = 100
73
+ target-version = "py310"
74
+
75
+ [tool.mypy]
76
+ python_version = "3.10"
77
+ strict = true
@@ -0,0 +1,49 @@
1
+ """supercarto - LLM-native spatial middleware for Python.
2
+
3
+ A thin, dependency-free client for the supercarto MCP server.
4
+
5
+ The design decision worth knowing about: this package does not reimplement
6
+ anything. The map compilation, the token budgeting, the topology work and the
7
+ indoor graph all live in the Node library, and this speaks JSON-RPC to it over
8
+ stdio. That is deliberate, because those algorithms are the product and a second
9
+ implementation in a second language would be a second thing to keep correct.
10
+
11
+ So the shape here is: start the server, call a tool, get back text an agent can
12
+ act on.
13
+
14
+ import asyncio
15
+ from supercarto import SuperCarto
16
+
17
+ async def main():
18
+ async with SuperCarto() as carto:
19
+ m = await carto.maplet(lat=35.6833, lon=139.7620, radius_m=400, budget=1500)
20
+ print(m.yaml)
21
+ print(m.tokens, "tokens")
22
+
23
+ asyncio.run(main())
24
+ """
25
+
26
+ from .client import (
27
+ ConnectionError as SuperCartoConnectionError,
28
+ MapletResult,
29
+ RouteResult,
30
+ SuperCarto,
31
+ ToolError,
32
+ TrafficResult,
33
+ WeatherResult,
34
+ default_server_command,
35
+ )
36
+
37
+ __version__ = "0.3.0"
38
+
39
+ __all__ = [
40
+ "MapletResult",
41
+ "RouteResult",
42
+ "SuperCarto",
43
+ "SuperCartoConnectionError",
44
+ "ToolError",
45
+ "TrafficResult",
46
+ "WeatherResult",
47
+ "default_server_command",
48
+ "__version__",
49
+ ]
@@ -0,0 +1,593 @@
1
+ """JSON-RPC client for the supercarto MCP server over stdio.
2
+
3
+ The protocol is three messages and a Content-Length-framed JSON body. That is
4
+ small enough to implement directly, which is why this package has no runtime
5
+ dependencies: importing an SDK here would force httpx and pydantic onto every
6
+ user, most of whom already have one of them at a different version.
7
+
8
+ What this module does care about is being honest when the server cannot start.
9
+ A Node binary that is missing is the single most likely failure for a new user,
10
+ and the error says so in one sentence with the fix, rather than surfacing an
11
+ ``FileNotFoundError`` from deep inside ``asyncio``.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import json
18
+ import os
19
+ import shutil
20
+ from dataclasses import dataclass, field
21
+ from typing import Any, AsyncIterator, Sequence
22
+
23
+ __all__ = [
24
+ "ConnectionError",
25
+ "MapletResult",
26
+ "RouteResult",
27
+ "SuperCarto",
28
+ "ToolError",
29
+ "TrafficResult",
30
+ "WeatherResult",
31
+ "default_server_command",
32
+ ]
33
+
34
+ # JSON-RPC method names as they appear on the wire.
35
+ _INITIALIZE = "initialize"
36
+ _TOOLS_LIST = "tools/list"
37
+ _TOOLS_CALL = "tools/call"
38
+ _NOTIFICATIONS_INITIALIZED = "notifications/initialized"
39
+
40
+
41
+ class ConnectionError(Exception):
42
+ """The MCP server could not be started or did not respond."""
43
+
44
+
45
+ class ToolError(Exception):
46
+ """A tool ran and reported a failure.
47
+
48
+ Kept distinct from :class:`ConnectionError` because the two mean different
49
+ things to a caller: a connection error is this client's problem, a tool error
50
+ is usually a real answer about the world, such as "traffic is not configured
51
+ for this deployment".
52
+ """
53
+
54
+
55
+ @dataclass
56
+ class MapletResult:
57
+ """A compiled, token-budgeted map graph."""
58
+
59
+ yaml: str
60
+ tokens: int
61
+ """Tokens the server reported. Always within the requested budget."""
62
+
63
+ budget: int
64
+ fetched_from: str
65
+ """Which upstream source answered. Useful when a latency is unexpected."""
66
+
67
+ warnings: list[str] = field(default_factory=list)
68
+ """Problems the source reported. A non-empty list means the map is partial."""
69
+
70
+
71
+ @dataclass
72
+ class RouteResult:
73
+ """Turn-by-turn directions as prose."""
74
+
75
+ mode: str
76
+ distance_m: int
77
+ duration_s: int
78
+ steps: list[str]
79
+ source: str
80
+ free_flow_only: bool = False
81
+ """True when no traffic source was configured, so the duration ignores
82
+ congestion. Check this before quoting an arrival time to anyone."""
83
+
84
+
85
+ @dataclass
86
+ class WeatherResult:
87
+ """Current conditions and a short forecast."""
88
+
89
+ summary: str
90
+ temp_c: float | None
91
+ feels_like_c: float | None
92
+ precipitation: str
93
+ wind_kmh: float | None
94
+ advisory: str
95
+ degraded: bool = False
96
+ """True when the forecast source was unreachable. ``temp_c`` is None then,
97
+ and the advisory says so. Do not read a missing reading as a dry day."""
98
+
99
+
100
+ @dataclass
101
+ class TrafficResult:
102
+ """Congestion and arrival time."""
103
+
104
+ level: str
105
+ worst_level: str
106
+ duration_s: int
107
+ free_flow_s: int
108
+ delay_s: int
109
+ free_flow_only: bool
110
+ unavailable: str | None = None
111
+
112
+
113
+ def default_server_command() -> list[str]:
114
+ """How to launch the server when the caller does not say.
115
+
116
+ Prefers an already-installed ``supercarto`` on PATH, because that is the
117
+ normal case after ``npm install -g supercarto``. Falls back to ``npx`` so a
118
+ user who has only pip-installed the Python package still works, at the cost
119
+ of a first-call download.
120
+ """
121
+ explicit = os.environ.get("SUPERCARTO_SERVER_CMD")
122
+ if explicit:
123
+ return explicit.split()
124
+
125
+ on_path = shutil.which("supercarto")
126
+ if on_path:
127
+ return [on_path, "mcp"]
128
+
129
+ if shutil.which("npx"):
130
+ return ["npx", "-y", "supercarto", "mcp"]
131
+
132
+ return ["supercarto", "mcp"]
133
+
134
+
135
+ class SuperCarto:
136
+ """An MCP client for supercarto.
137
+
138
+ Use it as an async context manager so the subprocess is always cleaned up::
139
+
140
+ async with SuperCarto() as carto:
141
+ await carto.maplet(lat=51.5, lon=-0.12)
142
+
143
+ Or manage ``start`` and ``close`` yourself if the lifetime is awkward to
144
+ express with ``async with``.
145
+ """
146
+
147
+ def __init__(
148
+ self,
149
+ command: Sequence[str] | None = None,
150
+ *,
151
+ env: dict[str, str] | None = None,
152
+ timeout_s: float = 90.0,
153
+ ) -> None:
154
+ self._command = list(command) if command else default_server_command()
155
+ self._env = {**os.environ, **(env or {})}
156
+ # Generous by default because a first request against the public Overpass
157
+ # instance genuinely takes 15-40 seconds, and a timeout shorter than
158
+ # that would fail on correct behaviour.
159
+ self._timeout_s = timeout_s
160
+ self._proc: asyncio.subprocess.Process | None = None
161
+ self._next_id = 1
162
+ self._tools: list[dict[str, Any]] | None = None
163
+ self._write_lock = asyncio.Lock()
164
+
165
+ async def __aenter__(self) -> SuperCarto:
166
+ await self.start()
167
+ return self
168
+
169
+ async def __aexit__(self, *exc: object) -> None:
170
+ await self.close()
171
+
172
+ async def start(self) -> None:
173
+ """Spawn the server and complete the MCP handshake."""
174
+ try:
175
+ self._proc = await asyncio.create_subprocess_exec(
176
+ *self._command,
177
+ stdin=asyncio.subprocess.PIPE,
178
+ stdout=asyncio.subprocess.PIPE,
179
+ stderr=asyncio.subprocess.DEVNULL,
180
+ env=self._env,
181
+ )
182
+ except FileNotFoundError as exc:
183
+ # The one error every new user hits, so it gets the one error worth
184
+ # writing well.
185
+ raise ConnectionError(
186
+ f"could not run {' '.join(self._command)!r}: command not found.\n"
187
+ "supercarto is a Node program. Install it with:\n"
188
+ " npm install -g supercarto\n"
189
+ "or set SUPERCARTO_SERVER_CMD to its full path."
190
+ ) from exc
191
+
192
+ await self._request(
193
+ _INITIALIZE,
194
+ {
195
+ "protocolVersion": "2024-11-05",
196
+ "capabilities": {},
197
+ "clientInfo": {"name": "supercarto-python", "version": "0.3.0"},
198
+ },
199
+ )
200
+ await self._notify(_NOTIFICATIONS_INITIALIZED, {})
201
+
202
+ async def close(self) -> None:
203
+ """Terminate the server."""
204
+ if self._proc is None:
205
+ return
206
+ if self._proc.returncode is None:
207
+ self._proc.terminate()
208
+ try:
209
+ # A short grace period before SIGKILL, so the server can close
210
+ # its own handles instead of being cut off mid-write.
211
+ await asyncio.wait_for(self._proc.wait(), timeout=5)
212
+ except asyncio.TimeoutError:
213
+ self._proc.kill()
214
+ await self._proc.wait()
215
+ self._proc = None
216
+ self._tools = None
217
+
218
+ async def tools(self) -> list[str]:
219
+ """Tool names this deployment actually offers.
220
+
221
+ Worth checking before a loop: ``get_traffic`` is absent unless a flow
222
+ credential is configured, and calling it anyway raises rather than
223
+ returning a plausible free-flow estimate.
224
+ """
225
+ if self._tools is None:
226
+ result = await self._request(_TOOLS_LIST, {})
227
+ self._tools = list(result.get("tools", []))
228
+ return [t["name"] for t in self._tools if "name" in t]
229
+
230
+ async def maplet(
231
+ self,
232
+ lat: float,
233
+ lon: float,
234
+ radius_m: int = 300,
235
+ budget: int = 1024,
236
+ layers: list[str] | None = None,
237
+ ) -> MapletResult:
238
+ """Fetch a map around a coordinate and compile it for an agent.
239
+
240
+ The budget is honoured: the server measures its own output and cuts until
241
+ it fits, so ``tokens`` will not exceed ``budget``.
242
+ """
243
+ args: dict[str, Any] = {"lat": lat, "lon": lon, "radiusM": radius_m, "budget": budget}
244
+ if layers:
245
+ args["layers"] = layers
246
+
247
+ text = await self._call("get_maplet", args)
248
+ return _parse_maplet(text, budget)
249
+
250
+ async def route(
251
+ self,
252
+ from_lat: float,
253
+ from_lon: float,
254
+ to_lat: float,
255
+ to_lon: float,
256
+ mode: str = "walk",
257
+ ) -> RouteResult:
258
+ """Turn-by-turn directions as prose, which a model reads better than geometry."""
259
+ text = await self._call(
260
+ "route",
261
+ {
262
+ "fromLat": from_lat,
263
+ "fromLon": from_lon,
264
+ "toLat": to_lat,
265
+ "toLon": to_lon,
266
+ "mode": mode,
267
+ },
268
+ )
269
+ return _parse_route(text)
270
+
271
+ async def search_places(
272
+ self,
273
+ lat: float,
274
+ lon: float,
275
+ radius_m: int = 300,
276
+ query: str | None = None,
277
+ limit: int = 20,
278
+ ) -> list[str]:
279
+ """Find named places near a coordinate. Cheaper than :meth:`maplet`."""
280
+ args: dict[str, Any] = {"lat": lat, "lon": lon, "radiusM": radius_m, "limit": limit}
281
+ if query:
282
+ args["query"] = query
283
+ text = await self._call("search_places", args)
284
+ return [line[2:].strip() for line in text.splitlines() if line.startswith("- ")]
285
+
286
+ async def weather(self, lat: float, lon: float, hours: int = 12) -> WeatherResult:
287
+ """Current conditions and forecast. Needs no API key.
288
+
289
+ Raises :class:`ToolError` if the forecast source is unreachable, rather
290
+ than returning a result that reads as a dry day.
291
+ """
292
+ text = await self._call("get_weather", {"lat": lat, "lon": lon, "hours": hours})
293
+ return _parse_weather(text)
294
+
295
+ async def traffic(
296
+ self, from_lat: float, from_lon: float, to_lat: float, to_lon: float
297
+ ) -> TrafficResult:
298
+ """Congestion and arrival time.
299
+
300
+ Raises :class:`ToolError` when no flow source is configured, because a
301
+ free-flow number returned as if it were live is the failure this library
302
+ exists to avoid.
303
+ """
304
+ text = await self._call(
305
+ "get_traffic",
306
+ {"fromLat": from_lat, "fromLon": from_lon, "toLat": to_lat, "toLon": to_lon},
307
+ )
308
+ return _parse_traffic(text)
309
+
310
+ async def _call(self, name: str, args: dict[str, Any]) -> str:
311
+ result = await self._request(_TOOLS_CALL, {"name": name, "arguments": args})
312
+ if result.get("isError"):
313
+ raise ToolError(_content_text(result) or f"{name} failed")
314
+
315
+ text = _content_text(result)
316
+ if not text:
317
+ raise ToolError(f"{name} returned no content")
318
+ return text
319
+
320
+ async def _request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
321
+ if self._proc is None or self._proc.stdin is None:
322
+ raise ConnectionError("server not started; call start() or use `async with`")
323
+
324
+ self._next_id += 1
325
+ request_id = self._next_id
326
+ payload = {"jsonrpc": "2.0", "id": request_id, "method": method, "params": params}
327
+ await self._write(payload)
328
+
329
+ # A timeout is not paranoia. A framing mismatch between client and server
330
+ # manifests as the server never answering at all, so without this the
331
+ # failure mode is an indefinite hang rather than an error message.
332
+ try:
333
+ deadline = asyncio.wait_for(
334
+ self._await_response(request_id), timeout=self._timeout_s
335
+ )
336
+ return await deadline
337
+ except asyncio.TimeoutError as exc:
338
+ raise ConnectionError(
339
+ f"no response to {method} after {self._timeout_s:g}s. "
340
+ "If this is a map request the upstream data source may be slow; "
341
+ "otherwise the client and server disagree about framing."
342
+ ) from exc
343
+
344
+ async def _await_response(self, request_id: int) -> dict[str, Any]:
345
+ while True:
346
+ message = await self._read_message()
347
+ # Skip anything that is not our response: the server is free to send
348
+ # notifications, and a log line on stdout would otherwise look like a
349
+ # reply.
350
+ if message.get("id") != request_id:
351
+ if "error" in message and message.get("id") is None:
352
+ raise ConnectionError(f"server error: {message['error']}")
353
+ continue
354
+ if "error" in message:
355
+ raise ConnectionError(f"{method} failed: {message['error']}")
356
+ result = message.get("result", {})
357
+ return result if isinstance(result, dict) else {}
358
+
359
+ async def _notify(self, method: str, params: dict[str, Any]) -> None:
360
+ await self._write({"jsonrpc": "2.0", "method": method, "params": params})
361
+
362
+ async def _write(self, payload: dict[str, Any]) -> None:
363
+ """Send one newline-delimited JSON message.
364
+
365
+ Newline framing rather than Content-Length headers. supercarto's server
366
+ writes `JSON.stringify(...) + "\\n"`, which is the simpler of the two
367
+ framings the MCP spec allows and the one this client has to match:
368
+ sending a Content-Length header to a newline reader hangs on the first
369
+ request, because the server treats the header line as a malformed message
370
+ and answers nothing.
371
+ """
372
+ if self._proc is None or self._proc.stdin is None:
373
+ raise ConnectionError("server not started; call start() or use `async with`")
374
+ # Serialised because stdin is a single stream: two interleaved writes
375
+ # would corrupt the line framing.
376
+ async with self._write_lock:
377
+ self._proc.stdin.write((json.dumps(payload, separators=(",", ":")) + "\n").encode())
378
+ await self._proc.stdin.drain()
379
+
380
+ async def _read_message(self) -> dict[str, Any]:
381
+ if self._proc is None or self._proc.stdout is None:
382
+ raise ConnectionError("server not started")
383
+
384
+ while True:
385
+ line = await self._proc.stdout.readline()
386
+ if not line:
387
+ code = self._proc.returncode
388
+ raise ConnectionError(f"server closed its output (exit code {code})")
389
+ text = line.decode().strip()
390
+ if text == "":
391
+ continue
392
+ try:
393
+ parsed = json.loads(text)
394
+ except json.JSONDecodeError as exc:
395
+ # Anything that is not JSON on stdout is a stray print. Skipping
396
+ # it is better than dying, since a log line from a dependency
397
+ # should not take down a working session.
398
+ continue
399
+ if isinstance(parsed, dict):
400
+ return parsed
401
+
402
+
403
+ def _content_text(result: dict[str, Any]) -> str:
404
+ content = result.get("content")
405
+ if not isinstance(content, list):
406
+ return ""
407
+ return "\n".join(
408
+ block.get("text", "") for block in content if isinstance(block, dict)
409
+ ).strip()
410
+
411
+
412
+ # ---------------------------------------------------------------------------
413
+ # Response parsing
414
+ #
415
+ # The MCP server returns text meant for a language model, so this parses prose
416
+ # rather than reading structured fields. That is a deliberate choice at both
417
+ # ends: the server emits prose because a model reads it better than a JSON blob,
418
+ # and this client parses it back with narrow patterns. Both halves are pinned by
419
+ # tests, so a change to the wording on one side fails loudly rather than
420
+ # silently returning None.
421
+ # ---------------------------------------------------------------------------
422
+
423
+
424
+ def _parse_maplet(text: str, budget: int) -> MapletResult:
425
+ header, sep, body = text.partition("\n\n")
426
+ # With no header at all, `partition` swallows the whole document as the
427
+ # header and returns an empty body. Detecting that case keeps a caller from
428
+ # receiving an empty map from a server that actually answered.
429
+ if not sep:
430
+ header, body = "", text
431
+
432
+ fetched_from = "unknown"
433
+ tokens = 0
434
+ warnings: list[str] = []
435
+
436
+ for line in header.splitlines():
437
+ if line.startswith("# maplet @"):
438
+ # The header carries the centre and the source in parentheses.
439
+ # Taking the last "(" group avoids splitting on the coordinate.
440
+ _, _, rest = line.partition("@")
441
+ tail = rest.strip()
442
+ _, _, trailing = tail.rpartition("(")
443
+ fetched_from = trailing.rstrip(")").strip() or tail
444
+ elif line.startswith("# tokens "):
445
+ # "tokens 749/1500 nodes 19 edges 34"
446
+ token_part = line.removeprefix("# tokens ").split()[0]
447
+ tokens = int(token_part.split("/")[0] or 0)
448
+ elif line.startswith("# WARNING: "):
449
+ warnings.append(line.removeprefix("# WARNING: "))
450
+
451
+ return MapletResult(
452
+ yaml=body,
453
+ tokens=tokens,
454
+ budget=budget,
455
+ fetched_from=fetched_from,
456
+ warnings=warnings,
457
+ )
458
+
459
+
460
+ def _parse_route(text: str) -> RouteResult:
461
+ mode = "walk"
462
+ distance = 0
463
+ duration = 0
464
+ source = "unknown"
465
+ steps: list[str] = []
466
+ free_flow_only = False
467
+
468
+ for line in text.splitlines():
469
+ if line.startswith("route ("):
470
+ # "route (walk) via osrm" carries both the mode and the source.
471
+ inner = line.removeprefix("route (").rstrip(")")
472
+ mode_part, _, source_part = inner.partition(") via ")
473
+ mode = mode_part.split()[0] if mode_part.split() else "walk"
474
+ source = source_part.strip() or source
475
+ elif line.startswith("total: "):
476
+ for part in line.removeprefix("total: ").split(", "):
477
+ value = part.split("m")[0].split("s")[0].strip()
478
+ if part.endswith("m"):
479
+ distance = int(value)
480
+ elif part.endswith("s"):
481
+ duration = int(value)
482
+ elif line[:1].isdigit() and "." in line:
483
+ steps.append(line.strip())
484
+
485
+ return RouteResult(
486
+ mode=mode,
487
+ distance_m=distance,
488
+ duration_s=duration,
489
+ steps=steps,
490
+ source=source,
491
+ free_flow_only=free_flow_only,
492
+ )
493
+
494
+
495
+ def _parse_weather(text: str) -> WeatherResult:
496
+ summary = "unknown"
497
+ temp: float | None = None
498
+ feels: float | None = None
499
+ precipitation = "unknown"
500
+ wind: float | None = None
501
+ advisory = ""
502
+
503
+ for line in text.splitlines():
504
+ if line.startswith("now: "):
505
+ body = line.removeprefix("now: ")
506
+ summary = body.split(",")[0].strip()
507
+ temp = _first_float(body)
508
+ feels = _nth_float(body, 1)
509
+ wind = _nth_float(body, 2)
510
+ elif line.startswith("precipitation: "):
511
+ value = line.removeprefix("precipitation: ").split(",")[0].strip()
512
+ precipitation = value.split()[0] or "unknown"
513
+ elif line.startswith("advisory: "):
514
+ advisory = line.removeprefix("advisory: ")
515
+
516
+ return WeatherResult(
517
+ summary=summary,
518
+ temp_c=temp,
519
+ feels_like_c=feels,
520
+ precipitation=precipitation,
521
+ wind_kmh=wind,
522
+ advisory=advisory,
523
+ )
524
+
525
+
526
+ def _parse_traffic(text: str) -> TrafficResult:
527
+ free_flow_only = "unknown" in text.splitlines()[0] if text else False
528
+ level = "unknown"
529
+ worst = "unknown"
530
+ duration = 0
531
+ free_flow = 0
532
+ delay = 0
533
+ unavailable = None
534
+
535
+ for line in text.splitlines():
536
+ if line.startswith("traffic: "):
537
+ level = line.removeprefix("traffic: ").split(" ")[0].strip()
538
+ if "worst segment" in line:
539
+ worst = line.split("worst segment ")[1].strip()
540
+ elif line.startswith("traffic "):
541
+ parts = line.split()
542
+ level = parts[1] if len(parts) > 1 else level
543
+ if "worst segment" in line:
544
+ worst = line.split("worst segment ")[1].strip()
545
+ elif line.startswith("free-flow estimate: "):
546
+ free_flow = _first_int(line)
547
+ elif line.startswith("duration: "):
548
+ body = line.removeprefix("duration: ")
549
+ duration = _first_int(body)
550
+ # "1500s including 900s of delay (free flow would be 600s)".
551
+ # Splitting on " including " rather than " of " avoids catching the
552
+ # "(free flow would be 600s)" tail, which is a different number.
553
+ if " including " in body:
554
+ delay = _first_int(body.split(" including ")[1])
555
+ elif line.startswith("note: "):
556
+ unavailable = line.removeprefix("note: ")
557
+
558
+ return TrafficResult(
559
+ level=level,
560
+ worst_level=worst,
561
+ duration_s=duration,
562
+ free_flow_s=free_flow or duration,
563
+ delay_s=delay,
564
+ free_flow_only=free_flow_only,
565
+ unavailable=unavailable,
566
+ )
567
+
568
+
569
+ def _first_float(text: str) -> float | None:
570
+ return _nth_float(text, 0)
571
+
572
+
573
+ def _nth_float(text: str, index: int) -> float | None:
574
+ """The index-th number in a string, or None.
575
+
576
+ Numbers are found with a strict pattern so the "C" in a temperature unit
577
+ does not count as part of a value and a street number in a name does not
578
+ shift the index.
579
+ """
580
+ import re
581
+
582
+ found = re.findall(r"-?\d+(?:\.\d+)?", text)
583
+ if index < len(found):
584
+ try:
585
+ return float(found[index])
586
+ except ValueError:
587
+ return None
588
+ return None
589
+
590
+
591
+ def _first_int(text: str) -> int:
592
+ value = _nth_float(text, 0)
593
+ return int(value) if value is not None else 0