-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
executable file
·2272 lines (1956 loc) · 82.2 KB
/
Copy pathproxy.py
File metadata and controls
executable file
·2272 lines (1956 loc) · 82.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Transparent LLM proxy for the OpenAI Responses API.
Forces a single model on every request, with optional plan-mode switching
based on reasoning effort. Supports OpenRouter and Requesty as upstream
providers, with provider pinning and fallback control.
Features
--------
- **Model forcing**: every request is rewritten to use MCP_TAP_MODEL (or
MCP_TAP_PLAN_MODE_MODEL when the reasoning effort matches
MCP_TAP_PLAN_MODE_TRIGGER).
- **Provider selection**: upstream is OpenRouter or Requesty, selected via
MCP_TAP_UPSTREAM_PROVIDER. OpenRouter provider pinning and fallback
disabling are configurable.
- **Per-model instructions**: inject additional system instructions per model
via MCP_TAP_PER_MODEL_YAML (inline YAML or @path to a file).
- **MCP tool interception**: tools declared in MCP_TAP_INTERCEPT_YAML are
exposed to the model as regular function tools. When the model calls them,
the proxy executes the real MCP tool locally, feeds the result back into the
conversation, and only surfaces the final assistant response. The client
never sees the intercepted tool calls.
- **Tool-call hook gateway**: when MCP_TAP_USE_TOOL_HOOK points to a hook
script, the proxy intercepts client tool calls, injects a synthetic
``get_goal`` call, and runs the hook to allow or block the response.
The hook can also return ``updated_tool_calls`` to rewrite tool call
arguments (e.g. wrap shell commands with ``rtk``) before the response
is returned to the client.
- **Session tracking**: UUIDv7-based session tracking with token accumulation
and elapsed-time measurement per conversation.
- **File logging**: optional request/response logging to MCP_TAP_LOG_FILE.
Compatible with Python 3.10+.
Supports normal JSON responses and streaming SSE responses.
to see logs:
journalctl --user -u mcptap.service -f
for DEBUG level:
journalctl --user -u mcptap.service -p debug -f
"""
import asyncio
import contextlib
import copy
import json
import logging
import os
import sys
import time
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
import yaml # type: ignore
from aiohttp import ( # type: ignore
ClientError,
ClientSession,
ClientTimeout,
TCPConnector,
web,
)
from dotenv import load_dotenv # type: ignore
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
CONFIG_DIR = Path.home() / ".config/mcptap"
load_dotenv(CONFIG_DIR / "proxy.env", override=True)
MCP_TAP_LISTEN_HOST = os.environ.get("MCP_TAP_LISTEN_HOST", "127.0.0.1")
MCP_TAP_LISTEN_PORT = int(os.environ.get("MCP_TAP_LISTEN_PORT", "8787"))
MCP_TAP_OPENROUTER_PROVIDER = os.environ.get("MCP_TAP_OPENROUTER_PROVIDER", "").strip()
MCP_TAP_OPENROUTER_DISABLE_PROVIDER_FALLBACKS = os.environ.get(
"MCP_TAP_OPENROUTER_DISABLE_PROVIDER_FALLBACKS", "1"
).lower() not in {
"0",
"false",
"no",
"off",
}
MCP_TAP_PLAN_MODE_TRIGGER = os.environ.get("MCP_TAP_PLAN_MODE_TRIGGER", "max").strip()
MCP_TAP_PLAN_MODE_MAX_INPUT_SIZE = int(os.environ.get("MCP_TAP_PLAN_MODE_MAX_INPUT_SIZE", 100000))
MCP_TAP_INTERCEPT_YAML = os.environ.get("MCP_TAP_INTERCEPT_YAML", "").strip()
MCP_TAP_INTERCEPT_MAX_ITERATIONS = int(os.environ.get("MCP_TAP_INTERCEPT_MAX_ITERATIONS", "8"))
MCP_TAP_INTERCEPT_TOOL_TIMEOUT = float(os.environ.get("MCP_TAP_INTERCEPT_TOOL_TIMEOUT", "120"))
MCP_TAP_PER_MODEL_YAML = os.environ.get("MCP_TAP_PER_MODEL_YAML", "").strip()
MCP_TAP_LOG_LEVEL = os.environ.get("MCP_TAP_LOG_LEVEL", "INFO").upper()
MCP_TAP_LOG_FILE = os.environ.get("MCP_TAP_LOG_FILE", "").strip()
LOG_FILE_REDACT_HEADERS = os.environ.get("LOG_FILE_REDACT_HEADERS", "0").lower() not in {
"0",
"false",
"no",
"off",
}
LOG_PAYLOAD_KEYS = [
"tools",
]
MCP_TAP_USE_TOOL_HOOK = os.environ.get("MCP_TAP_USE_TOOL_HOOK", "").strip()
MCP_TAP_USE_TOOL_HOOK_TIMEOUT = float(os.environ.get("MCP_TAP_USE_TOOL_HOOK_TIMEOUT", "30"))
# When set, the proxy injects a synthetic call to this tool name before
# running the hook. When empty, the hook runs immediately upon detecting
# client tool calls, without injecting any synthetic tool.
MCP_TAP_USE_TOOL_HOOK_SYNTHETIC_TOOL = os.environ.get("MCP_TAP_USE_TOOL_HOOK_SYNTHETIC_TOOL", "get_goal").strip()
# Directory for per-session blocklist control files. Each session gets a
# subdirectory named after the Codex session ID (CODEX_THREAD_ID).
# The LD_PRELOAD library reads <dir>/<session_id>/blocked_files.
MCP_TAP_PER_SESSION_DIR = os.environ.get("MCP_TAP_PER_SESSION_DIR", "/tmp/mcptap/per_session").strip()
# Maximum age (seconds) for a pending state before it is cleaned up.
MCP_TAP_USE_TOOL_HOOK_PENDING_TTL = 600.0
SYNTHETIC_GET_GOAL_CALL_ID = "synthetic_get_goal"
SYNTHETIC_GET_GOAL_TOOL_NAME = "get_goal"
PROVIDER_OPENROUTER = "openrouter"
PROVIDER_REQUESTY = "requesty"
MCP_TAP_UPSTREAM_PROVIDER = os.environ.get("MCP_TAP_UPSTREAM_PROVIDER")
UPSTREAM_BASE_URL = ""
PROVIDER_ENV_FILE = ""
if PROVIDER_OPENROUTER == MCP_TAP_UPSTREAM_PROVIDER:
UPSTREAM_BASE_URL = "https://openrouter.ai/api/v1"
PROVIDER_ENV_FILE = "openrouter.env"
elif PROVIDER_REQUESTY == MCP_TAP_UPSTREAM_PROVIDER:
UPSTREAM_BASE_URL = "https://router.requesty.ai/v1"
PROVIDER_ENV_FILE = "requesty.env"
if not UPSTREAM_BASE_URL:
raise RuntimeError("MCP_TAP_UPSTREAM_PROVIDER must be one of 'openrouter' or 'requesty'")
load_dotenv(CONFIG_DIR / PROVIDER_ENV_FILE, override=True)
MCP_TAP_API_KEY = os.environ.get("MCP_TAP_API_KEY").strip()
if not MCP_TAP_API_KEY:
raise RuntimeError("MCP_TAP_API_KEY must not be empty")
MCP_TAP_MODEL = os.environ.get("MCP_TAP_MODEL").strip()
MCP_TAP_PLAN_MODE_MODEL = os.environ.get("MCP_TAP_PLAN_MODE_MODEL").strip()
if not MCP_TAP_MODEL or not MCP_TAP_PLAN_MODE_MODEL:
raise RuntimeError("MCP_TAP_MODEL and MCP_TAP_PLAN_MODE_MODEL must not be empty")
if PROVIDER_REQUESTY == MCP_TAP_UPSTREAM_PROVIDER:
# requesty.ai models require '-responses' in model's name vendor
if MCP_TAP_MODEL.startswith("openai") and "-responses" not in MCP_TAP_MODEL:
vendor, model = MCP_TAP_MODEL.split("/", 1)
MCP_TAP_MODEL = f"{vendor}-responses/{model}"
if MCP_TAP_PLAN_MODE_MODEL.startswith("openai") and "-responses" not in MCP_TAP_PLAN_MODE_MODEL:
vendor, model = MCP_TAP_PLAN_MODE_MODEL.split("/", 1)
MCP_TAP_PLAN_MODE_MODEL = f"{vendor}-responses/{model}"
# strip any trailing ':.*' descriptors from model name
MCP_TAP_MODEL = MCP_TAP_MODEL.split(":")[0]
MCP_TAP_PLAN_MODE_MODEL = MCP_TAP_PLAN_MODE_MODEL.split(":")[0]
logging.basicConfig(
level=getattr(logging, MCP_TAP_LOG_LEVEL, logging.INFO),
format="%(asctime)s %(levelname)s %(message)s",
)
LOGGER = logging.getLogger("mcptap")
COMMUNICATION_LOGGER = logging.getLogger("mcptap-communication")
COMMUNICATION_LOGGER.propagate = False
COMMUNICATION_LOGGER.setLevel(logging.INFO)
if MCP_TAP_LOG_FILE:
communication_handler = logging.FileHandler(MCP_TAP_LOG_FILE, encoding="utf-8")
communication_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
COMMUNICATION_LOGGER.addHandler(communication_handler)
SENSITIVE_HEADER_NAMES = {
"authorization",
"cookie",
"proxy-authorization",
"set-cookie",
}
HOP_BY_HOP_HEADERS: Set[str] = {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"host",
"content-length",
}
DEBUG_PAYLOAD_KEYS = [
"tools",
]
def _load_per_model_config() -> Dict[str, Dict[str, Any]]:
"""Load per-model configuration from MCP_TAP_PER_MODEL_YAML.
Returns a dict mapping model identifiers to their config (e.g. instructions).
Supports model names with suffixes like ':floor' (suffix is ignored for matching).
Also supports '@preset/name' and 'policy/name' entries.
"""
if not MCP_TAP_PER_MODEL_YAML:
return {}
payload = MCP_TAP_PER_MODEL_YAML
if payload.startswith("@"):
path = payload[1:]
with open(path, "r", encoding="utf-8") as fh:
payload = fh.read()
data = yaml.safe_load(payload)
if not isinstance(data, dict):
LOGGER.warning("MCP_TAP_PER_MODEL_YAML must be a YAML dict")
return {}
# Process entries - strip suffixes from model names for matching
result: Dict[str, Dict[str, Any]] = {}
for model_key, cfg in data.items():
if not isinstance(cfg, dict):
continue
base_model = model_key.split(":")[0] if ":" in model_key else model_key
if isinstance(cfg.get("instructions"), str):
result[model_key] = cfg
if base_model != model_key:
result[base_model] = cfg
return result
def rewrite_json_payload(
request: web.Request,
payload: Dict[str, Any],
intercept: "MCPInterceptor",
per_model_config: Dict[str, Dict[str, Any]],
) -> Tuple[Optional[str], str, Optional[str]]:
"""In-place rewrite. Returns (original_model, forced_model, reasoning_effort)."""
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"%s %s payload_keys=%r",
request.method,
request.path_qs,
list(payload.keys()),
)
original_model, forced_model, reasoning_effort = _apply_model_and_provider(payload)
_inject_tools(payload, intercept)
if forced_model:
_inject_per_model_instructions(payload, forced_model, per_model_config)
candidate_force_model = MCP_TAP_MODEL
reasoning = payload.get("reasoning", {})
if not isinstance(reasoning, dict):
reasoning = {}
reasoning_effort = reasoning.get("effort", None)
if MCP_TAP_PLAN_MODE_TRIGGER == reasoning_effort:
candidate_force_model = MCP_TAP_PLAN_MODE_MODEL
if PROVIDER_REQUESTY == MCP_TAP_UPSTREAM_PROVIDER:
# requesty.ai does not support image_generation as a tool
# filer out image_generation tool
tools = []
for tool in payload["tools"]:
if tool["type"] != "image_generation":
tools.append(tool)
payload["tools"] = tools
# some google models do not like function tools and server tools mixed
if "google" in candidate_force_model:
tools = []
for tool in payload["tools"]:
if tool["type"] == "function" or tool["type"] == "namespace":
tools.append(tool)
payload["tools"] = tools
payload["tool_config"] = {"include_server_side_tool_invocations": True}
# some models do not like "include" field
del payload["include"]
if PROVIDER_OPENROUTER == MCP_TAP_UPSTREAM_PROVIDER:
if candidate_force_model.startswith("@"):
# openrouter.ai does not support some tools
# in presets (model=@...)
tools = []
for tool in payload["tools"]:
if tool["type"] == "function" or tool["type"] == "namespace":
tools.append(tool)
payload["tools"] = tools
if LOGGER.isEnabledFor(logging.DEBUG):
for key in DEBUG_PAYLOAD_KEYS:
LOGGER.debug(
"%s %s After rewrite payload_key=%r payload_value=%r",
request.method,
request.path_qs,
key,
payload.get(key),
)
return original_model, forced_model, reasoning_effort
# ---------------------------------------------------------------------------
# MCP intercept manager
# ---------------------------------------------------------------------------
class InterceptedTool:
"""One tool exposed to the model that is backed by an MCP tool call."""
def __init__(self, mapping: Dict[str, Any]) -> None:
self.expose_as: str = mapping["expose_as"]
self.mcp_tool: str = mapping["mcp_tool"]
override = mapping.get("override") or {}
if not isinstance(override, dict):
raise RuntimeError(f"MCP intercept mapping {self.expose_as!r} has non-object 'override'")
self.override: Dict[str, Any] = override
# Filled by MCPInterceptor after list_tools()
self.resolved_parameters: Optional[Dict[str, Any]] = None
self.resolved_description: Optional[str] = None
def to_tool_definition(self) -> Dict[str, Any]:
base: Dict[str, Any] = {
"type": "function",
"execution": "client",
"name": self.expose_as,
"description": self.resolved_description or f"MCP-backed tool {self.mcp_tool}",
"strict": False,
"parameters": self.resolved_parameters or {"type": "object", "properties": {}},
}
# `override` shallow-merges on top of the MCP-derived definition.
# Fields we control (type/name/execution) are always restored so the
# routing on our side cannot be broken by a stray override.
merged = {**base, **self.override}
merged["type"] = "function"
merged["execution"] = "client"
merged["name"] = self.expose_as
return merged
class MCPInterceptor:
"""Owns a single long-lived MCP subprocess and dispatches tool calls to it."""
def __init__(self, config: Optional[Dict[str, Any]]) -> None:
self._config = config
self.tools: List[InterceptedTool] = [InterceptedTool(m) for m in config["mappings"]] if config else []
self._session: Any = None
self._exit_stack: Optional[contextlib.AsyncExitStack] = None
self._lock: Optional[asyncio.Lock] = None
self._started = False
@property
def enabled(self) -> bool:
return bool(self.tools)
def tool_names(self) -> Set[str]:
return {tool.expose_as for tool in self.tools}
def find_tool(self, exposed_name: str) -> Optional[InterceptedTool]:
for tool in self.tools:
if tool.expose_as == exposed_name:
return tool
return None
async def start(self) -> None:
if not self.enabled or self._started:
return
from mcp import ClientSession, StdioServerParameters # type: ignore
from mcp.client.stdio import stdio_client # type: ignore
server = self._config
assert server is not None
stack = contextlib.AsyncExitStack()
await stack.__aenter__()
try:
merged_env = os.environ.copy()
merged_env.update(server.get("mcp_env") or {})
params = StdioServerParameters(
command=server["mcp_command"],
args=list(server.get("mcp_args") or []),
env=merged_env,
cwd=server.get("mcp_cwd"),
)
read, write = await stack.enter_async_context(stdio_client(params))
session = await stack.enter_async_context(ClientSession(read, write))
await session.initialize()
LOGGER.info(
"MCP session started: command=%r args=%r env=%r cwd=%r",
server["mcp_command"],
server.get("mcp_args") or [],
merged_env,
server.get("mcp_cwd"),
)
except Exception:
await stack.aclose()
raise
self._exit_stack = stack
self._session = session
self._lock = asyncio.Lock()
listing = await session.list_tools()
by_name = {t.name: t for t in listing.tools}
for tool in self.tools:
mcp_tool = by_name.get(tool.mcp_tool)
if mcp_tool is None:
LOGGER.warning(
"MCP tool %r not found on server (available: %r)",
tool.mcp_tool,
list(by_name.keys()),
)
continue
tool.resolved_description = mcp_tool.description
tool.resolved_parameters = mcp_tool.inputSchema
LOGGER.info(
"Intercept ready: expose_as=%r -> mcp_tool=%r",
tool.expose_as,
tool.mcp_tool,
)
self._started = True
async def stop(self) -> None:
if self._exit_stack is not None:
try:
await self._exit_stack.aclose()
except Exception as exc:
LOGGER.warning("Error closing MCP session: %s", exc)
self._exit_stack = None
self._session = None
self._lock = None
self._started = False
async def call(self, exposed_name: str, arguments: Dict[str, Any]) -> str:
tool = self.find_tool(exposed_name)
if tool is None:
raise KeyError(exposed_name)
if self._session is None or self._lock is None:
raise RuntimeError("MCP session is not started")
async with self._lock:
LOGGER.info("MCP call: expose_as=%r mcp_tool=%r", exposed_name, tool.mcp_tool)
try:
result = await asyncio.wait_for(
self._session.call_tool(tool.mcp_tool, arguments or {}),
timeout=MCP_TAP_INTERCEPT_TOOL_TIMEOUT,
)
except asyncio.TimeoutError:
LOGGER.warning(
"MCP call timed out after %.1fs: %r",
MCP_TAP_INTERCEPT_TOOL_TIMEOUT,
exposed_name,
)
return json.dumps({"error": f"MCP tool {tool.mcp_tool} timed out"})
except Exception as exc:
LOGGER.exception("MCP call failed: %s", exc)
return json.dumps({"error": f"MCP tool {tool.mcp_tool} failed: {exc}"})
return _serialize_mcp_result(result)
def _serialize_mcp_result(result: Any) -> str:
"""Turn an MCP CallToolResult into a plain string the model can consume."""
if result is None:
return ""
if getattr(result, "structuredContent", None) is not None:
try:
return json.dumps(result.structuredContent, ensure_ascii=False)
except (TypeError, ValueError):
pass
parts: List[str] = []
for item in getattr(result, "content", []) or []:
item_type = getattr(item, "type", None)
if item_type == "text":
parts.append(getattr(item, "text", ""))
else:
try:
parts.append(json.dumps(item.model_dump(mode="json"), ensure_ascii=False))
except Exception:
parts.append(str(item))
if getattr(result, "isError", False):
prefix = "[tool error] "
else:
prefix = ""
return prefix + ("\n".join(p for p in parts if p))
def _load_intercept_config() -> Optional[Dict[str, Any]]:
"""Return the intercept config as a validated dict, or None if disabled.
MCP_TAP_INTERCEPT_YAML is a YAML object describing a single MCP server plus a
list of mappings. Server fields (mcp_command/mcp_args/mcp_env/mcp_cwd) live
on the top-level object; each entry in `mappings` carries `expose_as`,
`mcp_tool`, and optionally `description`/`parameters`.
Value can be prefixed with `@` to load YAML from a file path.
"""
if not MCP_TAP_INTERCEPT_YAML:
return None
payload = MCP_TAP_INTERCEPT_YAML
if payload.startswith("@"):
path = payload[1:]
with open(path, "r", encoding="utf-8") as fh:
payload = fh.read()
data = yaml.safe_load(payload)
if not isinstance(data, dict):
raise RuntimeError("MCP_TAP_INTERCEPT_YAML must be a YAML object with 'mcp_command' and 'mappings'")
if "mcp_command" not in data:
raise RuntimeError("MCP_TAP_INTERCEPT_YAML must contain 'mcp_command'")
mappings = data.get("mappings")
if not isinstance(mappings, list) or not mappings:
raise RuntimeError("MCP_TAP_INTERCEPT_YAML must contain a non-empty 'mappings' list")
seen: Set[str] = set()
for mapping in mappings:
if not isinstance(mapping, dict):
raise RuntimeError("Each mapping in MCP_TAP_INTERCEPT_YAML must be an object")
for required in ("expose_as", "mcp_tool"):
if required not in mapping:
raise RuntimeError(f"MCP intercept mapping missing required field: {required!r}")
name = mapping["expose_as"]
if name in seen:
raise RuntimeError(f"Duplicate expose_as in MCP_TAP_INTERCEPT_YAML: {name!r}")
seen.add(name)
return {
"mcp_command": data["mcp_command"],
"mcp_args": data.get("mcp_args") or [],
"mcp_env": data.get("mcp_env") or {},
"mcp_cwd": data.get("mcp_cwd"),
"mappings": mappings,
}
# ---------------------------------------------------------------------------
# Session tracking and tool-call hook gateway
# ---------------------------------------------------------------------------
def _uuid_v7_timestamp(uuid_str: str) -> Optional[float]:
"""Extract a Unix timestamp (seconds) from a UUIDv7 string.
UUIDv7 embeds a 48-bit Unix timestamp in milliseconds in the first 48 bits.
Returns None if the string is not a valid UUIDv7.
"""
try:
u = uuid.UUID(uuid_str)
except (ValueError, AttributeError):
return None
if u.version != 7:
return None
bits = u.int
timestamp_ms = bits >> 80
return timestamp_ms / 1000.0
class SessionTracker:
"""Tracks per-session token usage and session start time.
Session ID is extracted from the ``session-id`` header.
If the UUID is v7, the embedded timestamp is used as session start;
otherwise the time of the first request is used.
"""
def __init__(self) -> None:
self._sessions: Dict[str, Dict[str, Any]] = {}
self._lock = asyncio.Lock()
async def track_request(self, request: web.Request, forced_model: str) -> Dict[str, Any]:
"""Return (or create) the session info dict for this request."""
session_id = request.headers.get("session-id", "").strip()
if not session_id:
session_id = "default"
async with self._lock:
info = self._sessions.get(session_id)
if info is None:
ts = _uuid_v7_timestamp(session_id)
start_time = ts if ts is not None else time.time()
info = {
"session_id": session_id,
"start_time": start_time,
"total_tokens": 0,
"forced_model": forced_model,
}
self._sessions[session_id] = info
else:
info["forced_model"] = forced_model
return dict(info)
async def add_usage(self, session_id: str, total_tokens: int) -> None:
if not session_id or total_tokens <= 0:
return
async with self._lock:
info = self._sessions.get(session_id)
if info is None:
ts = _uuid_v7_timestamp(session_id)
start_time = ts if ts is not None else time.time()
info = {
"session_id": session_id,
"start_time": start_time,
"total_tokens": 0,
"forced_model": MCP_TAP_MODEL,
}
self._sessions[session_id] = info
info["total_tokens"] += total_tokens
async def get_usage(self, session_id: str) -> int:
async with self._lock:
info = self._sessions.get(session_id)
return info["total_tokens"] if info else 0
async def get_session_info(self, session_id: str) -> Optional[Dict[str, Any]]:
async with self._lock:
info = self._sessions.get(session_id)
return dict(info) if info else None
async def get_elapsed_seconds(self, session_id: str) -> float:
async with self._lock:
info = self._sessions.get(session_id)
if info is None:
return 0.0
return time.time() - info["start_time"]
async def cleanup_expired(self) -> None:
now = time.time()
async with self._lock:
expired = [sid for sid, info in self._sessions.items() if now - info["start_time"] > 3600]
for sid in expired:
del self._sessions[sid]
class PendingState:
"""Stores a saved upstream response with client function calls awaiting hook decision."""
def __init__(
self,
session_id: str,
saved_status: int,
saved_headers: Dict[str, str],
saved_raw: bytes,
saved_body_json: Dict[str, Any],
client_tool_calls: List[Dict[str, Any]],
get_goal_result: Dict[str, Any],
forced_model: str,
used_tokens: int,
used_time_seconds: float,
) -> None:
self.session_id = session_id
self.saved_status = saved_status
self.saved_headers = saved_headers
self.saved_raw = saved_raw
self.saved_body_json = saved_body_json
self.client_tool_calls = client_tool_calls
self.get_goal_result = get_goal_result
self.forced_model = forced_model
self.used_tokens = used_tokens
self.used_time_seconds = used_time_seconds
self.created_at = time.time()
def is_expired(self, ttl: float = MCP_TAP_USE_TOOL_HOOK_PENDING_TTL) -> bool:
return time.time() - self.created_at > ttl
class ToolHookGateway:
"""Manages pending tool-call batches and runs the hook script.
When the model returns client function calls (non-intercepted), the gateway:
1. Saves the upstream response.
2. Returns a synthetic ``get_goal`` call to the client.
3. On the next request (which contains the get_goal result), runs the hook.
4. Returns the saved response if allowed, or feeds the block message to the model.
"""
def __init__(self, session_tracker: SessionTracker) -> None:
self.enabled = bool(MCP_TAP_USE_TOOL_HOOK)
self.session_tracker = session_tracker
self._pending: Dict[str, PendingState] = {}
self._lock = asyncio.Lock()
async def get_pending(self, session_id: str) -> Optional[PendingState]:
async with self._lock:
state = self._pending.get(session_id)
if state is None:
return None
if state.is_expired():
del self._pending[session_id]
return None
return state
async def set_pending(self, session_id: str, state: PendingState) -> None:
async with self._lock:
now = time.time()
expired = [
sid for sid, s in self._pending.items() if now - s.created_at > MCP_TAP_USE_TOOL_HOOK_PENDING_TTL
]
for sid in expired:
del self._pending[sid]
self._pending[session_id] = state
async def clear_pending(self, session_id: str) -> None:
async with self._lock:
self._pending.pop(session_id, None)
async def run_hook(self, state: PendingState) -> Dict[str, Any]:
"""Run the hook script and return its decision.
Returns one of:
{"action": "allow"}
{"action": "allow", "blocked_files": [...]}
{"action": "allow", "updated_tool_calls": [...]}
{"action": "block", "message": "..."}
``updated_tool_calls`` lets the hook rewrite tool call arguments
(e.g. ``cmd`` field) before the response is returned to the client.
Each entry must contain a ``call_id`` and may override ``name``
and/or ``arguments``.
On timeout, non-zero exit, or invalid JSON, raises RuntimeError.
"""
hook_input = {
"session_id": state.session_id,
"forced_model": state.forced_model,
"used_tokens": state.used_tokens,
"used_time_seconds": state.used_time_seconds,
"get_goal_result": state.get_goal_result,
"tool_calls": state.client_tool_calls,
}
stdin_data = json.dumps(hook_input, ensure_ascii=False)
try:
proc = await asyncio.create_subprocess_exec(
sys.executable,
MCP_TAP_USE_TOOL_HOOK,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
except OSError as exc:
raise RuntimeError(f"Failed to start hook script: {exc}") from exc
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
proc.communicate(stdin_data.encode("utf-8")),
timeout=MCP_TAP_USE_TOOL_HOOK_TIMEOUT,
)
except asyncio.TimeoutError:
proc.kill()
await proc.wait()
raise RuntimeError(f"Hook script timed out after {MCP_TAP_USE_TOOL_HOOK_TIMEOUT}s")
if proc.returncode != 0:
stderr_text = stderr_bytes.decode("utf-8", errors="replace")[:2000]
raise RuntimeError(f"Hook script exited with code {proc.returncode}: {stderr_text}")
stdout_text = stdout_bytes.decode("utf-8", errors="replace").strip()
try:
result = json.loads(stdout_text)
except json.JSONDecodeError as exc:
raise RuntimeError(f"Hook script returned invalid JSON: {stdout_text[:500]}") from exc
if not isinstance(result, dict) or result.get("action") not in ("allow", "block"):
raise RuntimeError(
f'Hook script must return {{"action": "allow"}} or '
f'{{"action": "block", "message": "..."}}, got: {stdout_text[:500]}'
)
return result
def _extract_usage_total_tokens(body_json: Optional[Dict[str, Any]]) -> int:
"""Extract usage.total_tokens from a Responses API response body."""
if not body_json:
return 0
usage = body_json.get("usage")
if not isinstance(usage, dict):
return 0
total = usage.get("total_tokens")
if isinstance(total, (int, float)):
return int(total)
return 0
def _extract_client_tool_calls(
body_json: Dict[str, Any],
intercept_names: Set[str],
) -> List[Dict[str, Any]]:
"""Extract function_call items that are NOT intercepted MCP tools.
Returns a list of dicts with keys: call_id, name, arguments.
"""
result = []
for item, call_id, name, arguments in _iter_function_calls(body_json):
if name in intercept_names:
continue
if not call_id:
continue
try:
parsed_args = json.loads(arguments) if isinstance(arguments, str) else (arguments or {})
if not isinstance(parsed_args, dict):
parsed_args = {}
except json.JSONDecodeError:
parsed_args = {}
result.append(
{
"call_id": call_id,
"name": name,
"arguments": parsed_args,
}
)
return result
def _has_intercepted_calls(body_json: Dict[str, Any], intercept_names: Set[str]) -> bool:
"""Check if the response contains any intercepted MCP tool calls."""
for _, call_id, name, _ in _iter_function_calls(body_json):
if name in intercept_names and call_id:
return True
return False
def _has_client_tool_calls(body_json: Dict[str, Any], intercept_names: Set[str]) -> bool:
"""Check if the response contains any client (non-intercepted) function calls."""
for _, call_id, name, _ in _iter_function_calls(body_json):
if name not in intercept_names and call_id:
return True
return False
def _extract_get_goal_result(working_payload: Dict[str, Any]) -> Dict[str, Any]:
"""Extract the get_goal result from the input items sent back by the client.
The client executes the synthetic get_goal call and returns a
function_call_output item with call_id == SYNTHETIC_GET_GOAL_CALL_ID.
"""
input_items = working_payload.get("input") or []
if not isinstance(input_items, list):
return {}
for item in input_items:
if not isinstance(item, dict):
continue
if item.get("type") == "function_call_output" and item.get("call_id") == SYNTHETIC_GET_GOAL_CALL_ID:
output = item.get("output")
if isinstance(output, dict):
return output
if isinstance(output, str):
try:
parsed = json.loads(output)
if isinstance(parsed, dict):
return parsed
except json.JSONDecodeError:
pass
return {"output": output}
return {}
def _strip_synthetic_get_goal(input_items: List[Any]) -> List[Any]:
"""Remove synthetic get_goal function_call and its function_call_output from input items."""
result = []
synthetic_call_ids = {SYNTHETIC_GET_GOAL_CALL_ID}
for item in input_items:
if not isinstance(item, dict):
result.append(item)
continue
call_id = item.get("call_id")
if call_id in synthetic_call_ids:
continue
result.append(item)
return result
def _build_synthetic_tool_response(
forced_model: str,
tool_name: str,
) -> Dict[str, Any]:
"""Build a synthetic response containing a single function_call to the
given tool name. The client executes the tool and sends the result back,
which MCPTap intercepts to run the hook.
"""
return {
"id": f"resp_{uuid.uuid4().hex[:24]}",
"object": "response",
"created_at": int(time.time()),
"model": forced_model,
"status": "incompleted",
"output": [
{
"type": "function_call",
"id": f"fc_{uuid.uuid4().hex[:24]}",
"call_id": SYNTHETIC_GET_GOAL_CALL_ID,
"name": tool_name,
"arguments": "{}",
}
],
"usage": None,
}
def _build_synthetic_get_goal_response(
forced_model: str,
) -> Dict[str, Any]:
"""Build a synthetic response containing a single get_goal function_call."""
return _build_synthetic_tool_response(forced_model, SYNTHETIC_GET_GOAL_TOOL_NAME)
def _build_hook_error_response(error_message: str, forced_model: str) -> Dict[str, Any]:
"""Build an error response for use_tool_hook_error."""
return {
"id": f"resp_{uuid.uuid4().hex[:24]}",
"object": "response",
"created_at": int(time.time()),
"model": forced_model,
"status": "failed",
"error": {
"message": error_message,
"type": "use_tool_hook_error",
},
"output": [],
"usage": None,
}
def _build_sse_from_response(response: Dict[str, Any]) -> bytes:
"""Build a minimal SSE byte stream from a response dict.
Emits response.created, response.output_item.added, response.output_item.done
and response.completed events so the client can parse the response and
extract individual output items (e.g. function_call items).
"""
lines: List[str] = []
created_payload = {"type": "response.created", "response": response}
lines.append("event: response.created")
lines.append(f"data: {json.dumps(created_payload, ensure_ascii=False)}")
lines.append("")
for item in response.get("output") or []:
if not isinstance(item, dict):
continue
added_payload = {"type": "response.output_item.added", "item": item}
lines.append("event: response.output_item.added")
lines.append(f"data: {json.dumps(added_payload, ensure_ascii=False)}")
lines.append("")
done_payload = {"type": "response.output_item.done", "item": item}
lines.append("event: response.output_item.done")
lines.append(f"data: {json.dumps(done_payload, ensure_ascii=False)}")
lines.append("")
completed_payload = {"type": "response.completed", "response": response}
lines.append("event: response.completed")
lines.append(f"data: {json.dumps(completed_payload, ensure_ascii=False)}")
lines.append("")
lines.append("data: [DONE]")
lines.append("")
return "\n".join(lines).encode("utf-8")
# ---------------------------------------------------------------------------
# File access blocking (LD_PRELOAD integration)
# ---------------------------------------------------------------------------
def _blocklist_file_path(session_id: str) -> str:
"""Return the path to the per-session blocklist control file.
The LD_PRELOAD library reads this file to know which paths to block.
The path is: <MCP_TAP_PER_SESSION_DIR>/<session_id>/blocked_files
"""
session_dir = os.path.join(MCP_TAP_PER_SESSION_DIR, session_id)
os.makedirs(session_dir, exist_ok=True)
return os.path.join(session_dir, "blocked_files")
def _write_blocklist(session_id: str, blocked_files: List[str]) -> str:
"""Write the blocked files list to a control file and return its path."""
path = _blocklist_file_path(session_id)
with open(path, "w") as f:
for entry in blocked_files:
f.write(f"{entry}\n")
LOGGER.info(
"Blocklist written for session=%s: %d files -> %s",
session_id,
len(blocked_files),
path,
)
return path
def _clear_blocklist(session_id: str) -> None:
"""Remove the blocklist control file for a session."""
path = _blocklist_file_path(session_id)
try:
os.unlink(path)
LOGGER.info("Blocklist cleared for session=%s", session_id)
except FileNotFoundError:
pass
# ---------------------------------------------------------------------------
# Request / response rewriting
# ---------------------------------------------------------------------------
def filtered_headers(headers) -> Dict[str, str]:
return {name: value for name, value in headers.items() if name.lower() not in HOP_BY_HOP_HEADERS}