revertx 0.2.0__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.
revertx/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """RevertX: Deterministic Execution Safety, Policy Enforcement, and Recovery Layer."""
2
+
3
+ from revertx.adapters.sdk import RevertXClient, protect
4
+
5
+ __version__ = "0.2.0"
6
+
7
+ __all__ = ["RevertXClient", "__version__", "protect"]
@@ -0,0 +1 @@
1
+ """Thin adapters wrapping RevertX core (MCP proxy, Python SDK, HTTP gateway)."""
@@ -0,0 +1,218 @@
1
+ """FastAPI HTTP reverse proxy adapter delegating REST writes to RevertXEngine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
7
+ from contextlib import asynccontextmanager
8
+ from typing import Any
9
+ from uuid import uuid4
10
+
11
+ import httpx
12
+ from fastapi import FastAPI, HTTPException, Request, Response
13
+ from fastapi.responses import JSONResponse
14
+
15
+ from revertx.core.approvals import process_telegram_webhook_update
16
+ from revertx.core.auth import AuthPolicyError, RouteAuthorizer
17
+ from revertx.core.engine import RevertXEngine
18
+ from revertx.core.exceptions import (
19
+ ApprovalTimeoutError,
20
+ PolicyViolationError,
21
+ RevertXError,
22
+ RollbackError,
23
+ SnapshotCaptureError,
24
+ )
25
+ from revertx.core.http_proxy import HttpRouteRule, match_http_route
26
+ from revertx.core.ledger import LedgerStore
27
+ from revertx.core.security import (
28
+ reject_spoofed_proxy_headers,
29
+ validate_outbound_url,
30
+ validate_safe_http_path,
31
+ validate_tool_arguments,
32
+ )
33
+
34
+ logger = logging.getLogger("revertx.http_gateway")
35
+
36
+
37
+ def create_http_gateway_app(
38
+ *,
39
+ ledger: LedgerStore,
40
+ engine: RevertXEngine,
41
+ upstream_client: httpx.AsyncClient,
42
+ routes: Sequence[HttpRouteRule],
43
+ webhook_secret: str | None = None,
44
+ allowed_telegram_users: Sequence[str] = (),
45
+ expected_telegram_chat_id: str | None = None,
46
+ bot_token: str | None = None,
47
+ telegram_http_client: httpx.AsyncClient | None = None,
48
+ api_token: str | None = None,
49
+ allowed_ips: Sequence[str] = (),
50
+ trusted_proxies: Sequence[str] = (),
51
+ allow_local_upstream: bool = False,
52
+ owns_resources: bool = False,
53
+ ) -> FastAPI:
54
+ """Create a FastAPI reverse proxy enforcing auth, SSRF checks, and RevertXEngine."""
55
+ authorizer = RouteAuthorizer(
56
+ api_token=api_token,
57
+ allowed_ips=allowed_ips,
58
+ trusted_proxies=trusted_proxies,
59
+ )
60
+
61
+ @asynccontextmanager
62
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
63
+ await ledger.init_schema()
64
+ await engine.recover_stranded_compensations()
65
+ try:
66
+ yield
67
+ finally:
68
+ if owns_resources:
69
+ await upstream_client.aclose()
70
+ await ledger.close()
71
+
72
+ app = FastAPI(title="RevertX HTTP Safety Gateway", lifespan=lifespan)
73
+
74
+ @app.middleware("http")
75
+ async def _enforce_auth(
76
+ request: Request,
77
+ call_next: Callable[[Request], Awaitable[Response]],
78
+ ) -> Response:
79
+ peer_ip = request.client.host if request.client else None
80
+ try:
81
+ authorizer.authorize(
82
+ path=request.url.path,
83
+ client_ip=peer_ip,
84
+ authorization_header=request.headers.get("Authorization"),
85
+ x_forwarded_for=request.headers.get("X-Forwarded-For"),
86
+ forwarded=request.headers.get("Forwarded"),
87
+ )
88
+ reject_spoofed_proxy_headers(
89
+ dict(request.headers),
90
+ from_trusted_proxy=authorizer.is_trusted_proxy(peer_ip),
91
+ )
92
+ validate_safe_http_path(request.url.path)
93
+ except AuthPolicyError as exc:
94
+ logger.warning("Gateway auth rejected path=%s error=%s", request.url.path, exc)
95
+ return JSONResponse({"error": str(exc)}, status_code=exc.status_code)
96
+ except PolicyViolationError as exc:
97
+ logger.warning("Gateway security rejected path=%s error=%s", request.url.path, exc)
98
+ return JSONResponse({"error": str(exc)}, status_code=403)
99
+ return await call_next(request)
100
+
101
+ @app.get("/healthz")
102
+ async def healthz() -> dict[str, str]:
103
+ return {"status": "ok"}
104
+
105
+ @app.post("/rollback/{run_id}")
106
+ async def rollback_endpoint(run_id: str) -> JSONResponse:
107
+ report = await engine.rollback_run(run_id, raise_on_failure=False)
108
+ return JSONResponse(report.model_dump(mode="json"))
109
+
110
+ @app.post("/webhooks/telegram")
111
+ async def telegram_webhook(request: Request) -> JSONResponse:
112
+ payload: dict[str, Any] = await request.json()
113
+ try:
114
+ resolved = await process_telegram_webhook_update(
115
+ ledger,
116
+ payload,
117
+ secret_token_header=request.headers.get("X-Telegram-Bot-Api-Secret-Token"),
118
+ expected_secret_token=webhook_secret,
119
+ allowed_user_ids=allowed_telegram_users,
120
+ expected_chat_id=expected_telegram_chat_id,
121
+ bot_token=bot_token,
122
+ http_client=telegram_http_client,
123
+ )
124
+ except PolicyViolationError as exc:
125
+ logger.warning("Rejected Telegram webhook update: %s", exc)
126
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
127
+ except ApprovalTimeoutError as exc:
128
+ logger.info("Expired Telegram webhook update: %s", exc)
129
+ raise HTTPException(status_code=410, detail=str(exc)) from exc
130
+ dec = resolved.decision.value if resolved else "IGNORED"
131
+ return JSONResponse({"ok": True, "decision": dec})
132
+
133
+ @app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
134
+ async def proxy_request(request: Request, full_path: str) -> Response:
135
+ req_path = "/" + full_path.lstrip("/")
136
+ if request.method == "GET":
137
+ try:
138
+ validate_tool_arguments("http_get", dict(request.query_params))
139
+ resp = await upstream_client.get(
140
+ req_path,
141
+ params=dict(request.query_params),
142
+ timeout=15.0,
143
+ follow_redirects=False,
144
+ )
145
+ if resp.is_redirect and "location" in resp.headers:
146
+ validate_outbound_url(
147
+ resp.headers["location"], allow_private=allow_local_upstream
148
+ )
149
+ except PolicyViolationError as exc:
150
+ logger.warning("Gateway GET SSRF/input blocked path=%s: %s", req_path, exc)
151
+ return JSONResponse({"error": str(exc)}, status_code=403)
152
+ except httpx.HTTPError as exc:
153
+ logger.error("Gateway GET upstream error path=%s: %s", req_path, exc)
154
+ return JSONResponse({"error": str(exc), "type": "UpstreamError"}, status_code=502)
155
+ return Response(
156
+ content=resp.content,
157
+ status_code=resp.status_code,
158
+ media_type=resp.headers.get("content-type"),
159
+ )
160
+
161
+ matched, path_params = match_http_route(routes, request.method, req_path)
162
+ if matched is None:
163
+ return JSONResponse({"error": f"Unclassified route {request.method} {req_path}."}, 403)
164
+ raw_body = await request.body()
165
+ try:
166
+ body_data: dict[str, Any] = await request.json() if raw_body else {}
167
+ except ValueError:
168
+ return JSONResponse({"error": "Invalid JSON body."}, status_code=400)
169
+
170
+ run_id = request.headers.get("X-RevertX-Run-Id") or str(uuid4())
171
+
172
+ async def _forward(_tool: str, _args: dict[str, Any]) -> httpx.Response:
173
+ resp = await upstream_client.request(
174
+ request.method,
175
+ req_path,
176
+ json=body_data if raw_body else None,
177
+ timeout=15.0,
178
+ follow_redirects=False,
179
+ )
180
+ if resp.is_redirect and "location" in resp.headers:
181
+ validate_outbound_url(
182
+ resp.headers["location"], allow_private=allow_local_upstream
183
+ )
184
+ if resp.status_code >= 400:
185
+ raise httpx.HTTPStatusError(
186
+ f"HTTP {resp.status_code}", request=resp.request, response=resp
187
+ )
188
+ return resp
189
+
190
+ try:
191
+ step, up_resp = await engine.execute_tool(
192
+ run_id=run_id,
193
+ tool_name=matched.tool_name,
194
+ arguments={**body_data, **path_params},
195
+ executor=_forward,
196
+ agent_name="http-gateway-client",
197
+ parent_step_id=request.headers.get("X-RevertX-Parent-Step-Id"),
198
+ )
199
+ except RollbackError as exc:
200
+ logger.error("Gateway rollback error run_id=%s: %s", run_id, exc)
201
+ return JSONResponse({"error": str(exc), "type": "RollbackError"}, status_code=409)
202
+ except SnapshotCaptureError as exc:
203
+ logger.error("Gateway snapshot error run_id=%s: %s", run_id, exc)
204
+ return JSONResponse({"error": str(exc), "type": "SnapshotCaptureError"}, 502)
205
+ except RevertXError as exc:
206
+ logger.warning("Gateway policy block run_id=%s: %s", run_id, exc)
207
+ return JSONResponse({"error": str(exc), "type": type(exc).__name__}, status_code=403)
208
+ except httpx.HTTPError as exc:
209
+ logger.error("Gateway upstream error run_id=%s: %s", run_id, exc)
210
+ return JSONResponse({"error": str(exc), "type": "UpstreamError"}, status_code=502)
211
+ return Response(
212
+ content=up_resp.content,
213
+ status_code=up_resp.status_code,
214
+ media_type=up_resp.headers.get("content-type"),
215
+ headers={"X-RevertX-Run-Id": run_id, "X-RevertX-Step-Id": step.step_id},
216
+ )
217
+
218
+ return app
@@ -0,0 +1,133 @@
1
+ """Streamable HTTP hosting, Origin DNS-rebinding guard, and lifespan recovery for FastMCP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
7
+ from contextlib import asynccontextmanager
8
+ from typing import Any
9
+
10
+ import uvicorn
11
+ from fastmcp.server.providers.proxy import FastMCPProxy
12
+ from starlette.applications import Starlette
13
+ from starlette.middleware import Middleware as ASGIMiddleware
14
+ from starlette.middleware.base import BaseHTTPMiddleware
15
+ from starlette.requests import Request
16
+ from starlette.responses import JSONResponse, Response
17
+ from starlette.types import ASGIApp
18
+
19
+ from revertx.core.auth import AuthPolicyError, RouteAuthorizer
20
+ from revertx.core.engine import RevertXEngine
21
+ from revertx.core.security import is_trusted_origin, validate_http_bind_host
22
+
23
+ logger = logging.getLogger("revertx.mcp_http")
24
+
25
+
26
+ class StreamableHTTPOriginMiddleware(BaseHTTPMiddleware):
27
+ """Enforces Origin validation (DNS-rebinding guard) and optional auth on MCP HTTP."""
28
+
29
+ def __init__(
30
+ self,
31
+ app: ASGIApp,
32
+ *,
33
+ allowed_origins: Sequence[str] = (),
34
+ authorizer: RouteAuthorizer | None = None,
35
+ ) -> None:
36
+ super().__init__(app)
37
+ self._allowed_origins = tuple(allowed_origins)
38
+ self._authorizer = authorizer
39
+
40
+ async def dispatch(
41
+ self,
42
+ request: Request,
43
+ call_next: Callable[[Request], Awaitable[Response]],
44
+ ) -> Response:
45
+ """Reject untrusted Origin headers with 403 and enforce optional RouteAuthorizer."""
46
+ origin = request.headers.get("origin")
47
+ if not is_trusted_origin(origin, allowed_origins=self._allowed_origins):
48
+ logger.warning("Rejected untrusted MCP Streamable HTTP Origin: %s", origin)
49
+ return JSONResponse(
50
+ {"error": f"Untrusted Origin '{origin}' rejected (DNS rebinding protection)."},
51
+ status_code=403,
52
+ )
53
+ if self._authorizer is not None:
54
+ try:
55
+ self._authorizer.authorize(
56
+ path=request.url.path,
57
+ client_ip=request.client.host if request.client else None,
58
+ authorization_header=request.headers.get("Authorization"),
59
+ x_forwarded_for=request.headers.get("X-Forwarded-For"),
60
+ forwarded=request.headers.get("Forwarded"),
61
+ )
62
+ except AuthPolicyError as exc:
63
+ return JSONResponse({"error": str(exc)}, status_code=exc.status_code)
64
+ return await call_next(request)
65
+
66
+
67
+ def create_mcp_http_app(
68
+ proxy: FastMCPProxy,
69
+ *,
70
+ allowed_origins: Sequence[str] = (),
71
+ api_token: str | None = None,
72
+ allowed_ips: Sequence[str] | None = None,
73
+ trusted_proxies: Sequence[str] = (),
74
+ engine: RevertXEngine | None = None,
75
+ ) -> Starlette:
76
+ """Build a Streamable HTTP ASGI app enforcing Origin, auth, and startup recovery."""
77
+ authorizer = (
78
+ RouteAuthorizer(
79
+ api_token=api_token,
80
+ allowed_ips=allowed_ips,
81
+ trusted_proxies=trusted_proxies,
82
+ exempt_paths=(),
83
+ )
84
+ if api_token is not None or allowed_ips is not None
85
+ else None
86
+ )
87
+ middleware = [
88
+ ASGIMiddleware(
89
+ StreamableHTTPOriginMiddleware,
90
+ allowed_origins=allowed_origins,
91
+ authorizer=authorizer,
92
+ )
93
+ ]
94
+ app = proxy.http_app(transport="streamable-http", middleware=middleware)
95
+ base_lifespan = app.router.lifespan_context
96
+
97
+ @asynccontextmanager
98
+ async def _recover_lifespan(target_app: Starlette) -> AsyncIterator[Any]:
99
+ if engine is not None:
100
+ await engine.recover_stranded_compensations()
101
+ async with base_lifespan(target_app) as state:
102
+ yield state
103
+
104
+ app.router.lifespan_context = _recover_lifespan
105
+ return app
106
+
107
+
108
+ async def run_mcp_proxy_http(
109
+ proxy: FastMCPProxy,
110
+ *,
111
+ host: str = "127.0.0.1",
112
+ port: int = 8001,
113
+ allow_non_loopback: bool = False,
114
+ api_token: str | None = None,
115
+ allowed_ips: Sequence[str] | None = None,
116
+ trusted_proxies: Sequence[str] = (),
117
+ allowed_origins: Sequence[str] = (),
118
+ engine: RevertXEngine | None = None,
119
+ ) -> None:
120
+ """Serve proxy over Streamable HTTP defaulting strictly to 127.0.0.1 + Origin guard."""
121
+ safe_host = validate_http_bind_host(
122
+ host, allow_non_loopback=allow_non_loopback, api_token=api_token
123
+ )
124
+ app = create_mcp_http_app(
125
+ proxy,
126
+ allowed_origins=allowed_origins,
127
+ api_token=api_token,
128
+ allowed_ips=allowed_ips,
129
+ trusted_proxies=trusted_proxies,
130
+ engine=engine,
131
+ )
132
+ server = uvicorn.Server(uvicorn.Config(app, host=safe_host, port=port))
133
+ await server.serve()
@@ -0,0 +1,249 @@
1
+ """Thin FastMCP proxy adapter routing intercepted tool calls through RevertXEngine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from collections.abc import Callable, Sequence
8
+ from contextvars import ContextVar
9
+ from typing import Any, cast
10
+ from uuid import uuid4
11
+
12
+ import mcp.types as mt
13
+ from fastmcp import FastMCP
14
+ from fastmcp.server import create_proxy
15
+ from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
16
+ from fastmcp.server.providers.proxy import FastMCPProxy
17
+ from fastmcp.tools import Tool, ToolResult
18
+ from pydantic import BaseModel, Field
19
+
20
+ from revertx.adapters.mcp_http import (
21
+ StreamableHTTPOriginMiddleware,
22
+ create_mcp_http_app,
23
+ run_mcp_proxy_http,
24
+ )
25
+ from revertx.core.engine import RevertXEngine
26
+ from revertx.core.exceptions import ApprovalPendingError, RevertXError
27
+ from revertx.core.mcp_guard import ToolSchemaGuard
28
+ from revertx.core.models import StepStatus
29
+ from revertx.core.security import redact_payload
30
+
31
+ logger = logging.getLogger("revertx.mcp_proxy")
32
+
33
+ _mcp_run_var: ContextVar[str | None] = ContextVar("revertx_mcp_run_id", default=None)
34
+ _mcp_step_var: ContextVar[tuple[str, str] | None] = ContextVar(
35
+ "revertx_mcp_last_step_by_run", default=None
36
+ )
37
+
38
+ __all__ = [
39
+ "InterceptedToolCall",
40
+ "PassThroughInterceptorMiddleware",
41
+ "StreamableHTTPOriginMiddleware",
42
+ "create_mcp_http_app",
43
+ "create_mcp_proxy",
44
+ "run_mcp_proxy_http",
45
+ ]
46
+
47
+
48
+ class InterceptedToolCall(BaseModel):
49
+ """Structured record of a single intercepted MCP tool call."""
50
+
51
+ run_id: str
52
+ step_id: str
53
+ tool_name: str
54
+ arguments: dict[str, Any] = Field(default_factory=dict)
55
+ outcome: str
56
+ error_detail: str | None = None
57
+
58
+
59
+ class _UpstreamToolError(Exception):
60
+ def __init__(self, result: ToolResult, detail: str) -> None:
61
+ self.result = result
62
+ super().__init__(detail)
63
+
64
+
65
+ class PassThroughInterceptorMiddleware(Middleware):
66
+ """Intercepts MCP tools, pins schemas, recovers crashes, and routes via RevertXEngine."""
67
+
68
+ def __init__(
69
+ self,
70
+ *,
71
+ run_id: str | None = None,
72
+ events: list[InterceptedToolCall] | None = None,
73
+ printer: Callable[[str], None] | None = None,
74
+ engine: RevertXEngine | None = None,
75
+ schema_guard: ToolSchemaGuard | None = None,
76
+ upstream_server: FastMCP[Any] | None = None,
77
+ ) -> None:
78
+ self.run_id = run_id or str(uuid4())
79
+ self.events = events if events is not None else []
80
+ self._printer = printer
81
+ self._engine = engine
82
+ self._schema_guard = schema_guard
83
+ self._upstream_server = upstream_server
84
+ self._last_step_by_run: dict[str, str] = {}
85
+ self._recovery_lock = asyncio.Lock()
86
+ self._recovered = False
87
+
88
+ async def ensure_recovered(self) -> None:
89
+ """Run startup crash-recovery sweep once when wired to a RevertXEngine."""
90
+ if self._recovered or self._engine is None:
91
+ return
92
+ async with self._recovery_lock:
93
+ if not self._recovered:
94
+ await self._engine.recover_stranded_compensations()
95
+ self._recovered = True
96
+
97
+ async def on_list_tools(
98
+ self,
99
+ context: MiddlewareContext[mt.ListToolsRequest],
100
+ call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]],
101
+ ) -> Sequence[Tool]:
102
+ """Pin initial tool schemas/descriptions and detect rug-pull mutations on listing."""
103
+ await self.ensure_recovered()
104
+ tools = await call_next(context)
105
+ if self._schema_guard is not None:
106
+ await self._schema_guard.verify_or_pin_tools(tools)
107
+ return tools
108
+
109
+ async def on_call_tool(
110
+ self,
111
+ context: MiddlewareContext[mt.CallToolRequestParams],
112
+ call_next: CallNext[mt.CallToolRequestParams, ToolResult],
113
+ ) -> ToolResult:
114
+ """Verify schema fingerprint, enforce engine safety checks, and forward."""
115
+ await self.ensure_recovered()
116
+ step_id, tool_name = str(uuid4()), context.message.name
117
+ arguments: dict[str, Any] = dict(context.message.arguments or {})
118
+ active_run_id = _mcp_run_var.get() or self.run_id
119
+ ctx_step = _mcp_step_var.get()
120
+ parent_step_id = (
121
+ ctx_step[1]
122
+ if ctx_step is not None and ctx_step[0] == active_run_id
123
+ else self._last_step_by_run.get(active_run_id)
124
+ )
125
+ self._emit(f"[RevertX] INTERCEPT run_id={active_run_id} step_id={step_id} tool={tool_name}")
126
+
127
+ async def _forward(_name: str, _args: dict[str, Any]) -> ToolResult:
128
+ res = await call_next(context)
129
+ if getattr(res, "is_error", False):
130
+ parts = [getattr(b, "text", str(b)) for b in res.content]
131
+ raise _UpstreamToolError(res, "; ".join(parts) or "Upstream tool error.")
132
+ return res
133
+
134
+ try:
135
+ if self._schema_guard is not None and self._upstream_server is not None:
136
+ upstream_tool = await self._upstream_server.get_tool(tool_name)
137
+ if upstream_tool is not None:
138
+ await self._schema_guard.verify_single_tool(upstream_tool)
139
+ if self._engine is not None:
140
+ step, result = await self._engine.execute_tool(
141
+ run_id=active_run_id,
142
+ step_id=step_id,
143
+ parent_step_id=parent_step_id,
144
+ tool_name=tool_name,
145
+ arguments=arguments,
146
+ executor=_forward,
147
+ )
148
+ self._last_step_by_run[active_run_id] = step.step_id
149
+ _mcp_step_var.set((active_run_id, step.step_id))
150
+ if step.status in (
151
+ StepStatus.WOULD_EXECUTE,
152
+ StepStatus.WOULD_REQUIRE_APPROVAL,
153
+ StepStatus.WOULD_BLOCK,
154
+ ):
155
+ self._record(active_run_id, step_id, tool_name, arguments, step.status.value)
156
+ return ToolResult(
157
+ content=(
158
+ f"[RevertX SHADOW_PREVIEW] status={step.status.value} "
159
+ f"run_id={active_run_id} step_id={step.step_id}: "
160
+ f"{step.output_json or '{}'}"
161
+ ),
162
+ is_error=True,
163
+ )
164
+ else:
165
+ result = await _forward(tool_name, arguments)
166
+ except _UpstreamToolError as exc:
167
+ self._record(active_run_id, step_id, tool_name, arguments, "ERROR", str(exc))
168
+ return exc.result
169
+ except ApprovalPendingError as exc:
170
+ self._record(
171
+ active_run_id, step_id, tool_name, arguments, "PENDING_APPROVAL", str(exc)
172
+ )
173
+ return ToolResult(
174
+ content=(
175
+ f"[RevertX PENDING_APPROVAL] approval_id={exc.approval_id} "
176
+ f"run_id={exc.run_id} step_id={exc.step_id}: {exc}"
177
+ ),
178
+ is_error=True,
179
+ )
180
+ except RevertXError as exc:
181
+ self._record(active_run_id, step_id, tool_name, arguments, "BLOCKED", str(exc))
182
+ return ToolResult(content=f"[RevertX BLOCKED] {exc}", is_error=True)
183
+ except Exception as exc:
184
+ self._record(active_run_id, step_id, tool_name, arguments, "ERROR", str(exc))
185
+ raise
186
+
187
+ self._record(active_run_id, step_id, tool_name, arguments, "SUCCESS")
188
+ return cast(ToolResult, result)
189
+
190
+ def _record(
191
+ self,
192
+ run_id: str,
193
+ step_id: str,
194
+ tool_name: str,
195
+ arguments: dict[str, Any],
196
+ outcome: str,
197
+ error_detail: str | None = None,
198
+ ) -> None:
199
+ if outcome in ("ERROR", "BLOCKED"):
200
+ logger.error(
201
+ "MCP %s run_id=%s step_id=%s tool=%s detail=%s",
202
+ outcome,
203
+ run_id,
204
+ step_id,
205
+ tool_name,
206
+ error_detail,
207
+ )
208
+ safe_args = cast(dict[str, Any], redact_payload(arguments, include_pii=True))
209
+ self.events.append(
210
+ InterceptedToolCall(
211
+ run_id=run_id,
212
+ step_id=step_id,
213
+ tool_name=tool_name,
214
+ arguments=safe_args,
215
+ outcome=outcome,
216
+ error_detail=error_detail,
217
+ )
218
+ )
219
+ self._emit(f"[RevertX] {outcome} run_id={run_id} step_id={step_id} tool={tool_name}")
220
+
221
+ def _emit(self, message: str) -> None:
222
+ logger.info(message)
223
+ if self._printer is not None:
224
+ self._printer(message)
225
+
226
+
227
+ def create_mcp_proxy(
228
+ target: FastMCP[Any] | str,
229
+ *,
230
+ name: str = "revertx-proxy",
231
+ run_id: str | None = None,
232
+ events: list[InterceptedToolCall] | None = None,
233
+ printer: Callable[[str], None] | None = None,
234
+ engine: RevertXEngine | None = None,
235
+ schema_guard: ToolSchemaGuard | None = None,
236
+ ) -> FastMCPProxy:
237
+ """Create a FastMCP proxy wrapping target and enforcing RevertXEngine + schema guard."""
238
+ proxy = create_proxy(target, name=name)
239
+ upstream = target if isinstance(target, FastMCP) else None
240
+ interceptor = PassThroughInterceptorMiddleware(
241
+ run_id=run_id,
242
+ events=events,
243
+ printer=printer,
244
+ engine=engine,
245
+ schema_guard=schema_guard,
246
+ upstream_server=upstream,
247
+ )
248
+ proxy.add_middleware(interceptor)
249
+ return proxy