mcpower-proxy 0.0.67__py3-none-any.whl → 0.0.77__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.
- ide_tools/__init__.py +12 -0
- ide_tools/common/__init__.py +5 -0
- ide_tools/common/hooks/__init__.py +5 -0
- ide_tools/common/hooks/init.py +129 -0
- ide_tools/common/hooks/output.py +63 -0
- ide_tools/common/hooks/prompt_submit.py +136 -0
- ide_tools/common/hooks/read_file.py +170 -0
- ide_tools/common/hooks/shell_execution.py +257 -0
- ide_tools/common/hooks/shell_parser_bashlex.py +394 -0
- ide_tools/common/hooks/types.py +34 -0
- ide_tools/common/hooks/utils.py +286 -0
- ide_tools/cursor/__init__.py +11 -0
- ide_tools/cursor/constants.py +58 -0
- ide_tools/cursor/format.py +35 -0
- ide_tools/cursor/router.py +101 -0
- ide_tools/router.py +48 -0
- main.py +11 -4
- {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.77.dist-info}/METADATA +4 -3
- mcpower_proxy-0.0.77.dist-info/RECORD +62 -0
- {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.77.dist-info}/top_level.txt +1 -0
- modules/apis/security_policy.py +11 -6
- modules/decision_handler.py +219 -0
- modules/logs/audit_trail.py +20 -18
- modules/logs/logger.py +14 -18
- modules/redaction/gitleaks_rules.py +1 -1
- modules/redaction/pii_rules.py +0 -48
- modules/redaction/redactor.py +112 -107
- modules/ui/__init__.py +1 -1
- modules/ui/confirmation.py +0 -1
- modules/utils/cli.py +36 -6
- modules/utils/ids.py +50 -7
- modules/utils/json.py +3 -3
- modules/utils/platform.py +23 -0
- modules/utils/string.py +17 -0
- wrapper/__version__.py +1 -1
- wrapper/middleware.py +136 -221
- wrapper/server.py +19 -11
- mcpower_proxy-0.0.67.dist-info/RECORD +0 -43
- {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.77.dist-info}/WHEEL +0 -0
- {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.77.dist-info}/entry_points.txt +0 -0
- {mcpower_proxy-0.0.67.dist-info → mcpower_proxy-0.0.77.dist-info}/licenses/LICENSE +0 -0
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,25 @@ 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
|
|
31
|
+
from modules.utils.platform import get_client_os
|
|
32
|
+
from modules.utils.string import truncate_at
|
|
25
33
|
from wrapper.schema import merge_input_schema_with_existing
|
|
26
34
|
|
|
27
|
-
from mcpower_shared.mcp_types import (create_policy_request, create_policy_response, AgentContext, EnvironmentContext,
|
|
28
|
-
InitRequest,
|
|
29
|
-
ServerRef, ToolRef, UserConfirmation)
|
|
30
|
-
|
|
31
35
|
|
|
32
36
|
class MockContext:
|
|
33
37
|
"""Mock context for internal operations"""
|
|
@@ -53,10 +57,7 @@ class MockContext:
|
|
|
53
57
|
class SecurityMiddleware(Middleware):
|
|
54
58
|
"""FastMCP middleware for security policy enforcement"""
|
|
55
59
|
|
|
56
|
-
app_id: str = ""
|
|
57
60
|
_TOOLS_INIT_DEBOUNCE_SECONDS = 60
|
|
58
|
-
_last_tools_init_time: Optional[float] = None
|
|
59
|
-
_last_workspace_root: Optional[str] = None
|
|
60
61
|
|
|
61
62
|
def __init__(self,
|
|
62
63
|
wrapped_server_configs: dict,
|
|
@@ -72,6 +73,9 @@ class SecurityMiddleware(Middleware):
|
|
|
72
73
|
self.audit_logger = audit_logger
|
|
73
74
|
self.app_id = ""
|
|
74
75
|
self._last_workspace_root = None
|
|
76
|
+
self._last_tools_init_time: Optional[float] = None
|
|
77
|
+
self._tools_list_in_progress: Optional[asyncio.Task] = None
|
|
78
|
+
self._tools_list_lock = asyncio.Lock()
|
|
75
79
|
|
|
76
80
|
self.wrapped_server_name, self.wrapped_server_transport = (
|
|
77
81
|
extract_wrapped_server_info(self.wrapper_server_name, self.logger, self.wrapped_server_configs)
|
|
@@ -88,17 +92,36 @@ class SecurityMiddleware(Middleware):
|
|
|
88
92
|
async def on_message(self, context: MiddlewareContext, call_next: CallNext) -> Any:
|
|
89
93
|
self.logger.info(f"on_message: {redact(safe_json_dumps(context))}")
|
|
90
94
|
|
|
91
|
-
#
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
self.
|
|
95
|
+
# Skip workspace check for `initialize` calls to avoid premature app_uid changes.
|
|
96
|
+
# The `initialize` request doesn't contain workspace data, so checking it would
|
|
97
|
+
# cause unnecessary audit log flushes before the actual workspace init arrives.
|
|
98
|
+
if context.method != "initialize":
|
|
99
|
+
# Check workspace roots and re-initialize app_uid if workspace changed
|
|
100
|
+
workspace_roots = await self._extract_workspace_roots(context)
|
|
101
|
+
current_workspace_root = get_project_mcpower_dir(workspace_roots[0] if workspace_roots else None)
|
|
102
|
+
if current_workspace_root != self._last_workspace_root:
|
|
103
|
+
self.logger.debug(
|
|
104
|
+
f"Workspace root changed from {self._last_workspace_root} to {current_workspace_root}")
|
|
105
|
+
self._last_workspace_root = current_workspace_root
|
|
106
|
+
self.app_id = read_app_uid(logger=self.logger, project_folder_path=current_workspace_root)
|
|
107
|
+
self.audit_logger.set_app_uid(self.app_id)
|
|
99
108
|
|
|
100
109
|
operation_type = "message"
|
|
101
|
-
|
|
110
|
+
|
|
111
|
+
async def call_next_wrapper(ctx):
|
|
112
|
+
try:
|
|
113
|
+
return await call_next(ctx)
|
|
114
|
+
except HTTPStatusError as e:
|
|
115
|
+
if e.response.status_code in (401, 403):
|
|
116
|
+
raise FastMCPError(ErrorData(
|
|
117
|
+
code=-32000,
|
|
118
|
+
message="Authentication required",
|
|
119
|
+
data={
|
|
120
|
+
"type": "unauthorized",
|
|
121
|
+
"details": "Please provide valid authentication credentials"
|
|
122
|
+
}
|
|
123
|
+
))
|
|
124
|
+
raise e
|
|
102
125
|
|
|
103
126
|
match context.type:
|
|
104
127
|
case "request":
|
|
@@ -115,13 +138,13 @@ class SecurityMiddleware(Middleware):
|
|
|
115
138
|
operation_type = "prompt"
|
|
116
139
|
case "tools/list":
|
|
117
140
|
# Special handling for tools/list - call /init instead of normal inspection
|
|
118
|
-
return await self._handle_tools_list(context,
|
|
141
|
+
return await self._handle_tools_list(context, call_next_wrapper)
|
|
119
142
|
case "initialize" | "resources/list" | "resources/templates/list" | "prompts/list":
|
|
120
|
-
return await
|
|
143
|
+
return await call_next_wrapper(context)
|
|
121
144
|
|
|
122
145
|
return await self._handle_operation(
|
|
123
146
|
context=context,
|
|
124
|
-
call_next=
|
|
147
|
+
call_next=call_next_wrapper,
|
|
125
148
|
error_class=FastMCPError,
|
|
126
149
|
operation_type=operation_type
|
|
127
150
|
)
|
|
@@ -152,7 +175,7 @@ class SecurityMiddleware(Middleware):
|
|
|
152
175
|
async def secure_elicitation_handler(self, message, response_type, params, context):
|
|
153
176
|
# FIXME: elicitation message, params, and context should be redacted before logging
|
|
154
177
|
self.logger.info(f"secure_elicitation_handler: "
|
|
155
|
-
f"message={str(message)
|
|
178
|
+
f"message={truncate_at(str(message), 100)}, response_type={response_type},"
|
|
156
179
|
f"params={params}, context={context}")
|
|
157
180
|
|
|
158
181
|
mock_context = MockContext(
|
|
@@ -181,15 +204,15 @@ class SecurityMiddleware(Middleware):
|
|
|
181
204
|
return await ProxyClient.default_progress_handler(progress, total, message)
|
|
182
205
|
|
|
183
206
|
async def secure_log_handler(self, log_message):
|
|
184
|
-
# FIXME: log_message should be redacted before logging,
|
|
185
|
-
self.logger.info(f"secure_log_handler: {str(log_message)
|
|
207
|
+
# FIXME: log_message should be redacted before logging,
|
|
208
|
+
self.logger.info(f"secure_log_handler: {truncate_at(str(log_message), 100)}")
|
|
186
209
|
# FIXME: log_message should be reviewed with policy before forwarding
|
|
187
|
-
|
|
210
|
+
|
|
188
211
|
# Handle case where log_message.data is a string instead of dict
|
|
189
212
|
# The default_log_handler expects data to be a dict with 'msg' and 'extra' keys
|
|
190
213
|
if hasattr(log_message, 'data') and isinstance(log_message.data, str):
|
|
191
214
|
log_message = safe_copy(log_message, {'data': {'msg': log_message.data, 'extra': None}})
|
|
192
|
-
|
|
215
|
+
|
|
193
216
|
return await ProxyClient.default_log_handler(log_message)
|
|
194
217
|
|
|
195
218
|
async def _handle_operation(self, context: MiddlewareContext, call_next, error_class, operation_type: str):
|
|
@@ -222,19 +245,28 @@ class SecurityMiddleware(Middleware):
|
|
|
222
245
|
prompt_id=prompt_id
|
|
223
246
|
)
|
|
224
247
|
on_inspect_request_duration = time.time() - on_inspect_request_start_time
|
|
225
|
-
self.logger.
|
|
248
|
+
self.logger.debug(
|
|
249
|
+
f"PROFILE: {operation_type} id: {event_id} inspect_request duration: {on_inspect_request_duration:.2f} seconds")
|
|
226
250
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
251
|
+
try:
|
|
252
|
+
await DecisionHandler(
|
|
253
|
+
logger=self.logger,
|
|
254
|
+
audit_logger=self.audit_logger,
|
|
255
|
+
session_id=self.session_id,
|
|
256
|
+
app_id=self.app_id
|
|
257
|
+
).enforce_decision(
|
|
258
|
+
decision=request_decision,
|
|
259
|
+
is_request=True,
|
|
260
|
+
event_id=event_id,
|
|
261
|
+
tool_name=tool_name,
|
|
262
|
+
content_data=tool_args,
|
|
263
|
+
operation_type=operation_type,
|
|
264
|
+
prompt_id=prompt_id,
|
|
265
|
+
server_name=self.wrapped_server_name,
|
|
266
|
+
error_message_prefix=f"{operation_type.title()} request blocked by security policy"
|
|
267
|
+
)
|
|
268
|
+
except DecisionEnforcementError as e:
|
|
269
|
+
raise error_class(str(e))
|
|
238
270
|
|
|
239
271
|
self.audit_logger.log_event(
|
|
240
272
|
"agent_request_forwarded",
|
|
@@ -251,7 +283,8 @@ class SecurityMiddleware(Middleware):
|
|
|
251
283
|
# Call wrapped MCP with cleaned context (e.g., no wrapper args)
|
|
252
284
|
result = await call_next(cleaned_context)
|
|
253
285
|
on_call_next_duration = time.time() - on_call_next_start_time
|
|
254
|
-
self.logger.
|
|
286
|
+
self.logger.debug(
|
|
287
|
+
f"PROFILE: {operation_type} id: {event_id} call_next duration: {on_call_next_duration:.2f} seconds")
|
|
255
288
|
|
|
256
289
|
response_content = self._extract_response_content(result)
|
|
257
290
|
|
|
@@ -276,19 +309,28 @@ class SecurityMiddleware(Middleware):
|
|
|
276
309
|
prompt_id=prompt_id
|
|
277
310
|
)
|
|
278
311
|
on_inspect_response_duration = time.time() - on_inspect_response_start_time
|
|
279
|
-
self.logger.
|
|
312
|
+
self.logger.debug(
|
|
313
|
+
f"PROFILE: {operation_type} id: {event_id} inspect_response duration: {on_inspect_response_duration:.2f} seconds")
|
|
280
314
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
315
|
+
try:
|
|
316
|
+
await DecisionHandler(
|
|
317
|
+
logger=self.logger,
|
|
318
|
+
audit_logger=self.audit_logger,
|
|
319
|
+
session_id=self.session_id,
|
|
320
|
+
app_id=self.app_id
|
|
321
|
+
).enforce_decision(
|
|
322
|
+
decision=response_decision,
|
|
323
|
+
is_request=False,
|
|
324
|
+
event_id=event_id,
|
|
325
|
+
tool_name=tool_name,
|
|
326
|
+
content_data=response_content,
|
|
327
|
+
operation_type=operation_type,
|
|
328
|
+
prompt_id=prompt_id,
|
|
329
|
+
server_name=self.wrapped_server_name,
|
|
330
|
+
error_message_prefix=f"{operation_type.title()} response blocked by security policy"
|
|
331
|
+
)
|
|
332
|
+
except DecisionEnforcementError as e:
|
|
333
|
+
raise error_class(str(e))
|
|
292
334
|
|
|
293
335
|
self.audit_logger.log_event(
|
|
294
336
|
"mcp_response_forwarded",
|
|
@@ -301,15 +343,30 @@ class SecurityMiddleware(Middleware):
|
|
|
301
343
|
prompt_id=prompt_id
|
|
302
344
|
)
|
|
303
345
|
on_handle_operation_duration = time.time() - on_handle_operation_start_time
|
|
304
|
-
self.logger.
|
|
346
|
+
self.logger.debug(
|
|
347
|
+
f"PROFILE: {operation_type} id: {event_id} duration: {on_handle_operation_duration:.2f} seconds")
|
|
305
348
|
return result
|
|
306
349
|
|
|
307
350
|
async def _handle_tools_list(self, context: MiddlewareContext, call_next: CallNext) -> Any:
|
|
308
|
-
"""Handle tools/list by calling /init API and modifying schemas"""
|
|
351
|
+
"""Handle tools/list by calling /init API and modifying schemas with deduplication"""
|
|
309
352
|
event_id = generate_event_id()
|
|
310
353
|
on_handle_tools_list_start_time = time.time()
|
|
311
|
-
|
|
312
|
-
|
|
354
|
+
|
|
355
|
+
async with self._tools_list_lock:
|
|
356
|
+
if not self._tools_list_in_progress or self._tools_list_in_progress.done():
|
|
357
|
+
self._tools_list_in_progress = asyncio.create_task(call_next(context))
|
|
358
|
+
shared_task = self._tools_list_in_progress
|
|
359
|
+
|
|
360
|
+
try:
|
|
361
|
+
result = await shared_task
|
|
362
|
+
except Exception as e:
|
|
363
|
+
async with self._tools_list_lock:
|
|
364
|
+
if self._tools_list_in_progress is shared_task:
|
|
365
|
+
self._tools_list_in_progress = None
|
|
366
|
+
raise
|
|
367
|
+
self.logger.debug(
|
|
368
|
+
f"PROFILE: tools/list call_next duration: {time.time() - on_handle_tools_list_start_time:.2f} seconds id: {event_id}")
|
|
369
|
+
|
|
313
370
|
tools_list = None
|
|
314
371
|
if isinstance(result, list):
|
|
315
372
|
tools_list = result
|
|
@@ -339,11 +396,13 @@ class SecurityMiddleware(Middleware):
|
|
|
339
396
|
enhanced_result = result
|
|
340
397
|
|
|
341
398
|
on_handle_tools_list_duration = time.time() - on_handle_tools_list_start_time
|
|
342
|
-
self.logger.
|
|
399
|
+
self.logger.debug(
|
|
400
|
+
f"PROFILE: tools/list enhanced_result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
|
|
343
401
|
return enhanced_result
|
|
344
402
|
|
|
345
403
|
on_handle_tools_list_duration = time.time() - on_handle_tools_list_start_time
|
|
346
|
-
self.logger.
|
|
404
|
+
self.logger.debug(
|
|
405
|
+
f"PROFILE: tools/list result duration: {on_handle_tools_list_duration:.2f} seconds id: {event_id}")
|
|
347
406
|
|
|
348
407
|
return result
|
|
349
408
|
|
|
@@ -482,12 +541,12 @@ class SecurityMiddleware(Middleware):
|
|
|
482
541
|
file_path_prefix = 'file://'
|
|
483
542
|
if uri.startswith(file_path_prefix):
|
|
484
543
|
path = urllib.parse.unquote(uri[len(file_path_prefix):])
|
|
485
|
-
|
|
544
|
+
|
|
486
545
|
# Windows fix: remove leading slash before drive letter
|
|
487
546
|
# file:///C:/path becomes /C:/path, should be C:/path
|
|
488
547
|
if sys.platform == 'win32' and len(path) >= 3 and path[0] == '/' and path[2] == ':':
|
|
489
548
|
path = path[1:]
|
|
490
|
-
|
|
549
|
+
|
|
491
550
|
try:
|
|
492
551
|
resolved_path = str(Path(path).resolve())
|
|
493
552
|
workspace_roots.append(resolved_path)
|
|
@@ -511,9 +570,13 @@ class SecurityMiddleware(Middleware):
|
|
|
511
570
|
base_dict = await self._build_baseline_policy_dict(event_id, context, wrapper_args, tool_args)
|
|
512
571
|
policy_request = create_policy_request(
|
|
513
572
|
event_id=event_id,
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
573
|
+
server=ServerRef(
|
|
574
|
+
name=base_dict["server"]["name"],
|
|
575
|
+
transport=base_dict["server"]["transport"]
|
|
576
|
+
),
|
|
577
|
+
tool=ToolRef(
|
|
578
|
+
name=base_dict["tool"]["name"] or base_dict["tool"]["method"]
|
|
579
|
+
),
|
|
517
580
|
agent_context=base_dict["agent_context"],
|
|
518
581
|
env_context=base_dict["environment_context"],
|
|
519
582
|
arguments=tool_args,
|
|
@@ -539,9 +602,13 @@ class SecurityMiddleware(Middleware):
|
|
|
539
602
|
base_dict = await self._build_baseline_policy_dict(event_id, context, wrapper_args, tool_args)
|
|
540
603
|
policy_response = create_policy_response(
|
|
541
604
|
event_id=event_id,
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
605
|
+
server=ServerRef(
|
|
606
|
+
name=base_dict["server"]["name"],
|
|
607
|
+
transport=base_dict["server"]["transport"]
|
|
608
|
+
),
|
|
609
|
+
tool=ToolRef(
|
|
610
|
+
name=base_dict["tool"]["name"] or base_dict["tool"]["method"]
|
|
611
|
+
),
|
|
545
612
|
response_content=safe_json_dumps(result),
|
|
546
613
|
agent_context=base_dict["agent_context"],
|
|
547
614
|
env_context=base_dict["environment_context"],
|
|
@@ -589,32 +656,12 @@ class SecurityMiddleware(Middleware):
|
|
|
589
656
|
"current_files": wrapper_args.get('__wrapper_currentFiles')
|
|
590
657
|
},
|
|
591
658
|
client=self.wrapper_server_name,
|
|
592
|
-
client_version=self.wrapper_server_version
|
|
659
|
+
client_version=self.wrapper_server_version,
|
|
660
|
+
client_os=get_client_os(),
|
|
661
|
+
app_id=self.app_id,
|
|
593
662
|
)
|
|
594
663
|
}
|
|
595
664
|
|
|
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
665
|
@staticmethod
|
|
619
666
|
def _create_security_api_failure_decision(error: Exception) -> Dict[str, Any]:
|
|
620
667
|
"""Create a standard failure decision when security API is unavailable/failing/unreachable"""
|
|
@@ -624,135 +671,3 @@ class SecurityMiddleware(Middleware):
|
|
|
624
671
|
"reasons": [f"Security API unavailable: {error}"],
|
|
625
672
|
"matched_rules": ["security_api.error"]
|
|
626
673
|
}
|
|
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
|
|
56
|
-
|
|
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
|
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
main.py,sha256=4BnzO7q9Atpzgr-_NTc1loRnrRY0m5OxeG9biI-C0es,3707
|
|
2
|
-
mcpower_proxy-0.0.67.dist-info/licenses/LICENSE,sha256=U6WUzdnBrbmVxBmY75ikW-KtinwYnowZ7yNb5hECrvY,11337
|
|
3
|
-
modules/__init__.py,sha256=mJglXQwSRhU-bBv4LXgfu7NfGN9K4BeQWMPApen5rAA,30
|
|
4
|
-
modules/apis/__init__.py,sha256=Y5WZpKJzHpnRJebk0F80ZRTjR2PpA2LlYLgqI3XlmRo,15
|
|
5
|
-
modules/apis/security_policy.py,sha256=AZDHTuOf99WhhzNw9AwC-0KACx1-ZjtQx-Ve3gAKYPM,15000
|
|
6
|
-
modules/logs/__init__.py,sha256=dpboUQjuO02z8K-liCbm2DYkCa-CB_ZDV9WSSjNm7Fs,15
|
|
7
|
-
modules/logs/audit_trail.py,sha256=r8aIjaW-jBXXhSwdafzgOn0AvvdTZG8UPnkI0GmbJnA,6199
|
|
8
|
-
modules/logs/logger.py,sha256=dfYRLnABZB07SBfoYV4DsD8-ZCpzEeoewFCBGHyqo9k,4171
|
|
9
|
-
modules/redaction/__init__.py,sha256=e5NTmp-zonUdzzscih-w_WQ-X8Nvb8CE8b_d6SbrwWg,316
|
|
10
|
-
modules/redaction/constants.py,sha256=xbDSX8n72FuJu6JJ_sbBE0f5OcWuwEwHxBZuK9Xz-TI,1213
|
|
11
|
-
modules/redaction/gitleaks_rules.py,sha256=8dRb4g5OQaHAjx8vpMbxwu06CdDE39aqw9eqLiCDcqY,46411
|
|
12
|
-
modules/redaction/pii_rules.py,sha256=-JhjcCjH5NFeOfQGzTFNdx_-s_0i6tZ-XFxydtkByD0,10019
|
|
13
|
-
modules/redaction/redactor.py,sha256=jxb5itJ_xDo43XG28tXbAyMqhTmJXzAhStzAhlWvrOI,23905
|
|
14
|
-
modules/ui/__init__.py,sha256=-fZ_Bna6XnXeC7xB9loQ-7Qv2uK0NhSr-qoyRx2f8ZU,33
|
|
15
|
-
modules/ui/classes.py,sha256=ZvVRdzO_hD4WnpS3_eVa0WCyaooXiYVpHLzQkzBaH6M,1777
|
|
16
|
-
modules/ui/confirmation.py,sha256=VfVPFkttO4Mstja6dA85tqulyvdXyo8DyHzl0uiPWKU,7741
|
|
17
|
-
modules/ui/simple_dialog.py,sha256=PZW3WSPUVtnGXx-Kkg6hTQTr5NvpTQVhgHyro1z_3aY,3900
|
|
18
|
-
modules/ui/xdialog/__init__.py,sha256=KYQKVF6pGrwc99swRBxtWVXM__j9kVX_r6KikzbCOM4,9359
|
|
19
|
-
modules/ui/xdialog/constants.py,sha256=UjtqzT_O3OHUXJOyeTGroOUnaxdVyYukf7kK6vj1rog,200
|
|
20
|
-
modules/ui/xdialog/mac_dialogs.py,sha256=6r3hkJzJJdHSt-aH1Hy4lZ1MEuZK4Kc5D_YiWglKHAA,6129
|
|
21
|
-
modules/ui/xdialog/tk_dialogs.py,sha256=isxxN_mvZUFUQu8RD1J-GC7UMH2spqR3v_domgRbczQ,2403
|
|
22
|
-
modules/ui/xdialog/windows_custom_dialog.py,sha256=tcdo35d4ZoBydAj-4yzzgW2luw97-Sdjsr3X_3-a7jM,14849
|
|
23
|
-
modules/ui/xdialog/windows_dialogs.py,sha256=ohOoK4ciyv2s4BC9r7-zvGL6mECM-RCPTVOmzDnD6VQ,7626
|
|
24
|
-
modules/ui/xdialog/windows_structs.py,sha256=xzG44OGT5hBFnimJgOLXZBhmpQ_9CFxjtz-QNjP-VCw,8698
|
|
25
|
-
modules/ui/xdialog/yad_dialogs.py,sha256=EiajZVJg-xDwYymz1fyQwLtT5DzbJR3e8plMEnOgcpo,6933
|
|
26
|
-
modules/ui/xdialog/zenity_dialogs.py,sha256=wE71I_Ovf0sjhxHVNocbrhhDd8Y8X8loLETp8TMGMPQ,4512
|
|
27
|
-
modules/utils/__init__.py,sha256=Ptwu1epT_dW6EHjGkzGHAB-MbrrmYAlcPXGGcr4PvwE,20
|
|
28
|
-
modules/utils/cli.py,sha256=qYgf7TsWKjwPsCItbDYzNZCih2vfGAbAl2MIem320_Y,1517
|
|
29
|
-
modules/utils/config.py,sha256=YuGrIYfBsOYABWjFoZosObPz-R7Wdul16RnDed_glYI,6654
|
|
30
|
-
modules/utils/copy.py,sha256=9OJIqWn8PxPZXr3DTt_01jp0YgmPimckab1969WFh0c,1075
|
|
31
|
-
modules/utils/ids.py,sha256=eYN31WDlfCyRSsdNu9F_hr_duuEpYEUJ5-ZMqo1fiAQ,4701
|
|
32
|
-
modules/utils/json.py,sha256=8GA2akQsufXIn9HIP4SkFGFShzngexEBzejXi4B-Mfg,4031
|
|
33
|
-
modules/utils/mcp_configs.py,sha256=DZaujZnF9LlPDJHzyepH7fWSt1GTr-FEmShPCqnZ5aI,1829
|
|
34
|
-
wrapper/__init__.py,sha256=OJUsuWSoN1JqIHq4bSrzuL7ufcYJcwAmYCrJjLH44LM,22
|
|
35
|
-
wrapper/__version__.py,sha256=GNWaj29A6zHFh2lJ4QK-JjsO060CwlOyWjwVZ7HXZ1E,82
|
|
36
|
-
wrapper/middleware.py,sha256=_-dh_IxZ_02hyA0pGPdJ4UbdWfjFCouT6XyoFgYL_vs,35095
|
|
37
|
-
wrapper/schema.py,sha256=O-CtKI9eJ4eEnqeUXPCrK7QJAFJrdp_cFbmMyg452Aw,7952
|
|
38
|
-
wrapper/server.py,sha256=uVtxELALRrQNd-VrPWyLQPiEzxOpG-oCU7bItAeSjYU,2981
|
|
39
|
-
mcpower_proxy-0.0.67.dist-info/METADATA,sha256=u-474KwpvdcwykDYKJfXlt4FedpWLQWvKfe1XuYIAuI,15669
|
|
40
|
-
mcpower_proxy-0.0.67.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
41
|
-
mcpower_proxy-0.0.67.dist-info/entry_points.txt,sha256=0smL8dxE7ERNz6XEggNaUC3QzKp8mD-v4q5nVEo0MXE,48
|
|
42
|
-
mcpower_proxy-0.0.67.dist-info/top_level.txt,sha256=FLbRkTTggoMB-kq14IH4ZUbNGMGtbxtmiWw0QykRlkU,21
|
|
43
|
-
mcpower_proxy-0.0.67.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|