mapnetwork-mcp 1.2.2__tar.gz → 1.2.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mapnetwork-mcp
3
- Version: 1.2.2
3
+ Version: 1.2.3
4
4
  Summary: MCP server — generate styled map images via mapnetwork.app
5
5
  Project-URL: Homepage, https://mapnetwork.app
6
6
  Project-URL: Repository, https://github.com/toruproject/mapnetwork-mcp
@@ -2,7 +2,7 @@
2
2
  "manifest_version": "0.4",
3
3
  "name": "mapnetwork-mcp",
4
4
  "display_name": "MapNetwork",
5
- "version": "1.2.2",
5
+ "version": "1.2.3",
6
6
  "description": "Generate styled PNG/SVG map images of any location with 11 customizable color themes.",
7
7
  "long_description": "MCP server for MapNetwork — generate styled map images (PNG / SVG) for any location on Earth, directly from Claude.\n\n- Generate maps from a place name, coordinates, or a list of markers\n- 11 color themes (white, darkBlue, darkGreen, popArt, lightBlue, lightGreen, beige, magenta, gray, black, brawn)\n- Overlay walking / driving routes on the map\n- PNG or SVG output, saved to your Downloads folder\n- Re-download a previously generated map in a different theme or format without regenerating\n- Open any generated map in the MapNetwork web editor for manual customization",
8
8
  "author": {
@@ -14,6 +14,13 @@ from pydantic import BaseModel, ConfigDict, Field
14
14
  BASE_URL = os.environ.get("MAPNETWORK_BASE_URL", "https://mapnetwork.app")
15
15
  POLL_INTERVAL_SEC = 10.0
16
16
  MAX_WAIT_SEC = 600
17
+ # MCPクライアントによっては、report_progressで進捗通知を送ってもtools/call自体の
18
+ # クライアント側タイムアウトを延長してくれない(60秒固定のクライアントで実測確認済み)。
19
+ # そのため generate_map は内部ポーリングをこの秒数までに打ち切り、まだ終わっていなければ
20
+ # dataKeyを返してcheck_map_statusでの確認をモデルに促す。60秒に対して十分な余裕を残す値にする。
21
+ INITIAL_WAIT_SEC = 40.0
22
+ # check_map_statusをモデルが連打しても機械的に間隔が空くようにする最低待機時間
23
+ CHECK_THROTTLE_SEC = 5.0
17
24
 
18
25
  # layersは自由な多値配列にすると、モデルが「roadはhighway/driving/walkingの上位互換」
19
26
  # といった内部の組み合わせルールを知らないまま組み合わせを選んでしまう。
@@ -101,6 +108,12 @@ mcp = FastMCP(
101
108
  "2. Call `generate_map` with `route=<result>` and `markers=[result['from'], result['to']]`\n"
102
109
  "The route is drawn on top of all other layers. "
103
110
  "Add `'color': '#RRGGBB'` to the route dict to customise the line color.\n\n"
111
+ "## If generation is still in progress\n"
112
+ "For busy areas, `generate_map` may return before the map is ready, with a `dataKey` "
113
+ "and a message asking you to check back. In that case, wait about 20-30 seconds and "
114
+ "call `check_map_status(dataKey=...)` — do not call `generate_map` again for the same "
115
+ "location, that only starts a redundant duplicate job. Repeat `check_map_status` "
116
+ "(with the same wait between calls) until it returns the image.\n\n"
104
117
  "## Important: re-download without regenerating\n"
105
118
  "After generating a map, `generate_map` returns a `dataKey`. "
106
119
  "You can call `redownload_map` with that `dataKey` to get the same map in a different "
@@ -154,6 +167,56 @@ async def _download(client: httpx.AsyncClient, data_key: str, format: str,
154
167
  return resp.content
155
168
 
156
169
 
170
+ async def _poll_with_budget(
171
+ client: httpx.AsyncClient, data_key: str, budget_sec: float, ctx: Context | None,
172
+ ) -> str:
173
+ """dataKeyの状態をPOLL_INTERVAL_SEC間隔でbudget_sec以内までポーリングする。
174
+ "ready"/"failed"になればその時点で返す。budget_sec内に決着しなければ"pending"を
175
+ 返す(例外は投げない、呼び出し側で分岐する)。"""
176
+ if ctx is not None:
177
+ await ctx.report_progress(0, budget_sec, "Map generation queued...")
178
+ elapsed = 0.0
179
+ while elapsed < budget_sec:
180
+ await asyncio.sleep(POLL_INTERVAL_SEC)
181
+ elapsed += POLL_INTERVAL_SEC
182
+ status_resp = await client.get(
183
+ f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10
184
+ )
185
+ status = status_resp.json().get("status")
186
+ if status in ("ready", "failed"):
187
+ return status
188
+ if ctx is not None:
189
+ await ctx.report_progress(
190
+ elapsed, budget_sec, f"Map generation in progress... ({elapsed:.0f}s elapsed)"
191
+ )
192
+ return "pending"
193
+
194
+
195
+ def _build_success_result(image_bytes: bytes, out_path: Path, data_key: str) -> list:
196
+ out_path.write_bytes(image_bytes)
197
+ return [
198
+ Image(data=image_bytes, format="png"),
199
+ (
200
+ f"Map saved: {out_path}\n"
201
+ f"dataKey: {data_key}\n\n"
202
+ f"Open in editor: https://mapnetwork.app/generate?dataKey={data_key}\n\n"
203
+ f"Tip: call redownload_map(data_key='{data_key}', ...) to get this map "
204
+ f"in a different color_set or format (svg/png) without regenerating."
205
+ ),
206
+ ]
207
+
208
+
209
+ def _still_in_progress_result(data_key: str) -> list:
210
+ return [(
211
+ f"Map generation is still in progress (dataKey={data_key}). This can take a few "
212
+ "minutes for busy areas. Wait about 20-30 seconds, then call "
213
+ f"check_map_status(data_key='{data_key}') to check again — pass the same format/"
214
+ "color_set/canvas_width/canvas_height you used with generate_map, if any. "
215
+ "Do NOT call generate_map again for the same location — that starts a redundant "
216
+ "duplicate job and wastes time."
217
+ )]
218
+
219
+
157
220
  # ---------------------------------------------------------------------------
158
221
  # Tool: compute_route
159
222
  # ---------------------------------------------------------------------------
@@ -314,6 +377,11 @@ async def generate_map(
314
377
  After generation the dataKey is returned in the text result.
315
378
  Use redownload_map(dataKey=...) to get the same map in a different color or format
316
379
  without waiting for regeneration.
380
+
381
+ If generation is still running after a short wait, this returns a dataKey and asks
382
+ you to call check_map_status(dataKey=...) after a delay instead of returning the
383
+ image directly — do not call generate_map again for the same location in that case,
384
+ it would just start a redundant duplicate job.
317
385
  """
318
386
  has_center = place or (lat is not None and lng is not None)
319
387
  has_route_coords = route is not None and route.coords is not None and len(route.coords) >= 2
@@ -357,34 +425,20 @@ async def generate_map(
357
425
  raise RuntimeError(f"Request rejected ({resp.status_code}): {detail}")
358
426
  data_key = resp.json()["dataKey"]
359
427
 
360
- # 2. Poll until ready
361
- # ポーリング中に進捗通知を送らないと、クライアント側のタイムアウトが
362
- # (MAX_WAIT_SECより手前で)先に発火し、実際には裏で処理が続いているのに
363
- # クライアントには失敗したように見えてしまう。report_progressはprogressToken
364
- # が無いクライアントに対しては何もしない安全な呼び出しなので、常に呼んでよい。
365
- if ctx is not None:
366
- await ctx.report_progress(0, MAX_WAIT_SEC, "Map generation queued...")
367
- elapsed = 0.0
368
- while elapsed < MAX_WAIT_SEC:
369
- await asyncio.sleep(POLL_INTERVAL_SEC)
370
- elapsed += POLL_INTERVAL_SEC
371
- status_resp = await client.get(
372
- f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10
428
+ # 2. Poll, but only up to INITIAL_WAIT_SEC (安全のためMCPクライアントの典型的な
429
+ # 60秒タイムアウトより十分短くしてある)。多くの地図生成はこの範囲で終わるため、
430
+ # その場合はこの1回の呼び出しだけで完結する。間に合わなければ、ここで打ち切って
431
+ # dataKeyを返し、check_map_statusでの確認をモデルに促す(生成自体はバックエンドで
432
+ # 継続しているので、ここで諦めても失敗にはならない)。
433
+ status = await _poll_with_budget(client, data_key, INITIAL_WAIT_SEC, ctx)
434
+
435
+ if status == "failed":
436
+ raise RuntimeError(
437
+ f"Map generation failed (dataKey={data_key}). "
438
+ "Try a different location or smaller radius."
373
439
  )
374
- status = status_resp.json().get("status")
375
- if status == "ready":
376
- break
377
- if status == "failed":
378
- raise RuntimeError(
379
- f"Map generation failed (dataKey={data_key}). "
380
- "Try a different location or smaller radius."
381
- )
382
- if ctx is not None:
383
- await ctx.report_progress(
384
- elapsed, MAX_WAIT_SEC, f"Map generation in progress... ({elapsed:.0f}s elapsed)"
385
- )
386
- else:
387
- raise TimeoutError(f"Map generation timed out after {MAX_WAIT_SEC}s.")
440
+ if status == "pending":
441
+ return _still_in_progress_result(data_key)
388
442
 
389
443
  # 3. Download
390
444
  image_bytes = await _download(client, data_key, format, color_set,
@@ -398,19 +452,57 @@ async def generate_map(
398
452
  label = "_".join(m.label or "" for m in markers)[:40]
399
453
  else:
400
454
  label = "route"
401
- out_path = _make_filename(label, format)
402
- out_path.write_bytes(image_bytes)
455
+ return _build_success_result(image_bytes, _make_filename(label, format), data_key)
403
456
 
404
- return [
405
- Image(data=image_bytes, format="png" if format == "png" else "png"),
406
- (
407
- f"Map saved: {out_path}\n"
408
- f"dataKey: {data_key}\n\n"
409
- f"Open in editor: https://mapnetwork.app/generate?dataKey={data_key}\n\n"
410
- f"Tip: call redownload_map(data_key='{data_key}', ...) to get this map "
411
- f"in a different color_set or format (svg/png) without regenerating."
412
- ),
413
- ]
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # Tool: check_map_status
460
+ # ---------------------------------------------------------------------------
461
+
462
+ @mcp.tool()
463
+ async def check_map_status(
464
+ data_key: Annotated[
465
+ str,
466
+ "The dataKey returned by a generate_map call that reported it was still in progress.",
467
+ ],
468
+ color_set: Annotated[
469
+ str | None,
470
+ "Color theme, matching what generate_map was called with, if any.",
471
+ ] = None,
472
+ format: Annotated[
473
+ str,
474
+ "'png' or 'svg', matching what generate_map was called with.",
475
+ ] = "png",
476
+ canvas_width: Annotated[int | None, "Canvas width, matching what generate_map was called with, if any."] = None,
477
+ canvas_height: Annotated[int | None, "Canvas height, matching what generate_map was called with, if any."] = None,
478
+ ctx: Context = None,
479
+ ) -> list:
480
+ """Check whether a still-in-progress generate_map job has finished, and download it if so.
481
+
482
+ Only call this after generate_map reports it is still processing and gives you a
483
+ dataKey to check. Wait about 20-30 seconds between calls to this tool — do not call
484
+ it in a tight loop, and do not call generate_map again for the same location while a
485
+ job with this dataKey is still pending; that just starts a redundant duplicate job.
486
+ """
487
+ async with httpx.AsyncClient() as client:
488
+ # 連打されても機械的に間隔が空くようにする最低限のスロットル
489
+ await asyncio.sleep(CHECK_THROTTLE_SEC)
490
+ status_resp = await client.get(f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10)
491
+ status = status_resp.json().get("status")
492
+ if status == "failed":
493
+ raise RuntimeError(
494
+ f"Map generation failed (dataKey={data_key}). "
495
+ "Try a different location or smaller radius."
496
+ )
497
+ if status != "ready":
498
+ if ctx is not None:
499
+ await ctx.report_progress(0, 1, "Map generation still in progress...")
500
+ return _still_in_progress_result(data_key)
501
+
502
+ image_bytes = await _download(client, data_key, format, color_set,
503
+ canvas_width, canvas_height)
504
+
505
+ return _build_success_result(image_bytes, _make_filename(data_key, format), data_key)
414
506
 
415
507
 
416
508
  # ---------------------------------------------------------------------------
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mapnetwork-mcp"
3
- version = "1.2.2"
3
+ version = "1.2.3"
4
4
  description = "MCP server — generate styled map images via mapnetwork.app"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
File without changes
File without changes