windows-mcp 0.5.5__py3-none-any.whl → 0.5.6__py3-none-any.whl

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.
windows_mcp/__main__.py CHANGED
@@ -1,15 +1,20 @@
1
+ from windows_mcp.analytics import PostHogAnalytics, with_analytics
1
2
  from live_inspect.watch_cursor import WatchCursor
3
+ from windows_mcp.desktop.service import Desktop
2
4
  from contextlib import asynccontextmanager
3
5
  from fastmcp.utilities.types import Image
4
- from windows_mcp.desktop.service import Desktop
5
6
  from mcp.types import ToolAnnotations
7
+ from typing import Literal, Optional
6
8
  from humancursor import SystemCursor
9
+ from dotenv import load_dotenv
7
10
  from textwrap import dedent
8
11
  from fastmcp import FastMCP
9
- from typing import Literal
10
12
  import pyautogui as pg
11
13
  import asyncio
12
14
  import click
15
+ import os
16
+
17
+ load_dotenv()
13
18
 
14
19
  pg.FAILSAFE=False
15
20
  pg.PAUSE=1.0
@@ -26,6 +31,12 @@ Windows MCP server provides tools to interact directly with the {windows_version
26
31
  thus enabling to operate the desktop on the user's behalf.
27
32
  ''')
28
33
 
34
+ # Initialize analytics at module level to be used in decorators
35
+ if os.getenv("ANONYMIZED_TELEMETRY", "true").lower() == "false":
36
+ analytics = None
37
+ else:
38
+ analytics = PostHogAnalytics()
39
+
29
40
  @asynccontextmanager
30
41
  async def lifespan(app: FastMCP):
31
42
  """Runs initialization code before the server starts and cleanup code after it shuts down."""
@@ -35,6 +46,8 @@ async def lifespan(app: FastMCP):
35
46
  yield
36
47
  finally:
37
48
  watch_cursor.stop()
49
+ if analytics:
50
+ await analytics.close()
38
51
 
39
52
  mcp=FastMCP(name='windows-mcp',instructions=instructions,lifespan=lifespan)
40
53
 
@@ -49,6 +62,7 @@ mcp=FastMCP(name='windows-mcp',instructions=instructions,lifespan=lifespan)
49
62
  openWorldHint=False
50
63
  )
51
64
  )
65
+ @with_analytics(analytics, "App-Tool")
52
66
  def app_tool(mode:Literal['launch','resize','switch'],name:str|None=None,window_loc:list[int]|None=None,window_size:list[int]|None=None):
53
67
  return desktop.app(mode,name,window_loc,window_size)
54
68
 
@@ -63,6 +77,7 @@ def app_tool(mode:Literal['launch','resize','switch'],name:str|None=None,window_
63
77
  openWorldHint=True
64
78
  )
65
79
  )
80
+ @with_analytics(analytics, "Powershell-Tool")
66
81
  def powershell_tool(command: str) -> str:
67
82
  response,status_code=desktop.execute_command(command)
68
83
  return f'Response: {response}\nStatus Code: {status_code}'
@@ -78,6 +93,7 @@ def powershell_tool(command: str) -> str:
78
93
  openWorldHint=False
79
94
  )
80
95
  )
96
+ @with_analytics(analytics, "State-Tool")
81
97
  def state_tool(use_vision:bool=False,use_dom:bool=False):
82
98
  # Calculate scale factor to cap resolution at 1080p (1920x1080)
83
99
  max_width, max_height = 1920, 1080
@@ -118,6 +134,7 @@ def state_tool(use_vision:bool=False,use_dom:bool=False):
118
134
  openWorldHint=False
119
135
  )
120
136
  )
137
+ @with_analytics(analytics, "Click-Tool")
121
138
  def click_tool(loc:list[int],button:Literal['left','right','middle']='left',clicks:int=1)->str:
122
139
  if len(loc) != 2:
123
140
  raise ValueError("Location must be a list of exactly 2 integers [x, y]")
@@ -137,6 +154,7 @@ def click_tool(loc:list[int],button:Literal['left','right','middle']='left',clic
137
154
  openWorldHint=False
138
155
  )
139
156
  )
157
+ @with_analytics(analytics, "Type-Tool")
140
158
  def type_tool(loc:list[int],text:str,clear:bool=False,press_enter:bool=False)->str:
141
159
  if len(loc) != 2:
142
160
  raise ValueError("Location must be a list of exactly 2 integers [x, y]")
@@ -155,6 +173,7 @@ def type_tool(loc:list[int],text:str,clear:bool=False,press_enter:bool=False)->s
155
173
  openWorldHint=False
156
174
  )
157
175
  )
176
+ @with_analytics(analytics, "Scroll-Tool")
158
177
  def scroll_tool(loc:list[int]=None,type:Literal['horizontal','vertical']='vertical',direction:Literal['up','down','left','right']='down',wheel_times:int=1)->str:
159
178
  if loc and len(loc) != 2:
160
179
  raise ValueError("Location must be a list of exactly 2 integers [x, y]")
@@ -174,6 +193,7 @@ def scroll_tool(loc:list[int]=None,type:Literal['horizontal','vertical']='vertic
174
193
  openWorldHint=False
175
194
  )
176
195
  )
196
+ @with_analytics(analytics, "Drag-Tool")
177
197
  def drag_tool(to_loc:list[int])->str:
178
198
  if len(to_loc) != 2:
179
199
  raise ValueError("to_loc must be a list of exactly 2 integers [x, y]")
@@ -192,6 +212,7 @@ def drag_tool(to_loc:list[int])->str:
192
212
  openWorldHint=False
193
213
  )
194
214
  )
215
+ @with_analytics(analytics, "Move-Tool")
195
216
  def move_tool(to_loc:list[int])->str:
196
217
  if len(to_loc) != 2:
197
218
  raise ValueError("to_loc must be a list of exactly 2 integers [x, y]")
@@ -210,6 +231,7 @@ def move_tool(to_loc:list[int])->str:
210
231
  openWorldHint=False
211
232
  )
212
233
  )
234
+ @with_analytics(analytics, "Shortcut-Tool")
213
235
  def shortcut_tool(shortcut:str):
214
236
  desktop.shortcut(shortcut)
215
237
  return f"Pressed {shortcut}."
@@ -225,13 +247,14 @@ def shortcut_tool(shortcut:str):
225
247
  openWorldHint=False
226
248
  )
227
249
  )
250
+ @with_analytics(analytics, "Wait-Tool")
228
251
  def wait_tool(duration:int)->str:
229
252
  pg.sleep(duration)
230
253
  return f'Waited for {duration} seconds.'
231
254
 
232
255
  @mcp.tool(
233
256
  name='Scrape-Tool',
234
- description='Extracts visible text content from the currently focused browser tab. Returns content in plain text format with scroll status indicators (top/bottom reached or more content available). Only works when a browser with DOM is active. Use State-Tool with use_dom=True first to ensure browser is ready.',
257
+ description='Fetch content from a URL or the active browser tab. By default (use_dom=False), performs a lightweight HTTP request to the URL and returns markdown content of complete webpage. Note: Some websites may block automated HTTP requests. If this fails, open the page in a browser and retry with use_dom=True to extract visible text from the active tab\'s DOM within the viewport.',
235
258
  annotations=ToolAnnotations(
236
259
  title="Scrape Tool",
237
260
  readOnlyHint=True,
@@ -240,8 +263,13 @@ def wait_tool(duration:int)->str:
240
263
  openWorldHint=True
241
264
  )
242
265
  )
243
- def scrape_tool(url:str)->str:
244
- desktop_state=desktop.desktop_state
266
+ @with_analytics(analytics, "Scrape-Tool")
267
+ def scrape_tool(url:str,use_dom:bool=False)->str:
268
+ if not use_dom:
269
+ content=desktop.scrape(url)
270
+ return f'URL:{url}\nContent:\n{content}'
271
+
272
+ desktop_state=desktop.get_state(use_vision=False,use_dom=use_dom)
245
273
  tree_state=desktop_state.tree_state
246
274
  if not tree_state.dom_info:
247
275
  return f'No DOM information found. Please open {url} in browser first.'
@@ -250,7 +278,7 @@ def scrape_tool(url:str)->str:
250
278
  content='\n'.join([node.text for node in tree_state.dom_informative_nodes])
251
279
  header_status = "Reached top" if vertical_scroll_percent <= 0 else "Scroll up to see more"
252
280
  footer_status = "Reached bottom" if vertical_scroll_percent >= 100 else "Scroll down to see more"
253
- return f'URL:{url}\nContent:\n{header_status}\n{content}\n{footer_status}'
281
+ return f'URL:{url}\nContent:\n[{header_status}]\n{content}\n[{footer_status}]'
254
282
 
255
283
 
256
284
  @click.command()
@@ -0,0 +1,150 @@
1
+ from typing import Optional, Dict, Any, TypeVar, Callable, Protocol, Awaitable
2
+ from tempfile import TemporaryDirectory
3
+ from uuid_extensions import uuid7str
4
+ from functools import wraps
5
+ from pathlib import Path
6
+ import posthog
7
+ import asyncio
8
+ import logging
9
+ import time
10
+ import os
11
+
12
+ logging.basicConfig(level=logging.DEBUG)
13
+ logger = logging.getLogger(__name__)
14
+
15
+ T = TypeVar("T")
16
+
17
+ class Analytics(Protocol):
18
+ async def track_tool(self, tool_name: str, result: Dict[str, Any]) -> None:
19
+ """Tracks the execution of a tool."""
20
+ ...
21
+
22
+ async def track_error(self, error: Exception, context: Dict[str, Any]) -> None:
23
+ """Tracks an error that occurred during the execution of a tool."""
24
+ ...
25
+
26
+ async def is_feature_enabled(self, feature: str) -> bool:
27
+ """Checks if a feature flag is enabled."""
28
+ ...
29
+
30
+ async def close(self) -> None:
31
+ """Closes the analytics client."""
32
+ ...
33
+
34
+ class PostHogAnalytics:
35
+ TEMP_FOLDER = Path(TemporaryDirectory().name).parent
36
+ API_KEY = 'phc_uxdCItyVTjXNU0sMPr97dq3tcz39scQNt3qjTYw5vLV'
37
+ HOST = 'https://us.i.posthog.com'
38
+
39
+ def __init__(self):
40
+ self.client = posthog.Posthog(
41
+ self.API_KEY,
42
+ host=self.HOST,
43
+ disable_geoip=False,
44
+ enable_exception_autocapture=True,
45
+ debug=True
46
+ )
47
+ self._user_id = None
48
+ self.mcp_interaction_id = f"mcp_{int(time.time()*1000)}_{os.getpid()}"
49
+
50
+ if self.client:
51
+ logger.debug(f"Initialized with user ID: {self.user_id} and session ID: {self.mcp_interaction_id}")
52
+
53
+ @property
54
+ def user_id(self) -> str:
55
+ if self._user_id:
56
+ return self._user_id
57
+
58
+ user_id_file = self.TEMP_FOLDER / '.windows-mcp-user-id'
59
+ if user_id_file.exists():
60
+ self._user_id = user_id_file.read_text(encoding='utf-8').strip()
61
+ else:
62
+ self._user_id = uuid7str()
63
+ try:
64
+ user_id_file.write_text(self._user_id, encoding='utf-8')
65
+ except Exception as e:
66
+ logger.warning(f"Could not persist user ID: {e}")
67
+
68
+ return self._user_id
69
+
70
+ async def track_tool(self, tool_name: str, result: Dict[str, Any]) -> None:
71
+ if self.client:
72
+ self.client.capture(
73
+ distinct_id=self.user_id,
74
+ event="tool_executed",
75
+ properties={
76
+ "tool_name": tool_name,
77
+ "session_id": self.mcp_interaction_id,
78
+ "process_person_profile": True,
79
+ **result
80
+ }
81
+ )
82
+
83
+ duration = result.get("duration_ms", 0)
84
+ success_mark = "SUCCESS" if result.get("success") else "FAILED"
85
+ # Using print for immediate visibility in console during debugging
86
+ print(f"[Analytics] {tool_name}: {success_mark} ({duration}ms)")
87
+ logger.info(f"{tool_name}: {success_mark} ({duration}ms)")
88
+ if self.client:
89
+ self.client.flush()
90
+
91
+ async def track_error(self, error: Exception, context: Dict[str, Any]) -> None:
92
+ if self.client:
93
+ self.client.capture(
94
+ distinct_id=self.user_id,
95
+ event="exception",
96
+ properties={
97
+ "exception": str(error),
98
+ "traceback": str(error) if not hasattr(error, '__traceback__') else str(error),
99
+ "session_id": self.mcp_interaction_id,
100
+ "process_person_profile": True,
101
+ **context
102
+ }
103
+ )
104
+
105
+ if self.client:
106
+ self.client.flush()
107
+
108
+ logger.error(f"ERROR in {context.get('tool_name')}: {error}")
109
+
110
+ async def is_feature_enabled(self, feature: str) -> bool:
111
+ if not self.client:
112
+ return False
113
+ return self.client.is_feature_enabled(feature, self.user_id)
114
+
115
+ async def close(self) -> None:
116
+ if self.client:
117
+ self.client.shutdown()
118
+ logger.debug("Closed analytics")
119
+
120
+ def with_analytics(analytics_instance: Optional[Analytics], tool_name: str):
121
+ """
122
+ Decorator to wrap tool functions with analytics tracking.
123
+ """
124
+ def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
125
+ @wraps(func)
126
+ async def wrapper(*args, **kwargs) -> T:
127
+ start = time.time()
128
+ try:
129
+ if asyncio.iscoroutinefunction(func):
130
+ result = await func(*args, **kwargs)
131
+ else:
132
+ # Run sync function in thread to avoid blocking loop
133
+ result = await asyncio.to_thread(func, *args, **kwargs)
134
+
135
+ duration_ms = int((time.time() - start) * 1000)
136
+
137
+ if analytics_instance:
138
+ await analytics_instance.track_tool(tool_name, {"duration_ms": duration_ms, "success": True})
139
+
140
+ return result
141
+ except Exception as error:
142
+ duration_ms = int((time.time() - start) * 1000)
143
+ if analytics_instance:
144
+ await analytics_instance.track_error(error, {
145
+ "tool_name": tool_name,
146
+ "duration_ms": duration_ms
147
+ })
148
+ raise error
149
+ return wrapper
150
+ return decorator
@@ -1,10 +1,10 @@
1
1
  from windows_mcp.desktop.config import BROWSER_NAMES, PROCESS_PER_MONITOR_DPI_AWARE
2
2
  from windows_mcp.desktop.views import DesktopState, App, Size, Status
3
+ from windows_mcp.tree.service import Tree
3
4
  from locale import getpreferredencoding
4
5
  from contextlib import contextmanager
5
6
  from typing import Optional,Literal
6
7
  from markdownify import markdownify
7
- from windows_mcp.tree.service import Tree
8
8
  from fuzzywuzzy import process
9
9
  from psutil import Process
10
10
  from time import sleep
@@ -172,7 +172,7 @@ class Desktop:
172
172
  sleep(1.25)
173
173
  if status!=0:
174
174
  return response
175
- consecutive_waits=3
175
+ consecutive_waits=10
176
176
  for _ in range(consecutive_waits):
177
177
  if not self.is_app_running(name):
178
178
  sleep(1.25)
@@ -200,11 +200,12 @@ class Desktop:
200
200
  app_name,_=matched_app
201
201
  appid=apps_map.get(app_name)
202
202
  if appid is None:
203
- return (name,f'{name.title()} not found in start menu.',1)
204
- if name.endswith('.exe'):
205
- response,status=self.execute_command(f'Start-Process {appid}')
203
+ return (f'{name.title()} not found in start menu.',1)
204
+ if appid.endswith('.exe'):
205
+ command=f"Start-Process '{appid}'"
206
206
  else:
207
- response,status=self.execute_command(f'Start-Process shell:AppsFolder\\{appid}')
207
+ command=f"Start-Process shell:AppsFolder\\{appid}"
208
+ response,status=self.execute_command(command)
208
209
  return response,status
209
210
 
210
211
  def switch_app(self,name:str):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: windows-mcp
3
- Version: 0.5.5
3
+ Version: 0.5.6
4
4
  Summary: Lightweight MCP Server for interacting with Windows Operating System.
5
5
  Project-URL: homepage, https://github.com/CursorTouch
6
6
  Author-email: Jeomon George <jeogeoalukka@gmail.com>
@@ -37,14 +37,17 @@ Requires-Dist: live-inspect>=0.1.1
37
37
  Requires-Dist: markdownify>=1.1.0
38
38
  Requires-Dist: pdfplumber>=0.11.7
39
39
  Requires-Dist: pillow>=11.2.1
40
+ Requires-Dist: posthog>=7.4.0
40
41
  Requires-Dist: psutil>=7.0.0
41
42
  Requires-Dist: pyautogui>=0.9.54
42
43
  Requires-Dist: pygetwindow>=0.0.9
44
+ Requires-Dist: python-dotenv>=1.1.0
43
45
  Requires-Dist: python-levenshtein>=0.27.1
44
46
  Requires-Dist: pywinauto>=0.6.9
45
47
  Requires-Dist: requests>=2.32.3
46
48
  Requires-Dist: tabulate>=0.9.0
47
49
  Requires-Dist: uiautomation>=2.0.24
50
+ Requires-Dist: uuid7>=0.1.0
48
51
  Description-Content-Type: text/markdown
49
52
 
50
53
  [![MseeP.ai Security Assessment Badge](https://mseep.net/pr/cursortouch-windows-mcp-badge.png)](https://mseep.ai/app/cursortouch-windows-mcp)
@@ -261,7 +264,6 @@ npm install -g @google/gemini-cli
261
264
  {
262
265
  "theme": "Default",
263
266
  ...
264
- //MCP Server Config
265
267
  "mcpServers": {
266
268
  "windows-mcp": {
267
269
  "command": "uvx",
@@ -295,7 +297,6 @@ npm install -g @qwen-code/qwen-code@latest
295
297
 
296
298
  ```json
297
299
  {
298
- //MCP Server Config
299
300
  "mcpServers": {
300
301
  "windows-mcp": {
301
302
  "command": "uvx",
@@ -384,6 +385,28 @@ For detailed security information, including:
384
385
 
385
386
  Please read our [Security Policy](SECURITY.md).
386
387
 
388
+ ## 📊 Telemetry
389
+
390
+ Windows-MCP collects anonymized usage data to help improve the tool. No personal information, no tool arguments, no outputs are tracked.
391
+
392
+ To disable telemetry, add the following to your MCP client configuration:
393
+
394
+ ```json
395
+ {
396
+ "mcpServers": {
397
+ "windows-mcp": {
398
+ "command": "uvx",
399
+ "args": [
400
+ "windows-mcp"
401
+ ],
402
+ "env": {
403
+ "ANONYMIZED_TELEMETRY": "false"
404
+ }
405
+ }
406
+ }
407
+ }
408
+ ```
409
+
387
410
  ## 📝 Limitations
388
411
 
389
412
  - Selecting specific sections of the text in a paragraph, as the MCP is relying on a11y tree. (⌛ Working on it.)
@@ -421,3 +444,4 @@ Made with ❤️ by [CursorTouch](https://github.com/CursorTouch)
421
444
  url={https://github.com/CursorTouch/Windows-MCP}
422
445
  }
423
446
  ```
447
+
@@ -1,16 +1,17 @@
1
1
  windows_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- windows_mcp/__main__.py,sha256=pkwexVikZwUFHe0oqmMYFfiRavjNfs5Bv-ELvLv9Dpo,11939
2
+ windows_mcp/__main__.py,sha256=fHuuwAakKCFV1-Wqc2vd079pu87mf3CYMuEINIA0CBA,13040
3
+ windows_mcp/analytics.py,sha256=ZQmGlDJeB4pfHmRZXcPeFOxQh-LYrauBUqwEHOgS9Mg,5568
3
4
  windows_mcp/desktop/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
5
  windows_mcp/desktop/config.py,sha256=7rAb64pmC275PpNRXVOyOf0Psu089AOosRC8T5kVGWA,384
5
- windows_mcp/desktop/service.py,sha256=97e2E4TdMs3TwW6CtupVxnwhWqdBKU5eH4MDz6_5Hmk,18469
6
+ windows_mcp/desktop/service.py,sha256=hJqTMmo7utBRRdtmVUxaWXMw8XyBD6Pc1Y6tCk6YAvU,18463
6
7
  windows_mcp/desktop/views.py,sha256=_hZ5sfY1uWVi5mpaysVd-plwP_DT6SXpKa33Z8WT6gI,1523
7
8
  windows_mcp/tree/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
9
  windows_mcp/tree/config.py,sha256=k-Mjo_yIn0d1AzcEW_bxiaXyBFxBZZSyy7hCNQ3XVp0,1010
9
10
  windows_mcp/tree/service.py,sha256=evK62AwhMwifpq6lRQCdrmC4DPt1-w_HSp8nUwXsCVQ,23566
10
11
  windows_mcp/tree/utils.py,sha256=6hbxdIQPrAY-I3jcHsRqodHlxboTQj2GnLA71bf1lqY,911
11
12
  windows_mcp/tree/views.py,sha256=K2hTBDicjP4p_tPIRTLZ8Sq3pGYhsDtZVIROAnMGTz4,3599
12
- windows_mcp-0.5.5.dist-info/METADATA,sha256=Jx7stv6_Lm145NSLB8EdAsRJsBXiP0FhIQ-7cA2FmEU,13537
13
- windows_mcp-0.5.5.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
14
- windows_mcp-0.5.5.dist-info/entry_points.txt,sha256=wW8NcVQ_OJK5e5GemZSE_nOKyxfUtBPq2acFLszRwaw,58
15
- windows_mcp-0.5.5.dist-info/licenses/LICENSE.md,sha256=U1UM4Xi_IX-jHnHjGT0rETNia-Ck8gd92iSQMqQ6a8Y,1089
16
- windows_mcp-0.5.5.dist-info/RECORD,,
13
+ windows_mcp-0.5.6.dist-info/METADATA,sha256=ENARm5l-oAjYUB88yjWCWZIH7_5qN4xPd1ceUh50y5o,14024
14
+ windows_mcp-0.5.6.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
15
+ windows_mcp-0.5.6.dist-info/entry_points.txt,sha256=wW8NcVQ_OJK5e5GemZSE_nOKyxfUtBPq2acFLszRwaw,58
16
+ windows_mcp-0.5.6.dist-info/licenses/LICENSE.md,sha256=U1UM4Xi_IX-jHnHjGT0rETNia-Ck8gd92iSQMqQ6a8Y,1089
17
+ windows_mcp-0.5.6.dist-info/RECORD,,