mapnetwork-mcp 3.0.0__tar.gz → 5.0.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.
Files changed (23) hide show
  1. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/PKG-INFO +1 -1
  2. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/manifest.json +12 -4
  3. mapnetwork_mcp-5.0.0/mapnetwork_mcp/server.py +430 -0
  4. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/pyproject.toml +1 -1
  5. mapnetwork_mcp-5.0.0/spec/input_schema.json +106 -0
  6. mapnetwork_mcp-5.0.0/spec/output_schema.json +221 -0
  7. mapnetwork_mcp-5.0.0/uv.lock +819 -0
  8. mapnetwork_mcp-3.0.0/mapnetwork_mcp/server.py +0 -413
  9. mapnetwork_mcp-3.0.0/spec/input_schema.json +0 -158
  10. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/.github/workflows/workflow.yml +0 -0
  11. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/.gitignore +0 -0
  12. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/.mcpbignore +0 -0
  13. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/LICENSE +0 -0
  14. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/README.md +0 -0
  15. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/RELEASING.md +0 -0
  16. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/SECURITY.md +0 -0
  17. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-black.png +0 -0
  18. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-darkGreen.png +0 -0
  19. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-grey.png +0 -0
  20. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-lightGreen.png +0 -0
  21. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-popArt.png +0 -0
  22. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/images/Kanazawa21Museum-white.png +0 -0
  23. {mapnetwork_mcp-3.0.0 → mapnetwork_mcp-5.0.0}/mapnetwork_mcp/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mapnetwork-mcp
3
- Version: 3.0.0
3
+ Version: 5.0.0
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": "3.0.0",
5
+ "version": "5.0.0",
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": {
@@ -25,11 +25,19 @@
25
25
  "tools": [
26
26
  {
27
27
  "name": "generate_map",
28
- "description": "Generate a styled map image for a location and save it to Downloads"
28
+ "description": "Generate a styled map image centered on a single place and save it to Downloads"
29
29
  },
30
30
  {
31
- "name": "compute_route",
32
- "description": "Compute a walking or driving route between two locations"
31
+ "name": "generate_markers_map",
32
+ "description": "Generate a map with multiple pinned locations"
33
+ },
34
+ {
35
+ "name": "generate_route_map",
36
+ "description": "Compute a walking or driving route between two places and generate a map with it overlaid"
37
+ },
38
+ {
39
+ "name": "check_map_status",
40
+ "description": "Poll a pending map generation job and download it once ready"
33
41
  },
34
42
  {
35
43
  "name": "redownload_map",
@@ -0,0 +1,430 @@
1
+ """MCP server for MapNetwork — generates styled map images from a place name or coordinates."""
2
+
3
+ import asyncio
4
+ import os
5
+ import re
6
+ import sys
7
+ import threading
8
+ import time
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from typing import Annotated, Literal
12
+
13
+ import httpx
14
+ from mcp.server.fastmcp import Context, FastMCP, Image
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+ BASE_URL = os.environ.get("MAPNETWORK_BASE_URL", "https://mapnetwork.app")
18
+ POLL_INTERVAL_SEC = 10.0
19
+ MAX_WAIT_SEC = 600
20
+ # MCPクライアントによっては、report_progressで進捗通知を送ってもtools/call自体の
21
+ # クライアント側タイムアウトを延長してくれない(60秒固定のクライアントで実測確認済み)。
22
+ # そのため generate_* は内部ポーリングをこの秒数までに打ち切り、まだ終わっていなければ
23
+ # dataKeyを返してcheck_map_statusでの確認をモデルに促す。60秒に対して十分な余裕を残す値にする。
24
+ INITIAL_WAIT_SEC = 40.0
25
+ # check_map_statusをモデルが連打しても機械的に間隔が空くようにする最低待機時間
26
+ CHECK_THROTTLE_SEC = 5.0
27
+
28
+
29
+ # extra="forbid": 未知のキー(例えばmarkerの'label'と紛れて'place'を書いてしまう等)を
30
+ # Pydanticが黙って無視せずバリデーションエラーとして返す。tools/callがエラーで返れば
31
+ # モデルは次の呼び出しで自己修正できるが、黙って無視されるとその機会が失われる
32
+ # (実運用でmarkersの各要素に存在しない'place'キーが紛れ込む事故が実際に発生し、
33
+ # extra="ignore"がデフォルトのため気づかれずに黙って無視されていたことが判明した)。
34
+
35
+ class Marker(BaseModel):
36
+ """generate_markers_mapのマーカー。labelは必須、linkは任意で公式サイトURLを付けられる
37
+ (バックエンド側がPlaces APIで自動補完する場合も多いが、モデルが確度高く知っている場合は
38
+ 明示的に渡してもよい)。link無しのマーカーが混在してもよい(むしろ通常はこちら)。"""
39
+ model_config = ConfigDict(extra="forbid")
40
+
41
+ label: str = Field(description="Place name to geocode and display.")
42
+ link: str | None = Field(
43
+ default=None,
44
+ description="Optional: the marker's official website URL, if known. See server instructions.",
45
+ )
46
+
47
+
48
+ mcp = FastMCP(
49
+ "MapNetwork",
50
+ instructions=(
51
+ "You have access to MapNetwork, which generates styled map images (PNG) "
52
+ "for any location on Earth.\n\n"
53
+ "## Key capabilities — pick the tool that matches what you need\n"
54
+ "- **Single location**: `generate_map(place=...)` — centers a map on one place.\n"
55
+ "- **Multiple pinned locations**: `generate_markers_map(markers=[{\"label\": ...}, ...])` — "
56
+ "pins several places on one map. Each marker needs a `label`, and may optionally include "
57
+ "`link` (its official website URL, if known) to make that pin a clickable link in the "
58
+ "result's 'Open in editor' link. Use this whenever the user asks to show multiple places "
59
+ "on a single map, or wants a map they (or someone else) can click through to visit the "
60
+ "pinned places' websites.\n"
61
+ "- **Walking/driving route**: `generate_route_map(from=..., to=..., mode=...)` — computes a "
62
+ "route between two places and draws it on the map.\n"
63
+ "- Every generate_* call produces a PNG at the default color theme — see 'Important: "
64
+ "re-download without regenerating' below to change the theme or format without regenerating.\n\n"
65
+ "## If generation is still in progress\n"
66
+ "For busy areas, any generate_* tool may return before the map is ready, with a `dataKey` "
67
+ "and a message asking you to check back. In that case, wait about 10-20 seconds and "
68
+ "call `check_map_status(data_key=...)` — do not call the generate_* tool again for the same "
69
+ "request, that only starts a redundant duplicate job. Repeat `check_map_status` "
70
+ "(with the same wait between calls) until it returns the image.\n\n"
71
+ "## Important: re-download without regenerating\n"
72
+ "After generating a map, the tool returns a `dataKey`. "
73
+ "You can call `redownload_map` with that `dataKey` to get the same map in a different "
74
+ "color theme or format (png/svg) — **no regeneration needed**. "
75
+ "Use this when the user asks to change only the appearance after already generating the map. "
76
+ "MapNetwork supports 11 color themes (white, darkBlue, darkGreen, popArt, lightBlue, "
77
+ "lightGreen, beige, magenta, gray, black, brawn).\n\n"
78
+ "## Sharing the generated map\n"
79
+ "Every successful result includes a Download link and an 'Open in editor' link — "
80
+ "mention both to the user.\n\n"
81
+ "## Parameter discipline\n"
82
+ "- **place/label**: `place`, a marker's `label`, and route's `from`/`to` must each be a "
83
+ "place name specific enough for the server to geocode it to a single, unambiguous "
84
+ "location (e.g. a full venue or station name, not a vague or generic term like "
85
+ "\"the station\" or \"a nearby cafe\")."
86
+ ),
87
+ )
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # Helpers
91
+ # ---------------------------------------------------------------------------
92
+
93
+ def _make_filename(label: str, format: str) -> Path:
94
+ slug = re.sub(r"_+", "_", re.sub(r"[^\w぀-鿿]", "_", label)).strip("_")[:40]
95
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
96
+ out_dir = Path.home() / "Downloads"
97
+ out_dir.mkdir(exist_ok=True)
98
+ return out_dir / f"map_{slug}_{timestamp}.{format}"
99
+
100
+
101
+ async def _download(client: httpx.AsyncClient, data_key: str, format: str,
102
+ color_set: str | None) -> bytes:
103
+ params: dict = {"dataKey": data_key, "format": format}
104
+ if color_set is not None:
105
+ params["colorSet"] = color_set
106
+ resp = await client.get(f"{BASE_URL}/download", params=params, timeout=60)
107
+ if resp.status_code != 200:
108
+ raise RuntimeError(f"Download failed ({resp.status_code}): {resp.text}")
109
+ return resp.content
110
+
111
+
112
+ async def _has_any_link(client: httpx.AsyncClient, data_key: str) -> bool:
113
+ """dataKeyの生成結果(placeDict)にlinkを持つエントリが1つでもあるか判定する。
114
+ Web UIの共有リンク機能が使うAPIを流用する(MCP生成データも同じSTORE_DIR配下に
115
+ 保存されるため、dataKeyを指定すればWeb UI側からも同じデータが取得できる)。
116
+ どのツールを呼んだかではなく、実際に生成されたデータで判定する。"""
117
+ try:
118
+ resp = await client.get(f"{BASE_URL}/api/upd/download", params={"dataKey": data_key}, timeout=10)
119
+ if resp.status_code != 200:
120
+ return False
121
+ place_dict = resp.json().get("placeDict", {})
122
+ return any(isinstance(p, dict) and p.get("link") for p in place_dict.values())
123
+ except Exception:
124
+ return False
125
+
126
+
127
+ async def _poll_with_budget(
128
+ client: httpx.AsyncClient, data_key: str, budget_sec: float, ctx: Context | None,
129
+ ) -> str:
130
+ """dataKeyの状態をPOLL_INTERVAL_SEC間隔でbudget_sec以内までポーリングする。
131
+ "ready"/"failed"になればその時点で返す。budget_sec内に決着しなければ"pending"を
132
+ 返す(例外は投げない、呼び出し側で分岐する)。"""
133
+ if ctx is not None:
134
+ await ctx.report_progress(0, budget_sec, "Map generation queued...")
135
+ elapsed = 0.0
136
+ while elapsed < budget_sec:
137
+ await asyncio.sleep(POLL_INTERVAL_SEC)
138
+ elapsed += POLL_INTERVAL_SEC
139
+ status_resp = await client.get(
140
+ f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10
141
+ )
142
+ status = status_resp.json().get("status")
143
+ if status in ("ready", "failed"):
144
+ return status
145
+ if ctx is not None:
146
+ await ctx.report_progress(
147
+ elapsed, budget_sec, f"Map generation in progress... ({elapsed:.0f}s elapsed)"
148
+ )
149
+ return "pending"
150
+
151
+
152
+ def _build_success_result(image_bytes: bytes, out_path: Path, data_key: str, has_link: bool) -> list:
153
+ out_path.write_bytes(image_bytes)
154
+ # linkを持つマーカーが1つでもあれば、"Open in editor"を閲覧専用(lock)モードのURLにする。
155
+ # どのツールを呼んだかではなく実際に生成されたplaceDictの中身で判定している(_has_any_link)。
156
+ editor_url = f"https://mapnetwork.app/generate?dataKey={data_key}"
157
+ if has_link:
158
+ editor_url += "&lock=true"
159
+ download_url = f"https://mapnetwork.app/download?dataKey={data_key}"
160
+ return [
161
+ Image(data=image_bytes, format="png"),
162
+ (
163
+ f"Map saved: {out_path}\n"
164
+ f"dataKey: {data_key}\n\n"
165
+ f"Download: {download_url}\n"
166
+ f"Open in editor: {editor_url}\n\n"
167
+ f"Tip: call redownload_map(data_key='{data_key}', ...) to get this map "
168
+ f"in a different color theme or format (svg/png) without regenerating."
169
+ ),
170
+ ]
171
+
172
+
173
+ def _still_in_progress_result(data_key: str) -> list:
174
+ return [(
175
+ f"Map generation is still in progress (dataKey={data_key}). This can take a few "
176
+ "minutes for busy areas. Wait about 20-30 seconds, then call "
177
+ f"check_map_status(data_key='{data_key}') to check again. "
178
+ "Do NOT call the generate_* tool again for the same request — that starts a redundant "
179
+ "duplicate job and wastes time."
180
+ )]
181
+
182
+
183
+ async def _generate_map_common(body: dict, ctx: Context | None, label: str | None = None) -> list:
184
+ """3つのgenerate_*ツール共通のenqueue→poll→download→has_link判定→結果構築フロー。
185
+ labelはダウンロードファイル名の元にのみ使う(バックエンド側もplace/markers/routeから
186
+ 同じ表示名をconfigDict.nameとして独自に導出するため、bodyには含めない)。
187
+ 常にformat="png"・デフォルトcolor_setでダウンロードする(別の見た目が欲しければ
188
+ redownload_mapで取り直す)。"""
189
+ async with httpx.AsyncClient() as client:
190
+ # 1. Enqueue
191
+ resp = await client.post(f"{BASE_URL}/request", json=body, timeout=30)
192
+ if resp.status_code != 202:
193
+ try:
194
+ detail = resp.json().get("error", resp.text)
195
+ except Exception:
196
+ detail = resp.text
197
+ raise RuntimeError(f"Request rejected ({resp.status_code}): {detail}")
198
+ data_key = resp.json()["dataKey"]
199
+
200
+ # 2. Poll, but only up to INITIAL_WAIT_SEC (安全のためMCPクライアントの典型的な
201
+ # 60秒タイムアウトより十分短くしてある)。多くの地図生成はこの範囲で終わるため、
202
+ # その場合はこの1回の呼び出しだけで完結する。間に合わなければ、ここで打ち切って
203
+ # dataKeyを返し、check_map_statusでの確認をモデルに促す(生成自体はバックエンドで
204
+ # 継続しているので、ここで諦めても失敗にはならない)。
205
+ status = await _poll_with_budget(client, data_key, INITIAL_WAIT_SEC, ctx)
206
+
207
+ if status == "failed":
208
+ raise RuntimeError(
209
+ f"Map generation failed (dataKey={data_key}). "
210
+ "Try a different location."
211
+ )
212
+ if status == "pending":
213
+ return _still_in_progress_result(data_key)
214
+
215
+ # 3. Download + linkの有無判定
216
+ image_bytes = await _download(client, data_key, "png", None)
217
+ has_link = await _has_any_link(client, data_key)
218
+
219
+ return _build_success_result(image_bytes, _make_filename(label or data_key, "png"), data_key, has_link)
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Tool: generate_map
224
+ # ---------------------------------------------------------------------------
225
+
226
+ @mcp.tool()
227
+ async def generate_map(
228
+ place: Annotated[str, Field(description="Place name to center the map on (geocoded server-side).")],
229
+ ctx: Context = None,
230
+ ) -> list:
231
+ """Generate a styled map centered on a single place.
232
+
233
+ Example: generate_map(place="Tokyo Station")
234
+ """
235
+ body: dict = {"place": place}
236
+ return await _generate_map_common(body, ctx, label=place)
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Tool: generate_markers_map
241
+ # ---------------------------------------------------------------------------
242
+
243
+ @mcp.tool()
244
+ async def generate_markers_map(
245
+ markers: Annotated[
246
+ list[Marker], Field(description="Locations to pin on the map. At least one required.")
247
+ ],
248
+ place: Annotated[
249
+ str | None,
250
+ Field(description="Optional: place to center the map on. If omitted, the center is computed automatically from the markers."),
251
+ ] = None,
252
+ ctx: Context = None,
253
+ ) -> list:
254
+ """Generate a map with multiple pinned locations.
255
+
256
+ Example: generate_markers_map(markers=[{"label": "Tokyo Tower", "link": "https://www.tokyotower.co.jp/"}, {"label": "Zojoji Temple"}])
257
+ """
258
+ if not markers:
259
+ raise ValueError("'markers' must contain at least one marker.")
260
+ label = place or "_".join(m.label for m in markers)[:40]
261
+ body: dict = {"markers": [m.model_dump(exclude_none=True) for m in markers]}
262
+ if place:
263
+ body["place"] = place
264
+ return await _generate_map_common(body, ctx, label=label)
265
+
266
+
267
+ # ---------------------------------------------------------------------------
268
+ # Tool: generate_route_map
269
+ # ---------------------------------------------------------------------------
270
+
271
+ @mcp.tool()
272
+ async def generate_route_map(
273
+ # Pythonの予約語のため実引数名は'from_'。JSON上のキー名はvalidation_aliasで'from'にする
274
+ # (Field(alias=...)だとFastMCPが関数呼び出し時もalias名でキーワード引数を組み立てて
275
+ # TypeErrorになるため、入力側だけをマッピングするvalidation_aliasを使う)。
276
+ from_: Annotated[str, Field(validation_alias="from", description="Route start. Place name to geocode.")],
277
+ to: Annotated[str, Field(description="Route end. Place name to geocode.")],
278
+ mode: Annotated[Literal["walking", "driving"], Field(description="Default 'walking'.")] = "walking",
279
+ place: Annotated[
280
+ str | None,
281
+ Field(description="Optional: place to center the map on. If omitted, the center is computed automatically from the route."),
282
+ ] = None,
283
+ ctx: Context = None,
284
+ ) -> list:
285
+ """Compute a walking/driving route between two places and generate a map with it overlaid.
286
+ Both endpoints are pinned on the map automatically — do not also call generate_markers_map for them.
287
+
288
+ Example: generate_route_map(from="Tokyo Station", to="Tokyo Tower", mode="walking")
289
+ """
290
+ # from/toはそのままバックエンドの/requestへ渡す(サーバー側がジオコード+ルート探索+
291
+ # 地図生成を1回のリクエスト内で行う。以前はここで先に/routeを呼んでルートを計算して
292
+ # いたが、それだと地図生成用の道路データ取得と合わせて同じ範囲の道路網を2回取得する
293
+ # ことになっていたため、サーバー側で1回にまとめた)。
294
+ label = place or "route"
295
+ body: dict = {"route": {"from": {"label": from_}, "to": {"label": to}, "mode": mode}}
296
+ if place:
297
+ body["place"] = place
298
+ return await _generate_map_common(body, ctx, label=label)
299
+
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # Tool: check_map_status
303
+ # ---------------------------------------------------------------------------
304
+
305
+ @mcp.tool()
306
+ async def check_map_status(
307
+ data_key: Annotated[
308
+ str,
309
+ Field(description="The dataKey returned by a generate_* call that reported it was still in progress."),
310
+ ],
311
+ ctx: Context = None,
312
+ ) -> list:
313
+ """Poll a pending generate_* job and download it once ready. Wait ~20-30s between calls.
314
+
315
+ Example: check_map_status(data_key="20260618aBcDeFgHiJ")
316
+ """
317
+ async with httpx.AsyncClient() as client:
318
+ # 連打されても機械的に間隔が空くようにする最低限のスロットル
319
+ await asyncio.sleep(CHECK_THROTTLE_SEC)
320
+ status_resp = await client.get(f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10)
321
+ status = status_resp.json().get("status")
322
+ if status == "failed":
323
+ raise RuntimeError(
324
+ f"Map generation failed (dataKey={data_key}). "
325
+ "Try a different location."
326
+ )
327
+ if status != "ready":
328
+ if ctx is not None:
329
+ await ctx.report_progress(0, 1, "Map generation still in progress...")
330
+ return _still_in_progress_result(data_key)
331
+
332
+ image_bytes = await _download(client, data_key, "png", None)
333
+ has_link = await _has_any_link(client, data_key)
334
+
335
+ return _build_success_result(image_bytes, _make_filename(data_key, "png"), data_key, has_link)
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # Tool: redownload_map
340
+ # ---------------------------------------------------------------------------
341
+
342
+ @mcp.tool()
343
+ async def redownload_map(
344
+ data_key: Annotated[str, Field(description="The dataKey returned by a previous generate_* call.")],
345
+ color_set: Annotated[
346
+ str | None,
347
+ Field(description="Color theme — see server instructions for the list. Only set when explicitly requested."),
348
+ ] = None,
349
+ format: Annotated[Literal["png", "svg"], Field(description="'png' (raster) or 'svg' (vector).")] = "png",
350
+ ) -> list:
351
+ """Re-download a prior map in a different color theme or format — instant, no regeneration.
352
+
353
+ Example: redownload_map(data_key="20260618aBcDeFgHiJ", color_set="black")
354
+ """
355
+ async with httpx.AsyncClient() as client:
356
+ image_bytes = await _download(client, data_key, format, color_set)
357
+
358
+ out_path = _make_filename(data_key, format)
359
+ out_path.write_bytes(image_bytes)
360
+
361
+ # Image(format=...)はmimeTypeを"image/{format}"にそのまま埋め込む。svgの正式なmimeTypeは
362
+ # "image/svg+xml"なので、ここだけ変換する(バックエンドへのリクエストやファイル名生成には
363
+ # 影響しない、format変数自体は"svg"のまま)。
364
+ image_format = "svg+xml" if format == "svg" else format
365
+ return [
366
+ Image(data=image_bytes, format=image_format),
367
+ f"Map saved: {out_path} (dataKey={data_key}, colorSet={color_set}, format={format})",
368
+ ]
369
+
370
+
371
+ # ---------------------------------------------------------------------------
372
+ # Orphan watchdog
373
+ # ---------------------------------------------------------------------------
374
+ #
375
+ # MCPホスト(Claude Desktop)は"uv run ... mapnetwork_mcp/server.py"でこのプロセスを起動する。
376
+ # Windows上ではuvが自身のプロセス置換(execve相当)を行えないため、"uv.exe -> python.exe"という
377
+ # 子プロセスになり、さらに観測上はその下にもう一段python.exeが生まれる(mcp SDK/anyio側の
378
+ # 挙動と見られるが詳細未特定)。標準入力のEOFで自発終了するstdio_serverのロジックは正しく
379
+ # 機能する(到達不能URLでの単体テストで確認済み)一方、実運用では拡張機能の無効化/更新/
380
+ # アンインストール時にホストが子孫プロセスツリー全体を確実にkillできず、末端のpython.exeが
381
+ # 孤児として残留し、.venv配下の実行ファイルをロックし続けてアンインストール自体が失敗する
382
+ # 事故が確認された(Windows特有: プロセスをkillしても既定では子孫まで自動的には終了しない)。
383
+ # stdinパイプのEOF検知に頼らず、起動時の親プロセス(uv.exe)の生死を直接ポーリングし、
384
+ # 親が消えていたら自分も終了することで、この孤児化を防ぐ。
385
+ _ORPHAN_CHECK_INTERVAL_SEC = 5.0
386
+
387
+
388
+ def _is_process_alive(pid: int) -> bool:
389
+ if sys.platform == "win32":
390
+ import ctypes
391
+
392
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
393
+ STILL_ACTIVE = 259
394
+ handle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
395
+ if not handle:
396
+ return False
397
+ try:
398
+ exit_code = ctypes.c_ulong()
399
+ if not ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
400
+ return False
401
+ return exit_code.value == STILL_ACTIVE
402
+ finally:
403
+ ctypes.windll.kernel32.CloseHandle(handle)
404
+ else:
405
+ try:
406
+ os.kill(pid, 0)
407
+ return True
408
+ except OSError:
409
+ return False
410
+
411
+
412
+ def _start_orphan_watchdog() -> None:
413
+ parent_pid = os.getppid()
414
+
415
+ def _watch() -> None:
416
+ while True:
417
+ time.sleep(_ORPHAN_CHECK_INTERVAL_SEC)
418
+ if not _is_process_alive(parent_pid):
419
+ os._exit(1)
420
+
421
+ threading.Thread(target=_watch, daemon=True, name="orphan-watchdog").start()
422
+
423
+
424
+ def main() -> None:
425
+ _start_orphan_watchdog()
426
+ mcp.run()
427
+
428
+
429
+ if __name__ == "__main__":
430
+ main()
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mapnetwork-mcp"
3
- version = "3.0.0"
3
+ version = "5.0.0"
4
4
  description = "MCP server — generate styled map images via mapnetwork.app"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -0,0 +1,106 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "MapNetwork MCP - 入力JSON仕様",
4
+ "description": "mapnetwork_mcp/server.py で定義されている5つのMCPツールの入力パラメータ仕様。各属性の型・デフォルト値・設定可能値(enum)・制約を示す。",
5
+ "definitions": {
6
+ "Marker": {
7
+ "type": "object",
8
+ "description": "generate_markers_mapが使う、地図上にピン留めする地点。labelは必須、linkは任意で公式サイトURLを付けられる(バックエンド側がPlaces APIで自動補完する場合も多い)。link無しのマーカーが混在してもよい(むしろ通常はこちら)。以前はgenerate_hyperlink_mapという別ツールが同じMarker型を使い、markers全体のうち少なくとも1件がlinkを持つことを追加要求していたが、Places APIによるlink自動補完でgenerate_markers_mapとの差が実質無くなったため廃止された",
9
+ "properties": {
10
+ "label": { "type": "string", "description": "地名(ジオコーディング・表示用)" },
11
+ "link": { "type": ["string", "null"], "default": null, "description": "その地点の公式サイトURL(既知の場合のみ設定)" }
12
+ },
13
+ "required": ["label"]
14
+ },
15
+ "ColorSet": {
16
+ "type": "string",
17
+ "description": "カラーテーマ",
18
+ "enum": ["white", "darkBlue", "darkGreen", "popArt", "lightBlue", "lightGreen", "beige", "magenta", "gray", "black", "brawn"],
19
+ "default": "white"
20
+ },
21
+ "Format": {
22
+ "type": "string",
23
+ "enum": ["png", "svg"],
24
+ "default": "png"
25
+ }
26
+ },
27
+ "tools": {
28
+ "generate_map": {
29
+ "description": "単一の地名を中心にしたスタイル付き地図画像を生成し、Downloadsフォルダに保存する。地図サイズ・取得レイヤーは座標から自動決定される。常にデフォルトのカラーテーマ・PNG形式でダウンロードする(別の見た目が欲しければredownload_mapで取り直す)",
30
+ "type": "object",
31
+ "properties": {
32
+ "place": { "type": "string", "description": "地図の中心とする地名(サーバー側でジオコーディング)", "required": true }
33
+ },
34
+ "required": ["place"],
35
+ "constraints": ["configDict.nameにはサーバー側がplaceの値をそのまま設定する(このツールにname引数はない)"],
36
+ "example": { "place": "Tokyo Station" }
37
+ },
38
+ "generate_markers_map": {
39
+ "description": "複数の地点をピン留めした地図画像を生成する。各地点は任意でlinkを持てる(一部/全部/どれもlinkを持たなくてもよい)。常にデフォルトのカラーテーマ・PNG形式でダウンロードする",
40
+ "type": "object",
41
+ "properties": {
42
+ "markers": {
43
+ "type": "array",
44
+ "description": "地図上にピン留めする地点リスト(1件以上必須)。linkは任意",
45
+ "items": { "$ref": "#/definitions/Marker" },
46
+ "minItems": 1
47
+ },
48
+ "place": { "type": ["string", "null"], "default": null, "description": "地図の中心とする地名。未指定ならmarkersの座標群から自動計算される" }
49
+ },
50
+ "required": ["markers"],
51
+ "constraints": [
52
+ "markersは1件以上必須(link有無は問わない。1件もlinkを持たないのが通常のケース)",
53
+ "markersのいずれかがlink(明示指定またはバックエンド側のPlaces API自動補完)を持つ場合、成功レスポンスの'Open in editor'リンクに&lock=trueが付き、閲覧専用モードでそのmarkerがクリック可能になる(判定はどのツールを呼んだかではなく実データによる)",
54
+ "configDict.nameにはサーバー側がplace(未指定ならmarkersのlabelを連結した文字列)を自動設定する"
55
+ ],
56
+ "example": { "markers": [{ "label": "Tokyo Tower", "link": "https://www.tokyotower.co.jp/" }, { "label": "Zojoji Temple" }] }
57
+ },
58
+ "generate_route_map": {
59
+ "description": "2地点間の徒歩/車ルートを計算し、それを重ねた地図画像を1回の呼び出しで生成する。ルート探索と地図生成が別ツールに分かれていた旧設計(compute_route→generate_route_mapの2段階)は、MCPホスト側にとって難易度が高すぎたため統合された。ルートの両端点は地図上に自動でピン留めされる。常にデフォルトのカラーテーマ・PNG形式でダウンロードする",
60
+ "type": "object",
61
+ "properties": {
62
+ "from": { "type": "string", "description": "ルート始点の地名(サーバー側でジオコーディング)", "required": true },
63
+ "to": { "type": "string", "description": "ルート終点の地名(サーバー側でジオコーディング)", "required": true },
64
+ "mode": {
65
+ "allOf": [{ "type": "string", "enum": ["walking", "driving"] }],
66
+ "default": "walking",
67
+ "description": "移動手段"
68
+ },
69
+ "place": { "type": ["string", "null"], "default": null, "description": "地図の中心とする地名。未指定ならルートの座標群から自動計算される" }
70
+ },
71
+ "required": ["from", "to"],
72
+ "constraints": [
73
+ "from/toは地名の文字列のみ。座標を自分で計算・推測して渡してはならない(サーバー側でジオコーディング・ルート探索の両方を行う)",
74
+ "ルートの両端点は自動でピン留めされるため、別途generate_markers_mapを呼ぶ必要はない",
75
+ "ルート探索はバックエンドのワーカー内(地図生成と同じジョブ)で、地図生成用に取得した道路データをそのまま再利用して行われる(別エンドポイントでの事前ルート探索は廃止済み、道路データの二重取得を避けるため)。そのため「ルートが見つからない」等の失敗は、呼び出し時点では分からず、地図生成ジョブ自体の失敗(dataKeyのstatusがfailed)として遅れて判明する",
76
+ "configDict.nameにはサーバー側がplace(未指定なら'route'固定文字列)を自動設定する"
77
+ ],
78
+ "example": { "from": "Tokyo Station", "to": "Tokyo Tower", "mode": "walking" }
79
+ },
80
+ "check_map_status": {
81
+ "description": "generate_*ツールが未完了(pending)を返した場合のジョブをポーリングし、完了していればデフォルトのカラーテーマ・PNG形式でダウンロードする",
82
+ "type": "object",
83
+ "properties": {
84
+ "data_key": { "type": "string", "description": "generate_*ツールが返したdataKey", "required": true }
85
+ },
86
+ "required": ["data_key"],
87
+ "example": { "data_key": "20260618aBcDeFgHiJ" }
88
+ },
89
+ "redownload_map": {
90
+ "description": "生成済みの地図を、再生成せずに別のカラーテーマ/形式で再ダウンロードする",
91
+ "type": "object",
92
+ "properties": {
93
+ "data_key": { "type": "string", "description": "以前のgenerate_*ツール呼び出しが返したdataKey", "required": true },
94
+ "color_set": {
95
+ "oneOf": [{ "$ref": "#/definitions/ColorSet" }, { "type": "null" }],
96
+ "default": null,
97
+ "description": "ユーザーが明示的に要求した場合のみ設定"
98
+ },
99
+ "format": { "allOf": [{ "$ref": "#/definitions/Format" }], "description": "'png'(ラスター)または'svg'(ベクター)" }
100
+ },
101
+ "required": ["data_key"],
102
+ "constraints": ["canvas_width/canvas_heightは廃止済み"],
103
+ "example": { "data_key": "20260618aBcDeFgHiJ", "color_set": "black" }
104
+ }
105
+ }
106
+ }