arcgispro-mcp 0.1.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,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: arcgispro-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for operating the local ArcGIS Pro: layers, symbology, spatial analysis
5
+ Author: arcgispro-mcp
6
+ License: MIT
7
+ Keywords: arcgis,arcgis-pro,gis,arcpy,mcp,model-context-protocol
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: GIS
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: mcp>=2.0
18
+ Requires-Dist: pywinauto>=0.6.9
19
+ Requires-Dist: pywin32>=306
20
+
21
+ # arcgispro-mcp
22
+
23
+ MCP server for operating the local **ArcGIS Pro** from natural language:
24
+ add layers, restyle symbols, adjust transparency, run buffer and mask analysis.
25
+
26
+ Works while the ArcGIS Pro project is already open — changes show up in the map right away.
27
+
28
+ ## Requirements
29
+
30
+ - Windows (ArcGIS Pro is Windows-only)
31
+ - ArcGIS Pro installed locally
32
+ - Python 3.9+
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ python -m pip install arcgispro-mcp
38
+ ```
39
+
40
+ ## Run
41
+
42
+ The server speaks MCP over stdio:
43
+
44
+ ```bash
45
+ python -m arcgispro_mcp
46
+ ```
47
+
48
+ MCP client config:
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "arcgispro-mcp": {
54
+ "type": "stdio",
55
+ "command": "python",
56
+ "args": ["-m", "arcgispro_mcp"],
57
+ "timeout": 60000
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ ## Tools
64
+
65
+ | Tool | Purpose |
66
+ |---|---|
67
+ | `doctor` | Check arcpy version, license, Spatial Analyst, current channel |
68
+ | `start_bridge` / `bridge_status` | Start / query the in-Pro bridge |
69
+ | `apply_changes` | Flush changes to the Pro window |
70
+ | `list_layers` | List layers with visibility and transparency |
71
+ | `add_layer` / `remove_layer` | Add or remove map layers |
72
+ | `set_symbology` | Single symbol / unique values / graduated colors / raster stretch |
73
+ | `buffer_analysis` | Buffer features |
74
+ | `extract_by_mask` | Clip raster by mask |
75
+ | `project_new` / `project_open` | Create or open a project file |
76
+ | `read_table` | Read attribute table with optional where clause |
77
+ | `select_and_save` | Select by attributes and save as new data |
78
+
79
+ ## How it works
80
+
81
+ Two channels are chosen automatically:
82
+
83
+ 1. **Bridge** — when a project is open in ArcGIS Pro, commands are executed inside the
84
+ Pro process, so edits land in the live project and appear immediately.
85
+ 2. **File** — otherwise a subprocess of ArcGIS Pro's own `arcgispro-py3` operates on the
86
+ `.aprx` on disk.
87
+
88
+ The bridge can be started programmatically (`start_bridge`); it types the bootstrap script
89
+ into Pro's Python window via UI Automation, so the user never has to paste anything.
90
+
91
+ ## Note on refresh
92
+
93
+ ArcGIS Pro only repaints its symbol renderer when a Python script finishes. Mutating tools
94
+ therefore finish by ending the bridge session, letting Pro repaint, then restarting the bridge.
95
+ That round trip takes roughly 7–10 seconds and is done automatically.
@@ -0,0 +1,75 @@
1
+ # arcgispro-mcp
2
+
3
+ MCP server for operating the local **ArcGIS Pro** from natural language:
4
+ add layers, restyle symbols, adjust transparency, run buffer and mask analysis.
5
+
6
+ Works while the ArcGIS Pro project is already open — changes show up in the map right away.
7
+
8
+ ## Requirements
9
+
10
+ - Windows (ArcGIS Pro is Windows-only)
11
+ - ArcGIS Pro installed locally
12
+ - Python 3.9+
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ python -m pip install arcgispro-mcp
18
+ ```
19
+
20
+ ## Run
21
+
22
+ The server speaks MCP over stdio:
23
+
24
+ ```bash
25
+ python -m arcgispro_mcp
26
+ ```
27
+
28
+ MCP client config:
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "arcgispro-mcp": {
34
+ "type": "stdio",
35
+ "command": "python",
36
+ "args": ["-m", "arcgispro_mcp"],
37
+ "timeout": 60000
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ ## Tools
44
+
45
+ | Tool | Purpose |
46
+ |---|---|
47
+ | `doctor` | Check arcpy version, license, Spatial Analyst, current channel |
48
+ | `start_bridge` / `bridge_status` | Start / query the in-Pro bridge |
49
+ | `apply_changes` | Flush changes to the Pro window |
50
+ | `list_layers` | List layers with visibility and transparency |
51
+ | `add_layer` / `remove_layer` | Add or remove map layers |
52
+ | `set_symbology` | Single symbol / unique values / graduated colors / raster stretch |
53
+ | `buffer_analysis` | Buffer features |
54
+ | `extract_by_mask` | Clip raster by mask |
55
+ | `project_new` / `project_open` | Create or open a project file |
56
+ | `read_table` | Read attribute table with optional where clause |
57
+ | `select_and_save` | Select by attributes and save as new data |
58
+
59
+ ## How it works
60
+
61
+ Two channels are chosen automatically:
62
+
63
+ 1. **Bridge** — when a project is open in ArcGIS Pro, commands are executed inside the
64
+ Pro process, so edits land in the live project and appear immediately.
65
+ 2. **File** — otherwise a subprocess of ArcGIS Pro's own `arcgispro-py3` operates on the
66
+ `.aprx` on disk.
67
+
68
+ The bridge can be started programmatically (`start_bridge`); it types the bootstrap script
69
+ into Pro's Python window via UI Automation, so the user never has to paste anything.
70
+
71
+ ## Note on refresh
72
+
73
+ ArcGIS Pro only repaints its symbol renderer when a Python script finishes. Mutating tools
74
+ therefore finish by ending the bridge session, letting Pro repaint, then restarting the bridge.
75
+ That round trip takes roughly 7–10 seconds and is done automatically.
@@ -0,0 +1,6 @@
1
+ """arcgispro-mcp: 用 MCP 协议操作本机 ArcGIS Pro。
2
+
3
+ 与 CLI 版(arcgispro-cli)同源不同壳: 核心逻辑一致, 只是把能力暴露成 MCP 工具,
4
+ 供 WorkBuddy 等客户端直接调用, 用户不用记命令行。
5
+ """
6
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,231 @@
1
+ """与 ArcGIS Pro 进程内的桥接服务通信。
2
+
3
+ 桥接本身跑在 Pro 的 Python 窗口里(pro_bridge.py), 监听 127.0.0.1:5789。
4
+ 本模块负责:
5
+ - 通过 socket 把指令送给桥接, 拿回结果(短连接, 一次一开一关)
6
+ - 会话结束后自动重启桥接(通过 UIA 往 Pro 的 Python 输入行粘贴命令)
7
+
8
+ 关键事实(实测得出, 别轻易改):
9
+ * Pro 的渲染只在 Python 脚本结束时刷新, 所以每次改动都要 "停 -> 画 -> 启"。
10
+ * Pro Python 窗口的输入行在 UIA 里的标识是 auto_id="repl", 位于窗口最底部;
11
+ auto_id="CommandTranscriptControl" 是输出区, 往那里粘贴不会有任何效果。
12
+ * 该自绘控件不接受 type_keys("{ENTER}"), 会被当成普通字符打出乱码,
13
+ 必须用 keybd_event 发 VK_RETURN。
14
+ """
15
+ import json
16
+ import os
17
+ import socket
18
+ import time
19
+
20
+ HOST = "127.0.0.1"
21
+ PORT = int(os.environ.get("ARCGIS_PRO_BRIDGE_PORT", "5789"))
22
+ # 桥接脚本随包安装, 默认用包内副本
23
+ BRIDGE_SCRIPT = os.environ.get(
24
+ "ARCGIS_PRO_BRIDGE_SCRIPT",
25
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "pro_bridge.py"))
26
+
27
+
28
+ # ---------------- socket ----------------
29
+
30
+ def alive(timeout=0.5):
31
+ try:
32
+ s = socket.create_connection((HOST, PORT), timeout=timeout)
33
+ s.close()
34
+ return True
35
+ except OSError:
36
+ return False
37
+
38
+
39
+ def call(op, args=None, timeout=120):
40
+ """调用桥接; 连不上抛 BridgeNotRunning。"""
41
+ try:
42
+ s = socket.create_connection((HOST, PORT), timeout=1.5)
43
+ except OSError:
44
+ raise BridgeNotRunning(
45
+ "桥接服务未运行。请先运行 `arcgispro-cli bridge start` 启动它"
46
+ "(需要 ArcGIS Pro 已打开工程)。")
47
+ try:
48
+ s.settimeout(timeout)
49
+ payload = json.dumps({"op": op, "args": args or {}}, ensure_ascii=False) + "\n"
50
+ s.sendall(payload.encode("utf-8"))
51
+ buf = b""
52
+ while b"\n" not in buf:
53
+ chunk = s.recv(65536)
54
+ if not chunk:
55
+ break
56
+ buf += chunk
57
+ if not buf:
58
+ raise BridgeNotRunning("桥接连接被关闭, 可能 Pro 里的脚本已退出")
59
+ resp = json.loads(buf.split(b"\n")[0].decode("utf-8", "replace"))
60
+ if not resp.get("ok"):
61
+ raise BridgeError(resp.get("error", "桥接执行失败"))
62
+ return resp.get("data")
63
+ finally:
64
+ try:
65
+ s.close()
66
+ except Exception:
67
+ pass
68
+
69
+
70
+ class BridgeNotRunning(RuntimeError):
71
+ pass
72
+
73
+
74
+ class BridgeError(RuntimeError):
75
+ pass
76
+
77
+
78
+ def stop():
79
+ """结束桥接会话 —— 这是让改动在 Pro 里上屏的唯一开关。"""
80
+ if not alive():
81
+ return {"stopped": False, "note": "桥接未运行"}
82
+ try:
83
+ s = socket.create_connection((HOST, PORT), timeout=2)
84
+ except OSError as e:
85
+ return {"stopped": False, "note": f"连接失败: {e}"}
86
+ try:
87
+ s.sendall(b'{"op":"stop","args":{}}\n')
88
+ buf = s.recv(65536)
89
+ ok = bool(buf) and json.loads(buf.split(b"\n")[0].decode("utf-8", "replace")).get("ok")
90
+ except Exception as e:
91
+ return {"stopped": False, "note": f"停止失败: {type(e).__name__}: {e}"}
92
+ finally:
93
+ try:
94
+ s.close()
95
+ except Exception:
96
+ pass
97
+ return {"stopped": ok}
98
+
99
+
100
+ # ---------------- 自动启动(UIA) ----------------
101
+
102
+ def _bridge_cmd():
103
+ if not BRIDGE_SCRIPT or not os.path.isfile(BRIDGE_SCRIPT):
104
+ raise BridgeError(
105
+ "找不到桥接脚本 pro_bridge.py。可设置环境变量 "
106
+ "ARCGIS_PRO_BRIDGE_SCRIPT 指向它。")
107
+ return 'exec(open(r"%s", encoding="utf-8").read())' % BRIDGE_SCRIPT
108
+
109
+
110
+ def _find_python_window():
111
+ """遍历可见顶层窗口, 找带有 repl 输入行的 Pro 窗口。"""
112
+ try:
113
+ import win32gui
114
+ from pywinauto import Application
115
+ except ImportError as e:
116
+ raise BridgeError(
117
+ "自动启动需要 pywinauto 与 pywin32, 当前环境缺少: %s。"
118
+ "可执行 python -m pip install pywinauto pywin32 后重试。" % e)
119
+
120
+ hwnds = []
121
+
122
+ def _cb(h, _):
123
+ try:
124
+ if win32gui.IsWindowVisible(h) and win32gui.GetWindowText(h):
125
+ hwnds.append(h)
126
+ except Exception:
127
+ pass
128
+
129
+ win32gui.EnumWindows(_cb, None)
130
+ for h in hwnds:
131
+ try:
132
+ app = Application(backend="uia").connect(handle=h)
133
+ w = app.window(handle=h)
134
+ repl = w.child_window(auto_id="repl", control_type="Document")
135
+ if repl.exists(timeout=0.2):
136
+ return w, repl
137
+ except Exception:
138
+ continue
139
+ return None
140
+
141
+
142
+ def autostart(wait_seconds=30):
143
+ """在 Pro 的 Python 窗口里自动启动桥接(等价于人手动粘贴命令)。"""
144
+ if alive():
145
+ return {"started": False, "note": "桥接已在运行", "elapsed": 0.0}
146
+
147
+ t0 = time.time()
148
+ cmd = _bridge_cmd()
149
+ found = _find_python_window()
150
+ if not found:
151
+ return {"started": False, "elapsed": round(time.time() - t0, 1),
152
+ "note": ("找不到 ArcGIS Pro 的 Python 窗口。请确认: "
153
+ "1) Pro 已启动并打开了工程; "
154
+ "2) Python 窗口已显示(分析 → Python 窗口)。")}
155
+ win, repl = found
156
+
157
+ old_clip = ""
158
+ try:
159
+ import win32clipboard
160
+ win32clipboard.OpenClipboard()
161
+ if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_UNICODETEXT):
162
+ old_clip = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
163
+ win32clipboard.EmptyClipboard()
164
+ win32clipboard.SetClipboardText(cmd, win32clipboard.CF_UNICODETEXT)
165
+ win32clipboard.CloseClipboard()
166
+ except Exception as e:
167
+ return {"started": False, "elapsed": round(time.time() - t0, 1),
168
+ "note": f"写入剪贴板失败: {type(e).__name__}: {e}"}
169
+
170
+ try:
171
+ repl.set_focus()
172
+ time.sleep(0.5)
173
+ # 清掉输入行可能残留的半截命令
174
+ try:
175
+ repl.type_keys("^a")
176
+ time.sleep(0.15)
177
+ repl.type_keys("{DELETE}")
178
+ time.sleep(0.15)
179
+ except Exception:
180
+ pass
181
+ repl.type_keys("^v")
182
+ time.sleep(1.0)
183
+ # 校验粘贴结果: 曾出现过输入行残留旧命令、结果执行了错路径的情况。
184
+ # 读不到文本时不阻断流程(某些版本 window_text 返回空), 只做尽力校验。
185
+ try:
186
+ txt = repl.window_text() or ""
187
+ if txt and "pro_bridge" not in txt:
188
+ repl.type_keys("^a")
189
+ time.sleep(0.15)
190
+ repl.type_keys("{DELETE}")
191
+ time.sleep(0.15)
192
+ repl.type_keys("^v")
193
+ time.sleep(1.0)
194
+ except Exception:
195
+ pass
196
+ import win32api
197
+ import win32con
198
+ win32api.keybd_event(win32con.VK_RETURN, 0, 0, 0)
199
+ time.sleep(0.1)
200
+ win32api.keybd_event(win32con.VK_RETURN, 0, win32con.KEYEVENTF_KEYUP, 0)
201
+ except Exception as e:
202
+ return {"started": False, "elapsed": round(time.time() - t0, 1),
203
+ "note": f"向 Python 窗口输入失败: {type(e).__name__}: {e}"}
204
+ finally:
205
+ try:
206
+ import win32clipboard
207
+ if old_clip:
208
+ win32clipboard.OpenClipboard()
209
+ win32clipboard.EmptyClipboard()
210
+ win32clipboard.SetClipboardText(old_clip, win32clipboard.CF_UNICODETEXT)
211
+ win32clipboard.CloseClipboard()
212
+ except Exception:
213
+ pass
214
+
215
+ deadline = t0 + wait_seconds
216
+ while time.time() < deadline:
217
+ time.sleep(1.0)
218
+ if alive():
219
+ return {"started": True, "elapsed": round(time.time() - t0, 1),
220
+ "note": "桥接已启动"}
221
+ return {"started": False, "elapsed": round(time.time() - t0, 1),
222
+ "note": f"等待 {wait_seconds}s 仍未就绪, 请检查 Pro 的 Python 窗口是否报错"}
223
+
224
+
225
+ def apply(wait=1.5, restart=True):
226
+ """让改动上屏: 停会话 -> 等 Pro 重绘 -> 重启桥接。"""
227
+ r = stop()
228
+ if r.get("stopped") and restart:
229
+ time.sleep(wait)
230
+ r["restart"] = autostart()
231
+ return r
@@ -0,0 +1,69 @@
1
+ """定位 ArcGIS Pro 自带的 arcgispro-py3 解释器。
2
+
3
+ 探测顺序:
4
+ 1. ARCPY_MCP_PYTHON 环境变量(直接指到 python.exe)
5
+ 2. 已知常规安装路径(C 盘及当前工作区所在盘)
6
+ 3. 注册表(HKLM/SOFTWARE/ESRI/ArcGISPro)
7
+ 结果缓存在本文件同目录 .pro_env_cache.json, 删除即重探。
8
+ """
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+ CACHE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".pro_env_cache.json")
14
+ REG_KEY = "SOFTWARE\\ESRI\\ArcGISPro"
15
+
16
+
17
+ def _candidates():
18
+ env = os.environ.get("ARCPY_MCP_PYTHON")
19
+ if env:
20
+ yield env
21
+ # 常规安装路径
22
+ for drive in ("C:", "D:", "E:", "F:", "G:"):
23
+ yield os.path.join(drive, os.sep, "Program Files", "ArcGIS", "Pro",
24
+ "bin", "Python", "envs", "arcgispro-py3", "python.exe")
25
+ # 注册表
26
+ try:
27
+ import winreg
28
+ for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
29
+ try:
30
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, REG_KEY, 0, view) as k:
31
+ installdir, _ = winreg.QueryValueEx(k, "InstallDir")
32
+ yield os.path.join(installdir, "bin", "Python", "envs",
33
+ "arcgispro-py3", "python.exe")
34
+ except OSError:
35
+ continue
36
+ except ImportError:
37
+ pass
38
+
39
+
40
+ def _verify(path):
41
+ if not (path and os.path.isfile(path)):
42
+ return None
43
+ return path
44
+
45
+
46
+ def locate(refresh=False):
47
+ """返回 arcgispro-py3 python.exe 完整路径, 找不到返回 None。"""
48
+ if not refresh and os.path.isfile(CACHE):
49
+ try:
50
+ cached = json.load(open(CACHE, encoding="utf-8"))
51
+ if cached.get("python") and os.path.isfile(cached["python"]):
52
+ return cached["python"]
53
+ except Exception:
54
+ pass
55
+ for cand in _candidates():
56
+ hit = _verify(cand)
57
+ if hit:
58
+ json.dump({"python": hit}, open(CACHE, "w", encoding="utf-8"))
59
+ return hit
60
+ return None
61
+
62
+
63
+ if __name__ == "__main__":
64
+ py = locate(refresh="--refresh" in sys.argv)
65
+ if py:
66
+ print(py)
67
+ else:
68
+ print("NOT_FOUND")
69
+ sys.exit(1)