mcpower-proxy 0.0.67__py3-none-any.whl → 0.0.73__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.
Files changed (36) hide show
  1. ide_tools/__init__.py +12 -0
  2. ide_tools/common/__init__.py +6 -0
  3. ide_tools/common/hooks/__init__.py +6 -0
  4. ide_tools/common/hooks/init.py +125 -0
  5. ide_tools/common/hooks/output.py +64 -0
  6. ide_tools/common/hooks/prompt_submit.py +186 -0
  7. ide_tools/common/hooks/read_file.py +170 -0
  8. ide_tools/common/hooks/shell_execution.py +196 -0
  9. ide_tools/common/hooks/types.py +35 -0
  10. ide_tools/common/hooks/utils.py +276 -0
  11. ide_tools/cursor/__init__.py +11 -0
  12. ide_tools/cursor/constants.py +58 -0
  13. ide_tools/cursor/format.py +35 -0
  14. ide_tools/cursor/router.py +100 -0
  15. ide_tools/router.py +48 -0
  16. main.py +11 -4
  17. {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.73.dist-info}/METADATA +3 -3
  18. mcpower_proxy-0.0.73.dist-info/RECORD +59 -0
  19. {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.73.dist-info}/top_level.txt +1 -0
  20. modules/apis/security_policy.py +11 -6
  21. modules/decision_handler.py +219 -0
  22. modules/logs/audit_trail.py +16 -15
  23. modules/logs/logger.py +14 -18
  24. modules/redaction/redactor.py +112 -107
  25. modules/ui/__init__.py +1 -1
  26. modules/ui/confirmation.py +0 -1
  27. modules/utils/cli.py +36 -6
  28. modules/utils/ids.py +50 -7
  29. modules/utils/json.py +3 -3
  30. wrapper/__version__.py +1 -1
  31. wrapper/middleware.py +115 -212
  32. wrapper/server.py +19 -11
  33. mcpower_proxy-0.0.67.dist-info/RECORD +0 -43
  34. {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.73.dist-info}/WHEEL +0 -0
  35. {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.73.dist-info}/entry_points.txt +0 -0
  36. {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.73.dist-info}/licenses/LICENSE +0 -0
modules/utils/ids.py CHANGED
@@ -24,6 +24,16 @@ def generate_event_id() -> str:
24
24
  return f"{timestamp}-{unique_part}"
25
25
 
26
26
 
27
+ def generate_prompt_id() -> str:
28
+ """
29
+ Generate truly-random 8-character prompt ID for user request correlation
30
+
31
+ Returns:
32
+ 8-character random ID string
33
+ """
34
+ return str(uuid.uuid4())[:8]
35
+
36
+
27
37
  def get_session_id() -> str:
28
38
  """
29
39
  Get session ID for the current process. Returns the same value for all calls
@@ -109,20 +119,53 @@ def _get_or_create_uuid(uid_path: Path, logger, id_type: str) -> str:
109
119
  time.sleep(0.1 * (2 ** attempt))
110
120
  continue
111
121
  raise
112
-
122
+
113
123
  new_uid = str(uuid.uuid4())
114
-
124
+
115
125
  if _atomic_write_uuid(uid_path, new_uid):
116
126
  logger.info(f"Generated {id_type}: {new_uid} at {uid_path}")
117
127
  return new_uid
118
-
119
- logger.debug(f"{id_type.title()} file created by another process, reading (attempt {attempt + 1}/{max_attempts})")
128
+
129
+ logger.debug(
130
+ f"{id_type.title()} file created by another process, reading (attempt {attempt + 1}/{max_attempts})")
120
131
  if attempt < max_attempts - 1:
121
132
  time.sleep(0.05)
122
-
133
+
123
134
  raise RuntimeError(f"Failed to get or create {id_type} after {max_attempts} attempts")
124
135
 
125
136
 
137
+ def get_home_mcpower_dir() -> Path:
138
+ """
139
+ Get the global MCPower directory path in user's home directory
140
+
141
+ Returns:
142
+ Path to ~/.mcpower directory
143
+ """
144
+ return Path.home() / ".mcpower"
145
+
146
+
147
+ def get_project_mcpower_dir(project_path: Optional[str] = None) -> str:
148
+ """
149
+ Get the MCPower directory path, with fallback to global ~/.mcpower
150
+
151
+ Args:
152
+ project_path: Optional project/workspace path. If None or invalid, falls back to ~/.mcpower
153
+
154
+ Returns:
155
+ Path to use for MCPower data (either project/.mcpower or ~/.mcpower)
156
+ """
157
+ if project_path:
158
+ try:
159
+ path = Path(project_path)
160
+ if path.exists() and path.is_dir():
161
+ return str(path)
162
+ except Exception:
163
+ pass
164
+
165
+ # Fallback to global ~/.mcpower
166
+ return str(get_home_mcpower_dir())
167
+
168
+
126
169
  def get_or_create_user_id(logger) -> str:
127
170
  """
128
171
  Get or create machine-wide user ID from ~/.mcpower/uid
@@ -134,7 +177,7 @@ def get_or_create_user_id(logger) -> str:
134
177
  Returns:
135
178
  User ID string
136
179
  """
137
- uid_path = Path.home() / ".mcpower" / "uid"
180
+ uid_path = get_home_mcpower_dir() / "uid"
138
181
  return _get_or_create_uuid(uid_path, logger, "user ID")
139
182
 
140
183
 
@@ -158,5 +201,5 @@ def read_app_uid(logger, project_folder_path: str) -> str:
158
201
  else:
159
202
  # Project-specific case
160
203
  uid_path = project_path / ".mcpower" / "app_uid"
161
-
204
+
162
205
  return _get_or_create_uuid(uid_path, logger, "app UID")
modules/utils/json.py CHANGED
@@ -52,7 +52,7 @@ def safe_json_dumps(obj: Any, **kwargs) -> str:
52
52
  # If it's a Pydantic BaseModel, use its built-in JSON serialization
53
53
  if isinstance(obj, BaseModel):
54
54
  return obj.model_dump_json(**kwargs)
55
-
55
+
56
56
  # If it's a dict or list that might contain Pydantic objects, use custom serializer
57
57
  def default_serializer(o):
58
58
  if isinstance(o, BaseModel):
@@ -72,7 +72,7 @@ def safe_json_dumps(obj: Any, **kwargs) -> str:
72
72
  return o.__dict__
73
73
  # Fallback to string representation
74
74
  return str(o)
75
-
75
+
76
76
  return json.dumps(obj, default=default_serializer, **kwargs)
77
77
 
78
78
 
@@ -117,4 +117,4 @@ def parse_jsonc(text: str) -> Any:
117
117
  return json.loads(text)
118
118
  except json.JSONDecodeError:
119
119
  # Re-raise the original JSONC error if JSON also fails
120
- raise json.JSONDecodeError(f"JSONC parsing failed: {str(e)}", text, 0)
120
+ raise json.JSONDecodeError(f"JSONC parsing failed: {str(e)}", text, 0)
wrapper/__version__.py CHANGED
@@ -3,4 +3,4 @@
3
3
  Wrapper MCP Server Version
4
4
  """
5
5
 
6
- __version__ = "0.0.67"
6
+ __version__ = "0.0.73"
wrapper/middleware.py CHANGED
@@ -2,6 +2,7 @@
2
2
  FastMCP middleware for security policy enforcement
3
3
  Implements pre/post interception for all MCP operations
4
4
  """
5
+ import asyncio
5
6
  import sys
6
7
  import time
7
8
  import urllib.parse
@@ -12,22 +13,23 @@ from typing import Any, Dict, List, Optional
12
13
  from fastmcp.exceptions import FastMCPError
13
14
  from fastmcp.server.middleware.middleware import Middleware, MiddlewareContext, CallNext
14
15
  from fastmcp.server.proxy import ProxyClient
16
+ from httpx import HTTPStatusError
17
+ from mcp import ErrorData
18
+
19
+ from mcpower_shared.mcp_types import (create_policy_request, create_policy_response, AgentContext, EnvironmentContext,
20
+ InitRequest,
21
+ ServerRef, ToolRef)
15
22
  from modules.apis.security_policy import SecurityPolicyClient
23
+ from modules.decision_handler import DecisionHandler, DecisionEnforcementError
16
24
  from modules.logs.audit_trail import AuditTrailLogger
17
25
  from modules.logs.logger import MCPLogger
18
26
  from modules.redaction import redact
19
- from modules.ui.classes import ConfirmationRequest, DialogOptions, UserDecision
20
- from modules.ui.confirmation import UserConfirmationDialog, UserConfirmationError
21
27
  from modules.utils.copy import safe_copy
22
- from modules.utils.ids import generate_event_id, get_session_id, read_app_uid
28
+ from modules.utils.ids import generate_event_id, get_session_id, read_app_uid, get_project_mcpower_dir
23
29
  from modules.utils.json import safe_json_dumps, to_dict
24
30
  from modules.utils.mcp_configs import extract_wrapped_server_info
25
31
  from wrapper.schema import merge_input_schema_with_existing
26
32
 
27
- from mcpower_shared.mcp_types import (create_policy_request, create_policy_response, AgentContext, EnvironmentContext,
28
- InitRequest,
29
- ServerRef, ToolRef, UserConfirmation)
30
-
31
33
 
32
34
  class MockContext:
33
35
  """Mock context for internal operations"""
@@ -53,10 +55,7 @@ class MockContext:
53
55
  class SecurityMiddleware(Middleware):
54
56
  """FastMCP middleware for security policy enforcement"""
55
57
 
56
- app_id: str = ""
57
58
  _TOOLS_INIT_DEBOUNCE_SECONDS = 60
58
- _last_tools_init_time: Optional[float] = None
59
- _last_workspace_root: Optional[str] = None
60
59
 
61
60
  def __init__(self,
62
61
  wrapped_server_configs: dict,
@@ -72,6 +71,9 @@ class SecurityMiddleware(Middleware):
72
71
  self.audit_logger = audit_logger
73
72
  self.app_id = ""
74
73
  self._last_workspace_root = None
74
+ self._last_tools_init_time: Optional[float] = None
75
+ self._tools_list_in_progress: Optional[asyncio.Task] = None
76
+ self._tools_list_lock = asyncio.Lock()
75
77
 
76
78
  self.wrapped_server_name, self.wrapped_server_transport = (
77
79
  extract_wrapped_server_info(self.wrapper_server_name, self.logger, self.wrapped_server_configs)
@@ -88,17 +90,36 @@ class SecurityMiddleware(Middleware):
88
90
  async def on_message(self, context: MiddlewareContext, call_next: CallNext) -> Any:
89
91
  self.logger.info(f"on_message: {redact(safe_json_dumps(context))}")
90
92
 
91
- # Check workspace roots and re-initialize app_uid if workspace changed
92
- workspace_roots = await self._extract_workspace_roots(context)
93
- current_workspace_root = workspace_roots[0] if workspace_roots else str(Path.home() / ".mcpower")
94
- if current_workspace_root != self._last_workspace_root:
95
- self.logger.debug(f"Workspace root changed from {self._last_workspace_root} to {current_workspace_root}")
96
- self._last_workspace_root = current_workspace_root
97
- self.app_id = read_app_uid(logger=self.logger, project_folder_path=current_workspace_root)
98
- self.audit_logger.set_app_uid(self.app_id)
93
+ # Skip workspace check for `initialize` calls to avoid premature app_uid changes.
94
+ # The `initialize` request doesn't contain workspace data, so checking it would
95
+ # cause unnecessary audit log flushes before the actual workspace init arrives.
96
+ if context.method != "initialize":
97
+ # Check workspace roots and re-initialize app_uid if workspace changed
98
+ workspace_roots = await self._extract_workspace_roots(context)
99
+ current_workspace_root = get_project_mcpower_dir(workspace_roots[0] if workspace_roots else None)
100
+ if current_workspace_root != self._last_workspace_root:
101
+ self.logger.debug(
102
+ f"Workspace root changed from {self._last_workspace_root} to {current_workspace_root}")
103
+ self._last_workspace_root = current_workspace_root
104
+ self.app_id = read_app_uid(logger=self.logger, project_folder_path=current_workspace_root)
105
+ self.audit_logger.set_app_uid(self.app_id)
99
106
 
100
107
  operation_type = "message"
101
- call_next_callback = call_next
108
+
109
+ async def call_next_wrapper(ctx):
110
+ try:
111
+ return await call_next(ctx)
112
+ except HTTPStatusError as e:
113
+ if e.response.status_code in (401, 403):
114
+ raise FastMCPError(ErrorData(
115
+ code=-32000,
116
+ message="Authentication required",
117
+ data={
118
+ "type": "unauthorized",
119
+ "details": "Please provide valid authentication credentials"
120
+ }
121
+ ))
122
+ raise e
102
123
 
103
124
  match context.type:
104
125
  case "request":
@@ -115,13 +136,13 @@ class SecurityMiddleware(Middleware):
115
136
  operation_type = "prompt"
116
137
  case "tools/list":
117
138
  # Special handling for tools/list - call /init instead of normal inspection
118
- return await self._handle_tools_list(context, call_next)
139
+ return await self._handle_tools_list(context, call_next_wrapper)
119
140
  case "initialize" | "resources/list" | "resources/templates/list" | "prompts/list":
120
- return await call_next_callback(context)
141
+ return await call_next_wrapper(context)
121
142
 
122
143
  return await self._handle_operation(
123
144
  context=context,
124
- call_next=call_next_callback,
145
+ call_next=call_next_wrapper,
125
146
  error_class=FastMCPError,
126
147
  operation_type=operation_type
127
148
  )
@@ -181,15 +202,15 @@ class SecurityMiddleware(Middleware):
181
202
  return await ProxyClient.default_progress_handler(progress, total, message)
182
203
 
183
204
  async def secure_log_handler(self, log_message):
184
- # FIXME: log_message should be redacted before logging,
205
+ # FIXME: log_message should be redacted before logging,
185
206
  self.logger.info(f"secure_log_handler: {str(log_message)[:100]}...")
186
207
  # FIXME: log_message should be reviewed with policy before forwarding
187
-
208
+
188
209
  # Handle case where log_message.data is a string instead of dict
189
210
  # The default_log_handler expects data to be a dict with 'msg' and 'extra' keys
190
211
  if hasattr(log_message, 'data') and isinstance(log_message.data, str):
191
212
  log_message = safe_copy(log_message, {'data': {'msg': log_message.data, 'extra': None}})
192
-
213
+
193
214
  return await ProxyClient.default_log_handler(log_message)
194
215
 
195
216
  async def _handle_operation(self, context: MiddlewareContext, call_next, error_class, operation_type: str):
@@ -222,19 +243,28 @@ class SecurityMiddleware(Middleware):
222
243
  prompt_id=prompt_id
223
244
  )
224
245
  on_inspect_request_duration = time.time() - on_inspect_request_start_time
225
- self.logger.info(f"PROFILE: {operation_type} id: {event_id} inspect_request duration: {on_inspect_request_duration:.2f} seconds")
246
+ self.logger.debug(
247
+ f"PROFILE: {operation_type} id: {event_id} inspect_request duration: {on_inspect_request_duration:.2f} seconds")
226
248
 
227
- await self._enforce_decision(
228
- decision=request_decision,
229
- error_class=error_class,
230
- base_message=f"{operation_type.title()} request blocked by security policy",
231
- is_request=True,
232
- event_id=event_id,
233
- tool_name=tool_name,
234
- content_data=tool_args,
235
- operation_type=operation_type,
236
- prompt_id=prompt_id
237
- )
249
+ try:
250
+ await DecisionHandler(
251
+ logger=self.logger,
252
+ audit_logger=self.audit_logger,
253
+ session_id=self.session_id,
254
+ app_id=self.app_id
255
+ ).enforce_decision(
256
+ decision=request_decision,
257
+ is_request=True,
258
+ event_id=event_id,
259
+ tool_name=tool_name,
260
+ content_data=tool_args,
261
+ operation_type=operation_type,
262
+ prompt_id=prompt_id,
263
+ server_name=self.wrapped_server_name,
264
+ error_message_prefix=f"{operation_type.title()} request blocked by security policy"
265
+ )
266
+ except DecisionEnforcementError as e:
267
+ raise error_class(str(e))
238
268
 
239
269
  self.audit_logger.log_event(
240
270
  "agent_request_forwarded",
@@ -251,7 +281,8 @@ class SecurityMiddleware(Middleware):
251
281
  # Call wrapped MCP with cleaned context (e.g., no wrapper args)
252
282
  result = await call_next(cleaned_context)
253
283
  on_call_next_duration = time.time() - on_call_next_start_time
254
- self.logger.info(f"PROFILE: {operation_type} id: {event_id} call_next duration: {on_call_next_duration:.2f} seconds")
284
+ self.logger.debug(
285
+ f"PROFILE: {operation_type} id: {event_id} call_next duration: {on_call_next_duration:.2f} seconds")
255
286
 
256
287
  response_content = self._extract_response_content(result)
257
288
 
@@ -276,19 +307,28 @@ class SecurityMiddleware(Middleware):
276
307
  prompt_id=prompt_id
277
308
  )
278
309
  on_inspect_response_duration = time.time() - on_inspect_response_start_time
279
- self.logger.info(f"PROFILE: {operation_type} id: {event_id} inspect_response duration: {on_inspect_response_duration:.2f} seconds")
310
+ self.logger.debug(
311
+ f"PROFILE: {operation_type} id: {event_id} inspect_response duration: {on_inspect_response_duration:.2f} seconds")
280
312
 
281
- await self._enforce_decision(
282
- decision=response_decision,
283
- error_class=error_class,
284
- base_message=f"{operation_type.title()} response blocked by security policy",
285
- is_request=False,
286
- event_id=event_id,
287
- tool_name=tool_name,
288
- content_data=response_content,
289
- operation_type=operation_type,
290
- prompt_id=prompt_id
291
- )
313
+ try:
314
+ await DecisionHandler(
315
+ logger=self.logger,
316
+ audit_logger=self.audit_logger,
317
+ session_id=self.session_id,
318
+ app_id=self.app_id
319
+ ).enforce_decision(
320
+ decision=response_decision,
321
+ is_request=False,
322
+ event_id=event_id,
323
+ tool_name=tool_name,
324
+ content_data=response_content,
325
+ operation_type=operation_type,
326
+ prompt_id=prompt_id,
327
+ server_name=self.wrapped_server_name,
328
+ error_message_prefix=f"{operation_type.title()} response blocked by security policy"
329
+ )
330
+ except DecisionEnforcementError as e:
331
+ raise error_class(str(e))
292
332
 
293
333
  self.audit_logger.log_event(
294
334
  "mcp_response_forwarded",
@@ -301,15 +341,30 @@ class SecurityMiddleware(Middleware):
301
341
  prompt_id=prompt_id
302
342
  )
303
343
  on_handle_operation_duration = time.time() - on_handle_operation_start_time
304
- self.logger.info(f"PROFILE: {operation_type} id: {event_id} duration: {on_handle_operation_duration:.2f} seconds")
344
+ self.logger.debug(
345
+ f"PROFILE: {operation_type} id: {event_id} duration: {on_handle_operation_duration:.2f} seconds")
305
346
  return result
306
347
 
307
348
  async def _handle_tools_list(self, context: MiddlewareContext, call_next: CallNext) -> Any:
308
- """Handle tools/list by calling /init API and modifying schemas"""
349
+ """Handle tools/list by calling /init API and modifying schemas with deduplication"""
309
350
  event_id = generate_event_id()
310
351
  on_handle_tools_list_start_time = time.time()
311
- result = await call_next(context)
312
- self.logger.info(f"PROFILE: tools/list call_next duration: {time.time() - on_handle_tools_list_start_time:.2f} seconds id: {event_id}")
352
+
353
+ async with self._tools_list_lock:
354
+ if not self._tools_list_in_progress or self._tools_list_in_progress.done():
355
+ self._tools_list_in_progress = asyncio.create_task(call_next(context))
356
+ shared_task = self._tools_list_in_progress
357
+
358
+ try:
359
+ result = await shared_task
360
+ except Exception as e:
361
+ async with self._tools_list_lock:
362
+ if self._tools_list_in_progress is shared_task:
363
+ self._tools_list_in_progress = None
364
+ raise
365
+ self.logger.debug(
366
+ f"PROFILE: tools/list call_next duration: {time.time() - on_handle_tools_list_start_time:.2f} seconds id: {event_id}")
367
+
313
368
  tools_list = None
314
369
  if isinstance(result, list):
315
370
  tools_list = result
@@ -339,11 +394,13 @@ class SecurityMiddleware(Middleware):
339
394
  enhanced_result = result
340
395
 
341
396
  on_handle_tools_list_duration = time.time() - on_handle_tools_list_start_time
342
- self.logger.info(f"PROFILE: tools/list enhanced_result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
397
+ self.logger.debug(
398
+ f"PROFILE: tools/list enhanced_result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
343
399
  return enhanced_result
344
400
 
345
401
  on_handle_tools_list_duration = time.time() - on_handle_tools_list_start_time
346
- self.logger.info(f"PROFILE: tools/list result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
402
+ self.logger.debug(
403
+ f"PROFILE: tools/list result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
347
404
 
348
405
  return result
349
406
 
@@ -482,12 +539,12 @@ class SecurityMiddleware(Middleware):
482
539
  file_path_prefix = 'file://'
483
540
  if uri.startswith(file_path_prefix):
484
541
  path = urllib.parse.unquote(uri[len(file_path_prefix):])
485
-
542
+
486
543
  # Windows fix: remove leading slash before drive letter
487
544
  # file:///C:/path becomes /C:/path, should be C:/path
488
545
  if sys.platform == 'win32' and len(path) >= 3 and path[0] == '/' and path[2] == ':':
489
546
  path = path[1:]
490
-
547
+
491
548
  try:
492
549
  resolved_path = str(Path(path).resolve())
493
550
  workspace_roots.append(resolved_path)
@@ -593,28 +650,6 @@ class SecurityMiddleware(Middleware):
593
650
  )
594
651
  }
595
652
 
596
- async def _record_user_confirmation(self, event_id: str, is_request: bool, user_decision: UserDecision,
597
- prompt_id: str, call_type: str = None):
598
- """Record user confirmation decision with the security API"""
599
- try:
600
- direction = "request" if is_request else "response"
601
-
602
- user_confirmation = UserConfirmation(
603
- event_id=event_id,
604
- direction=direction,
605
- user_decision=user_decision,
606
- call_type=call_type
607
- )
608
-
609
- async with SecurityPolicyClient(session_id=self.session_id, logger=self.logger,
610
- audit_logger=self.audit_logger, app_id=self.app_id) as client:
611
- result = await client.record_user_confirmation(user_confirmation, prompt_id=prompt_id)
612
- self.logger.debug(f"User confirmation recorded: {result}")
613
- except Exception as e:
614
- # Don't fail the operation if API call fails - just log the error
615
- self.logger.error(f"Failed to record user confirmation: {e}")
616
-
617
-
618
653
  @staticmethod
619
654
  def _create_security_api_failure_decision(error: Exception) -> Dict[str, Any]:
620
655
  """Create a standard failure decision when security API is unavailable/failing/unreachable"""
@@ -624,135 +659,3 @@ class SecurityMiddleware(Middleware):
624
659
  "reasons": [f"Security API unavailable: {error}"],
625
660
  "matched_rules": ["security_api.error"]
626
661
  }
627
-
628
- async def _enforce_decision(self, decision: Dict[str, Any], error_class, base_message: str,
629
- is_request: bool, event_id: str, tool_name: str, content_data: Dict[str, Any],
630
- operation_type: str, prompt_id: str):
631
- """Enforce security decision with user confirmation support"""
632
- decision_type = decision.get("decision", "block")
633
-
634
- if decision_type == "allow":
635
- return
636
-
637
- elif decision_type == "block":
638
- policy_reasons = decision.get("reasons", ["Policy violation"])
639
- severity = decision.get("severity", "unknown")
640
- call_type = decision.get("call_type")
641
-
642
- try:
643
- # Show a blocking dialog and wait for user decision
644
- confirmation_request = ConfirmationRequest(
645
- is_request=is_request,
646
- tool_name=tool_name,
647
- policy_reasons=policy_reasons,
648
- content_data=content_data,
649
- severity=severity,
650
- event_id=event_id,
651
- operation_type=operation_type,
652
- server_name=self.wrapped_server_name,
653
- timeout_seconds=60
654
- )
655
-
656
- response = UserConfirmationDialog(
657
- self.logger, self.audit_logger
658
- ).request_blocking_confirmation(confirmation_request, prompt_id, call_type)
659
-
660
- # If we got here, user chose "Allow Anyway"
661
- self.logger.info(f"User chose to 'allow anyway' a blocked {confirmation_request.operation_type} "
662
- f"operation for tool '{tool_name}' (event: {event_id})")
663
-
664
- await self._record_user_confirmation(event_id, is_request, response.user_decision, prompt_id, call_type)
665
- return
666
-
667
- except UserConfirmationError as e:
668
- # User chose to block or dialog failed
669
- self.logger.warning(f"User blocking confirmation failed: {e}")
670
- await self._record_user_confirmation(event_id, is_request, UserDecision.BLOCK, prompt_id, call_type)
671
- reasons = "; ".join(policy_reasons)
672
- raise error_class("Security Violation. User blocked the operation")
673
-
674
- elif decision_type == "required_explicit_user_confirmation":
675
- policy_reasons = decision.get("reasons", ["Security policy requires confirmation"])
676
- severity = decision.get("severity", "unknown")
677
- call_type = decision.get("call_type")
678
-
679
- try:
680
- confirmation_request = ConfirmationRequest(
681
- is_request=is_request,
682
- tool_name=tool_name,
683
- policy_reasons=policy_reasons,
684
- content_data=content_data,
685
- severity=severity,
686
- event_id=event_id,
687
- operation_type=operation_type,
688
- server_name=self.wrapped_server_name,
689
- timeout_seconds=60
690
- )
691
-
692
- # only show YES_ALWAYS if call_type exists
693
- options = DialogOptions(
694
- show_always_allow=(call_type is not None),
695
- show_always_block=False
696
- )
697
-
698
- response = UserConfirmationDialog(
699
- self.logger, self.audit_logger
700
- ).request_confirmation(confirmation_request, prompt_id, call_type, options)
701
-
702
- # If we got here, user approved the operation
703
- self.logger.info(f"User {response.user_decision.value} {confirmation_request.operation_type} "
704
- f"operation for tool '{tool_name}' (event: {event_id})")
705
-
706
- await self._record_user_confirmation(event_id, is_request, response.user_decision, prompt_id, call_type)
707
- return
708
-
709
- except UserConfirmationError as e:
710
- # User denied confirmation or dialog failed
711
- self.logger.warning(f"User confirmation failed: {e}")
712
- await self._record_user_confirmation(event_id, is_request, UserDecision.BLOCK, prompt_id, call_type)
713
- raise error_class("Security Violation. User blocked the operation")
714
-
715
- elif decision_type == "need_more_info":
716
- stage_title = 'CLIENT REQUEST' if is_request else 'TOOL RESPONSE'
717
-
718
- # Create an actionable error message for the AI agent
719
- reasons = decision.get("reasons", [])
720
- need_fields = decision.get("need_fields", [])
721
-
722
- error_parts = [
723
- f"SECURITY POLICY NEEDS MORE INFORMATION FOR REVIEWING {stage_title}:",
724
- '\n'.join(reasons),
725
- '' # newline
726
- ]
727
-
728
- if need_fields:
729
- # Convert server field names to wrapper field names for the AI agent
730
- wrapper_field_mapping = {
731
- "context.agent.intent": "__wrapper_modelIntent",
732
- "context.agent.plan": "__wrapper_modelPlan",
733
- "context.agent.expectedOutputs": "__wrapper_modelExpectedOutputs",
734
- "context.agent.user_prompt": "__wrapper_userPrompt",
735
- "context.agent.user_prompt_id": "__wrapper_userPromptId",
736
- "context.agent.context_summary": "__wrapper_contextSummary",
737
- "context.workspace.current_files": "__wrapper_currentFiles",
738
- }
739
-
740
- missing_wrapper_fields = []
741
- for field in need_fields:
742
- wrapper_field = wrapper_field_mapping.get(field, field)
743
- missing_wrapper_fields.append(wrapper_field)
744
-
745
- if missing_wrapper_fields:
746
- error_parts.append("AFFECTED FIELDS:")
747
- error_parts.extend(missing_wrapper_fields)
748
- else:
749
- error_parts.append("MISSING INFORMATION:")
750
- error_parts.extend(need_fields)
751
-
752
-
753
- error_parts.append("\nMANDATORY ACTIONS:")
754
- error_parts.append("1. Add/Edit ALL affected fields according to the required information")
755
- error_parts.append("2. Retry the tool call")
756
-
757
- actionable_message = "\n".join(error_parts)
758
- raise error_class(actionable_message)
wrapper/server.py CHANGED
@@ -6,10 +6,11 @@ Implements transparent 1:1 MCP proxying with security middleware
6
6
  import logging
7
7
 
8
8
  from fastmcp.server.middleware.logging import StructuredLoggingMiddleware
9
- from fastmcp.server.proxy import ProxyClient, default_proxy_roots_handler, FastMCPProxy
9
+ from fastmcp.server.proxy import ProxyClient, default_proxy_roots_handler, FastMCPProxy, StatefulProxyClient
10
10
 
11
11
  from modules.logs.audit_trail import AuditTrailLogger
12
12
  from modules.logs.logger import MCPLogger
13
+ from modules.utils.json import safe_json_dumps
13
14
  from .__version__ import __version__
14
15
  from .middleware import SecurityMiddleware
15
16
 
@@ -42,7 +43,7 @@ def create_wrapper_server(wrapper_server_name: str,
42
43
  logger=logger,
43
44
  audit_logger=audit_logger
44
45
  )
45
-
46
+
46
47
  # Log MCPower startup to audit trail
47
48
  audit_logger.log_event("mcpower_start", {
48
49
  "wrapper_version": __version__,
@@ -51,16 +52,23 @@ def create_wrapper_server(wrapper_server_name: str,
51
52
  })
52
53
 
53
54
  # Create FastMCP server as proxy with our security-aware ProxyClient
55
+ # Use StatefulProxyClient for remote servers (mcp-remote or url-based transports)
56
+ config_str = safe_json_dumps(wrapped_server_configs)
57
+ is_remote = '"@mcpower/mcp-remote",' in config_str or '"url":' in config_str
58
+ backend_class = StatefulProxyClient if is_remote else ProxyClient
59
+ backend = backend_class(
60
+ wrapped_server_configs,
61
+ name=wrapper_server_name,
62
+ roots=default_proxy_roots_handler, # Use default for filesystem roots
63
+ sampling_handler=security_middleware.secure_sampling_handler,
64
+ elicitation_handler=security_middleware.secure_elicitation_handler,
65
+ log_handler=security_middleware.secure_log_handler,
66
+ progress_handler=security_middleware.secure_progress_handler,
67
+ )
68
+
54
69
  def client_factory():
55
- return ProxyClient(
56
- wrapped_server_configs,
57
- name=wrapper_server_name,
58
- roots=default_proxy_roots_handler, # Use default for filesystem roots
59
- sampling_handler=security_middleware.secure_sampling_handler,
60
- elicitation_handler=security_middleware.secure_elicitation_handler,
61
- log_handler=security_middleware.secure_log_handler,
62
- progress_handler=security_middleware.secure_progress_handler,
63
- )
70
+ # we must return the same instance, otherwise StatefulProxyClient doesn't play nice with mcp-remote
71
+ return backend
64
72
 
65
73
  server = FastMCPProxy(client_factory=client_factory, name=wrapper_server_name, version=__version__)
66
74