mapnetwork-mcp 2.0.0__tar.gz → 4.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.
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/PKG-INFO +1 -1
- mapnetwork_mcp-4.0.0/SECURITY.md +22 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/manifest.json +16 -4
- mapnetwork_mcp-4.0.0/mapnetwork_mcp/server.py +470 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/pyproject.toml +1 -1
- mapnetwork_mcp-4.0.0/spec/input_schema.json +126 -0
- mapnetwork_mcp-4.0.0/spec/output_schema.json +236 -0
- mapnetwork_mcp-4.0.0/uv.lock +819 -0
- mapnetwork_mcp-2.0.0/mapnetwork_mcp/server.py +0 -446
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/.github/workflows/workflow.yml +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/.gitignore +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/.mcpbignore +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/LICENSE +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/README.md +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/RELEASING.md +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-black.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-darkGreen.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-grey.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-lightGreen.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-popArt.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.0.0}/images/Kanazawa21Museum-white.png +0 -0
- {mapnetwork_mcp-2.0.0 → mapnetwork_mcp-4.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
|
+
Version: 4.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
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Supported Versions
|
|
4
|
+
|
|
5
|
+
Only the latest major version receives security fixes.
|
|
6
|
+
|
|
7
|
+
| Version | Supported |
|
|
8
|
+
| ------- | ------------------ |
|
|
9
|
+
| 2.x | :white_check_mark: |
|
|
10
|
+
| < 2.0 | :x: |
|
|
11
|
+
|
|
12
|
+
## Reporting a Vulnerability
|
|
13
|
+
|
|
14
|
+
Please report security vulnerabilities privately through
|
|
15
|
+
[GitHub Private Vulnerability Reporting](https://github.com/toruproject/mapnetwork-mcp/security/advisories/new).
|
|
16
|
+
This opens a private advisory visible only to the maintainer and you, so the
|
|
17
|
+
issue is not disclosed publicly before a fix is available.
|
|
18
|
+
|
|
19
|
+
Do not report security vulnerabilities through public GitHub issues.
|
|
20
|
+
|
|
21
|
+
We aim to respond as quickly as possible on a best-effort basis; we do not
|
|
22
|
+
currently commit to a fixed response-time SLA.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"manifest_version": "0.4",
|
|
3
3
|
"name": "mapnetwork-mcp",
|
|
4
4
|
"display_name": "MapNetwork",
|
|
5
|
-
"version": "
|
|
5
|
+
"version": "4.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,23 @@
|
|
|
25
25
|
"tools": [
|
|
26
26
|
{
|
|
27
27
|
"name": "generate_map",
|
|
28
|
-
"description": "Generate a styled map image
|
|
28
|
+
"description": "Generate a styled map image centered on a single place and save it to Downloads"
|
|
29
29
|
},
|
|
30
30
|
{
|
|
31
|
-
"name": "
|
|
32
|
-
"description": "
|
|
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": "generate_hyperlink_map",
|
|
40
|
+
"description": "Generate a map with pinned locations that are clickable links to their official websites"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"name": "check_map_status",
|
|
44
|
+
"description": "Poll a pending map generation job and download it once ready"
|
|
33
45
|
},
|
|
34
46
|
{
|
|
35
47
|
"name": "redownload_map",
|
|
@@ -0,0 +1,470 @@
|
|
|
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/generate_hyperlink_map共通。labelは必須、linkは任意で公式サイトURLを
|
|
37
|
+
付けられる。generate_markers_mapはlink無しのマーカーが混在してもよく(むしろ通常はこちら)、
|
|
38
|
+
generate_hyperlink_mapは少なくとも1つのマーカーが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`. Use this whenever the user "
|
|
57
|
+
"asks to show multiple places on a single map.\n"
|
|
58
|
+
"- **Walking/driving route**: `generate_route_map(from=..., to=..., mode=...)` — computes a "
|
|
59
|
+
"route between two places and draws it on the map, with both endpoints pinned automatically. "
|
|
60
|
+
"`mode` is 'walking' (default) or 'driving'.\n"
|
|
61
|
+
"- **Hyperlink map**: `generate_hyperlink_map(markers=[{\"label\": ..., \"link\": ...}, ...])` "
|
|
62
|
+
"— like generate_markers_map, but produces a map where markers are clickable links to their "
|
|
63
|
+
"official websites. Set `link` on any marker whose official website you already know (e.g. "
|
|
64
|
+
"from search results or prior knowledge); at least one marker must have `link` set, or the "
|
|
65
|
+
"call errors. Use this whenever the user wants a map they (or someone else) can click "
|
|
66
|
+
"through to visit the pinned places' websites.\n"
|
|
67
|
+
"- Every generate_* call produces a PNG at default size and theme — see 'Important: "
|
|
68
|
+
"re-download without regenerating' below to view it differently.\n\n"
|
|
69
|
+
"## If generation is still in progress\n"
|
|
70
|
+
"For busy areas, any generate_* tool may return before the map is ready, with a `dataKey` "
|
|
71
|
+
"and a message asking you to check back. In that case, wait about 20-30 seconds and "
|
|
72
|
+
"call `check_map_status(data_key=...)` — do not call the generate_* tool again for the same "
|
|
73
|
+
"request, that only starts a redundant duplicate job. Repeat `check_map_status` "
|
|
74
|
+
"(with the same wait between calls) until it returns the image.\n\n"
|
|
75
|
+
"## Important: re-download without regenerating\n"
|
|
76
|
+
"After generating a map, the tool returns a `dataKey`. "
|
|
77
|
+
"You can call `redownload_map` with that `dataKey` to get the same map in a different "
|
|
78
|
+
"color theme or format (png/svg) — **no regeneration needed**. "
|
|
79
|
+
"Use this when the user asks to change only the appearance after already generating the map. "
|
|
80
|
+
"MapNetwork supports 11 color themes (white, darkBlue, darkGreen, popArt, lightBlue, "
|
|
81
|
+
"lightGreen, beige, magenta, gray, black, brawn).\n\n"
|
|
82
|
+
"## Sharing the generated map\n"
|
|
83
|
+
"Every successful result includes a Download link, plus either a 'Hyperlink Map' link "
|
|
84
|
+
"(read-only, linked markers clickable) or an 'Open in editor' link. "
|
|
85
|
+
"Mention whichever one you receive.\n\n"
|
|
86
|
+
"## Parameter discipline\n"
|
|
87
|
+
"- **place/label**: `place`, a marker's `label`, and route's `from`/`to` must each be a "
|
|
88
|
+
"place name specific enough for the server to geocode it to a single, unambiguous "
|
|
89
|
+
"location (e.g. a full venue or station name, not a vague or generic term like "
|
|
90
|
+
"\"the station\" or \"a nearby cafe\")."
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# Helpers
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
def _make_filename(label: str, format: str) -> Path:
|
|
99
|
+
slug = re.sub(r"_+", "_", re.sub(r"[^\w-鿿]", "_", label)).strip("_")[:40]
|
|
100
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
101
|
+
out_dir = Path.home() / "Downloads"
|
|
102
|
+
out_dir.mkdir(exist_ok=True)
|
|
103
|
+
return out_dir / f"map_{slug}_{timestamp}.{format}"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def _download(client: httpx.AsyncClient, data_key: str, format: str,
|
|
107
|
+
color_set: str | None) -> bytes:
|
|
108
|
+
params: dict = {"dataKey": data_key, "format": format}
|
|
109
|
+
if color_set is not None:
|
|
110
|
+
params["colorSet"] = color_set
|
|
111
|
+
resp = await client.get(f"{BASE_URL}/download", params=params, timeout=60)
|
|
112
|
+
if resp.status_code != 200:
|
|
113
|
+
raise RuntimeError(f"Download failed ({resp.status_code}): {resp.text}")
|
|
114
|
+
return resp.content
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def _has_any_link(client: httpx.AsyncClient, data_key: str) -> bool:
|
|
118
|
+
"""dataKeyの生成結果(placeDict)にlinkを持つエントリが1つでもあるか判定する。
|
|
119
|
+
Web UIの共有リンク機能が使うAPIを流用する(MCP生成データも同じSTORE_DIR配下に
|
|
120
|
+
保存されるため、dataKeyを指定すればWeb UI側からも同じデータが取得できる)。
|
|
121
|
+
どのツールを呼んだかではなく、実際に生成されたデータで判定する。"""
|
|
122
|
+
try:
|
|
123
|
+
resp = await client.get(f"{BASE_URL}/api/upd/download", params={"dataKey": data_key}, timeout=10)
|
|
124
|
+
if resp.status_code != 200:
|
|
125
|
+
return False
|
|
126
|
+
place_dict = resp.json().get("placeDict", {})
|
|
127
|
+
return any(isinstance(p, dict) and p.get("link") for p in place_dict.values())
|
|
128
|
+
except Exception:
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
async def _poll_with_budget(
|
|
133
|
+
client: httpx.AsyncClient, data_key: str, budget_sec: float, ctx: Context | None,
|
|
134
|
+
) -> str:
|
|
135
|
+
"""dataKeyの状態をPOLL_INTERVAL_SEC間隔でbudget_sec以内までポーリングする。
|
|
136
|
+
"ready"/"failed"になればその時点で返す。budget_sec内に決着しなければ"pending"を
|
|
137
|
+
返す(例外は投げない、呼び出し側で分岐する)。"""
|
|
138
|
+
if ctx is not None:
|
|
139
|
+
await ctx.report_progress(0, budget_sec, "Map generation queued...")
|
|
140
|
+
elapsed = 0.0
|
|
141
|
+
while elapsed < budget_sec:
|
|
142
|
+
await asyncio.sleep(POLL_INTERVAL_SEC)
|
|
143
|
+
elapsed += POLL_INTERVAL_SEC
|
|
144
|
+
status_resp = await client.get(
|
|
145
|
+
f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10
|
|
146
|
+
)
|
|
147
|
+
status = status_resp.json().get("status")
|
|
148
|
+
if status in ("ready", "failed"):
|
|
149
|
+
return status
|
|
150
|
+
if ctx is not None:
|
|
151
|
+
await ctx.report_progress(
|
|
152
|
+
elapsed, budget_sec, f"Map generation in progress... ({elapsed:.0f}s elapsed)"
|
|
153
|
+
)
|
|
154
|
+
return "pending"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _build_success_result(image_bytes: bytes, out_path: Path, data_key: str, has_link: bool) -> list:
|
|
158
|
+
out_path.write_bytes(image_bytes)
|
|
159
|
+
# linkを持つマーカーが1つでもあれば閲覧専用(lock)リンクを、無ければ編集用リンクを返す。
|
|
160
|
+
# どのツールを呼んだかではなく実際に生成されたplaceDictの中身で判定している(_has_any_link)。
|
|
161
|
+
link_line = (
|
|
162
|
+
f"hyperlink Map: https://mapnetwork.app/generate?dataKey={data_key}&lock=true"
|
|
163
|
+
if has_link else
|
|
164
|
+
f"Open in editor: https://mapnetwork.app/generate?dataKey={data_key}"
|
|
165
|
+
)
|
|
166
|
+
return [
|
|
167
|
+
Image(data=image_bytes, format="png"),
|
|
168
|
+
(
|
|
169
|
+
f"Map saved: {out_path}\n"
|
|
170
|
+
f"dataKey: {data_key}\n\n"
|
|
171
|
+
f"{link_line}\n\n"
|
|
172
|
+
f"Tip: call redownload_map(data_key='{data_key}', ...) to get this map "
|
|
173
|
+
f"in a different color theme or format (svg/png) without regenerating."
|
|
174
|
+
),
|
|
175
|
+
]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _still_in_progress_result(data_key: str) -> list:
|
|
179
|
+
return [(
|
|
180
|
+
f"Map generation is still in progress (dataKey={data_key}). This can take a few "
|
|
181
|
+
"minutes for busy areas. Wait about 20-30 seconds, then call "
|
|
182
|
+
f"check_map_status(data_key='{data_key}') to check again. "
|
|
183
|
+
"Do NOT call the generate_* tool again for the same request — that starts a redundant "
|
|
184
|
+
"duplicate job and wastes time."
|
|
185
|
+
)]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
async def _generate_map_common(body: dict, ctx: Context | None) -> list:
|
|
189
|
+
"""4つのgenerate_*ツール共通のenqueue→poll→download→has_link判定→結果構築フロー。
|
|
190
|
+
body["name"]をファイル名の元にも使う。常にformat="png"・デフォルトcolor_setで
|
|
191
|
+
ダウンロードする(別の見た目が欲しければredownload_mapで取り直す)。"""
|
|
192
|
+
async with httpx.AsyncClient() as client:
|
|
193
|
+
# 1. Enqueue
|
|
194
|
+
resp = await client.post(f"{BASE_URL}/request", json=body, timeout=30)
|
|
195
|
+
if resp.status_code != 202:
|
|
196
|
+
try:
|
|
197
|
+
detail = resp.json().get("error", resp.text)
|
|
198
|
+
except Exception:
|
|
199
|
+
detail = resp.text
|
|
200
|
+
raise RuntimeError(f"Request rejected ({resp.status_code}): {detail}")
|
|
201
|
+
data_key = resp.json()["dataKey"]
|
|
202
|
+
|
|
203
|
+
# 2. Poll, but only up to INITIAL_WAIT_SEC (安全のためMCPクライアントの典型的な
|
|
204
|
+
# 60秒タイムアウトより十分短くしてある)。多くの地図生成はこの範囲で終わるため、
|
|
205
|
+
# その場合はこの1回の呼び出しだけで完結する。間に合わなければ、ここで打ち切って
|
|
206
|
+
# dataKeyを返し、check_map_statusでの確認をモデルに促す(生成自体はバックエンドで
|
|
207
|
+
# 継続しているので、ここで諦めても失敗にはならない)。
|
|
208
|
+
status = await _poll_with_budget(client, data_key, INITIAL_WAIT_SEC, ctx)
|
|
209
|
+
|
|
210
|
+
if status == "failed":
|
|
211
|
+
raise RuntimeError(
|
|
212
|
+
f"Map generation failed (dataKey={data_key}). "
|
|
213
|
+
"Try a different location."
|
|
214
|
+
)
|
|
215
|
+
if status == "pending":
|
|
216
|
+
return _still_in_progress_result(data_key)
|
|
217
|
+
|
|
218
|
+
# 3. Download + linkの有無判定
|
|
219
|
+
image_bytes = await _download(client, data_key, "png", None)
|
|
220
|
+
has_link = await _has_any_link(client, data_key)
|
|
221
|
+
|
|
222
|
+
label = body.get("name") or data_key
|
|
223
|
+
return _build_success_result(image_bytes, _make_filename(label, "png"), data_key, has_link)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ---------------------------------------------------------------------------
|
|
227
|
+
# Tool: generate_map
|
|
228
|
+
# ---------------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
@mcp.tool()
|
|
231
|
+
async def generate_map(
|
|
232
|
+
place: Annotated[str, Field(description="Place name to center the map on (geocoded server-side).")],
|
|
233
|
+
ctx: Context = None,
|
|
234
|
+
) -> list:
|
|
235
|
+
"""Generate a styled map centered on a single place.
|
|
236
|
+
|
|
237
|
+
Example: generate_map(place="Tokyo Station")
|
|
238
|
+
"""
|
|
239
|
+
body: dict = {"place": place, "name": place}
|
|
240
|
+
return await _generate_map_common(body, ctx)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ---------------------------------------------------------------------------
|
|
244
|
+
# Tool: generate_markers_map
|
|
245
|
+
# ---------------------------------------------------------------------------
|
|
246
|
+
|
|
247
|
+
@mcp.tool()
|
|
248
|
+
async def generate_markers_map(
|
|
249
|
+
markers: Annotated[
|
|
250
|
+
list[Marker], Field(description="Locations to pin on the map. At least one required.")
|
|
251
|
+
],
|
|
252
|
+
place: Annotated[
|
|
253
|
+
str | None,
|
|
254
|
+
Field(description="Optional: place to center the map on. If omitted, the center is computed automatically from the markers."),
|
|
255
|
+
] = None,
|
|
256
|
+
ctx: Context = None,
|
|
257
|
+
) -> list:
|
|
258
|
+
"""Generate a map with multiple pinned locations.
|
|
259
|
+
|
|
260
|
+
Example: generate_markers_map(markers=[{"label": "Tokyo Tower"}, {"label": "Zojoji Temple"}])
|
|
261
|
+
"""
|
|
262
|
+
if not markers:
|
|
263
|
+
raise ValueError("'markers' must contain at least one marker.")
|
|
264
|
+
label = place or "_".join(m.label for m in markers)[:40]
|
|
265
|
+
body: dict = {"markers": [m.model_dump(exclude_none=True) for m in markers], "name": label}
|
|
266
|
+
if place:
|
|
267
|
+
body["place"] = place
|
|
268
|
+
return await _generate_map_common(body, ctx)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# ---------------------------------------------------------------------------
|
|
272
|
+
# Tool: generate_route_map
|
|
273
|
+
# ---------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
@mcp.tool()
|
|
276
|
+
async def generate_route_map(
|
|
277
|
+
# Pythonの予約語のため実引数名は'from_'。JSON上のキー名はvalidation_aliasで'from'にする
|
|
278
|
+
# (Field(alias=...)だとFastMCPが関数呼び出し時もalias名でキーワード引数を組み立てて
|
|
279
|
+
# TypeErrorになるため、入力側だけをマッピングするvalidation_aliasを使う)。
|
|
280
|
+
from_: Annotated[str, Field(validation_alias="from", description="Route start. Place name to geocode.")],
|
|
281
|
+
to: Annotated[str, Field(description="Route end. Place name to geocode.")],
|
|
282
|
+
mode: Annotated[Literal["walking", "driving"], Field(description="Default 'walking'.")] = "walking",
|
|
283
|
+
place: Annotated[
|
|
284
|
+
str | None,
|
|
285
|
+
Field(description="Optional: place to center the map on. If omitted, the center is computed automatically from the route."),
|
|
286
|
+
] = None,
|
|
287
|
+
ctx: Context = None,
|
|
288
|
+
) -> list:
|
|
289
|
+
"""Compute a walking/driving route between two places and generate a map with it overlaid.
|
|
290
|
+
Both endpoints are pinned on the map automatically — do not also call generate_markers_map for them.
|
|
291
|
+
|
|
292
|
+
Example: generate_route_map(from="Tokyo Station", to="Tokyo Tower", mode="walking")
|
|
293
|
+
"""
|
|
294
|
+
# from/toはそのままバックエンドの/requestへ渡す(サーバー側がジオコード+ルート探索+
|
|
295
|
+
# 地図生成を1回のリクエスト内で行う。以前はここで先に/routeを呼んでルートを計算して
|
|
296
|
+
# いたが、それだと地図生成用の道路データ取得と合わせて同じ範囲の道路網を2回取得する
|
|
297
|
+
# ことになっていたため、サーバー側で1回にまとめた)。
|
|
298
|
+
label = place or "route"
|
|
299
|
+
body: dict = {"route": {"from": {"label": from_}, "to": {"label": to}, "mode": mode}, "name": label}
|
|
300
|
+
if place:
|
|
301
|
+
body["place"] = place
|
|
302
|
+
return await _generate_map_common(body, ctx)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# ---------------------------------------------------------------------------
|
|
306
|
+
# Tool: generate_hyperlink_map
|
|
307
|
+
# ---------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
@mcp.tool()
|
|
310
|
+
async def generate_hyperlink_map(
|
|
311
|
+
markers: Annotated[
|
|
312
|
+
list[Marker],
|
|
313
|
+
Field(description="Locations to pin. At least one required, and at least one marker must "
|
|
314
|
+
"have 'link' set (its official website URL) — otherwise use generate_markers_map instead."),
|
|
315
|
+
],
|
|
316
|
+
place: Annotated[
|
|
317
|
+
str | None,
|
|
318
|
+
Field(description="Optional: place to center the map on. If omitted, the center is computed automatically from the markers."),
|
|
319
|
+
] = None,
|
|
320
|
+
ctx: Context = None,
|
|
321
|
+
) -> list:
|
|
322
|
+
"""Generate a map with pinned locations whose website links are clickable in the resulting map link.
|
|
323
|
+
Requires at least one marker to have 'link' set — use generate_markers_map if none do.
|
|
324
|
+
|
|
325
|
+
Example: generate_hyperlink_map(markers=[{"label": "Tokyo Tower", "link": "https://www.tokyotower.co.jp/"}])
|
|
326
|
+
"""
|
|
327
|
+
if not markers:
|
|
328
|
+
raise ValueError("'markers' must contain at least one marker.")
|
|
329
|
+
if not any(m.link for m in markers):
|
|
330
|
+
raise ValueError(
|
|
331
|
+
"generate_hyperlink_map requires at least one marker with 'link' set. "
|
|
332
|
+
"Use generate_markers_map instead if no marker has a link."
|
|
333
|
+
)
|
|
334
|
+
label = place or "_".join(m.label for m in markers)[:40]
|
|
335
|
+
body: dict = {"markers": [m.model_dump(exclude_none=True) for m in markers], "name": label}
|
|
336
|
+
if place:
|
|
337
|
+
body["place"] = place
|
|
338
|
+
return await _generate_map_common(body, ctx)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
# ---------------------------------------------------------------------------
|
|
342
|
+
# Tool: check_map_status
|
|
343
|
+
# ---------------------------------------------------------------------------
|
|
344
|
+
|
|
345
|
+
@mcp.tool()
|
|
346
|
+
async def check_map_status(
|
|
347
|
+
data_key: Annotated[
|
|
348
|
+
str,
|
|
349
|
+
Field(description="The dataKey returned by a generate_* call that reported it was still in progress."),
|
|
350
|
+
],
|
|
351
|
+
ctx: Context = None,
|
|
352
|
+
) -> list:
|
|
353
|
+
"""Poll a pending generate_* job and download it once ready. Wait ~20-30s between calls.
|
|
354
|
+
|
|
355
|
+
Example: check_map_status(data_key="20260618aBcDeFgHiJ")
|
|
356
|
+
"""
|
|
357
|
+
async with httpx.AsyncClient() as client:
|
|
358
|
+
# 連打されても機械的に間隔が空くようにする最低限のスロットル
|
|
359
|
+
await asyncio.sleep(CHECK_THROTTLE_SEC)
|
|
360
|
+
status_resp = await client.get(f"{BASE_URL}/status", params={"dataKey": data_key}, timeout=10)
|
|
361
|
+
status = status_resp.json().get("status")
|
|
362
|
+
if status == "failed":
|
|
363
|
+
raise RuntimeError(
|
|
364
|
+
f"Map generation failed (dataKey={data_key}). "
|
|
365
|
+
"Try a different location."
|
|
366
|
+
)
|
|
367
|
+
if status != "ready":
|
|
368
|
+
if ctx is not None:
|
|
369
|
+
await ctx.report_progress(0, 1, "Map generation still in progress...")
|
|
370
|
+
return _still_in_progress_result(data_key)
|
|
371
|
+
|
|
372
|
+
image_bytes = await _download(client, data_key, "png", None)
|
|
373
|
+
has_link = await _has_any_link(client, data_key)
|
|
374
|
+
|
|
375
|
+
return _build_success_result(image_bytes, _make_filename(data_key, "png"), data_key, has_link)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# ---------------------------------------------------------------------------
|
|
379
|
+
# Tool: redownload_map
|
|
380
|
+
# ---------------------------------------------------------------------------
|
|
381
|
+
|
|
382
|
+
@mcp.tool()
|
|
383
|
+
async def redownload_map(
|
|
384
|
+
data_key: Annotated[str, Field(description="The dataKey returned by a previous generate_* call.")],
|
|
385
|
+
color_set: Annotated[
|
|
386
|
+
str | None,
|
|
387
|
+
Field(description="Color theme — see server instructions for the list. Only set when explicitly requested."),
|
|
388
|
+
] = None,
|
|
389
|
+
format: Annotated[Literal["png", "svg"], Field(description="'png' (raster) or 'svg' (vector).")] = "png",
|
|
390
|
+
) -> list:
|
|
391
|
+
"""Re-download a prior map in a different color theme or format — instant, no regeneration.
|
|
392
|
+
|
|
393
|
+
Example: redownload_map(data_key="20260618aBcDeFgHiJ", color_set="black")
|
|
394
|
+
"""
|
|
395
|
+
async with httpx.AsyncClient() as client:
|
|
396
|
+
image_bytes = await _download(client, data_key, format, color_set)
|
|
397
|
+
|
|
398
|
+
out_path = _make_filename(data_key, format)
|
|
399
|
+
out_path.write_bytes(image_bytes)
|
|
400
|
+
|
|
401
|
+
# Image(format=...)はmimeTypeを"image/{format}"にそのまま埋め込む。svgの正式なmimeTypeは
|
|
402
|
+
# "image/svg+xml"なので、ここだけ変換する(バックエンドへのリクエストやファイル名生成には
|
|
403
|
+
# 影響しない、format変数自体は"svg"のまま)。
|
|
404
|
+
image_format = "svg+xml" if format == "svg" else format
|
|
405
|
+
return [
|
|
406
|
+
Image(data=image_bytes, format=image_format),
|
|
407
|
+
f"Map saved: {out_path} (dataKey={data_key}, colorSet={color_set}, format={format})",
|
|
408
|
+
]
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
# ---------------------------------------------------------------------------
|
|
412
|
+
# Orphan watchdog
|
|
413
|
+
# ---------------------------------------------------------------------------
|
|
414
|
+
#
|
|
415
|
+
# MCPホスト(Claude Desktop)は"uv run ... mapnetwork_mcp/server.py"でこのプロセスを起動する。
|
|
416
|
+
# Windows上ではuvが自身のプロセス置換(execve相当)を行えないため、"uv.exe -> python.exe"という
|
|
417
|
+
# 子プロセスになり、さらに観測上はその下にもう一段python.exeが生まれる(mcp SDK/anyio側の
|
|
418
|
+
# 挙動と見られるが詳細未特定)。標準入力のEOFで自発終了するstdio_serverのロジックは正しく
|
|
419
|
+
# 機能する(到達不能URLでの単体テストで確認済み)一方、実運用では拡張機能の無効化/更新/
|
|
420
|
+
# アンインストール時にホストが子孫プロセスツリー全体を確実にkillできず、末端のpython.exeが
|
|
421
|
+
# 孤児として残留し、.venv配下の実行ファイルをロックし続けてアンインストール自体が失敗する
|
|
422
|
+
# 事故が確認された(Windows特有: プロセスをkillしても既定では子孫まで自動的には終了しない)。
|
|
423
|
+
# stdinパイプのEOF検知に頼らず、起動時の親プロセス(uv.exe)の生死を直接ポーリングし、
|
|
424
|
+
# 親が消えていたら自分も終了することで、この孤児化を防ぐ。
|
|
425
|
+
_ORPHAN_CHECK_INTERVAL_SEC = 5.0
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _is_process_alive(pid: int) -> bool:
|
|
429
|
+
if sys.platform == "win32":
|
|
430
|
+
import ctypes
|
|
431
|
+
|
|
432
|
+
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
433
|
+
STILL_ACTIVE = 259
|
|
434
|
+
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
435
|
+
if not handle:
|
|
436
|
+
return False
|
|
437
|
+
try:
|
|
438
|
+
exit_code = ctypes.c_ulong()
|
|
439
|
+
if not ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
|
|
440
|
+
return False
|
|
441
|
+
return exit_code.value == STILL_ACTIVE
|
|
442
|
+
finally:
|
|
443
|
+
ctypes.windll.kernel32.CloseHandle(handle)
|
|
444
|
+
else:
|
|
445
|
+
try:
|
|
446
|
+
os.kill(pid, 0)
|
|
447
|
+
return True
|
|
448
|
+
except OSError:
|
|
449
|
+
return False
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _start_orphan_watchdog() -> None:
|
|
453
|
+
parent_pid = os.getppid()
|
|
454
|
+
|
|
455
|
+
def _watch() -> None:
|
|
456
|
+
while True:
|
|
457
|
+
time.sleep(_ORPHAN_CHECK_INTERVAL_SEC)
|
|
458
|
+
if not _is_process_alive(parent_pid):
|
|
459
|
+
os._exit(1)
|
|
460
|
+
|
|
461
|
+
threading.Thread(target=_watch, daemon=True, name="orphan-watchdog").start()
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def main() -> None:
|
|
465
|
+
_start_orphan_watchdog()
|
|
466
|
+
mcp.run()
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
if __name__ == "__main__":
|
|
470
|
+
main()
|