Internal API¶
What you'll learn here: the modules that drive proxy wiring, state handling, and telemetry inside the adapter.
What belongs here¶
These modules are useful when you are:
- contributing to the adapter
- debugging request flow or upstream client behavior
- tracing session state, artifact handling, or telemetry emission
They are important, but they are more implementation-oriented than the public API section.
remote_mcp_adapter.proxy.factory¶
This module builds the per-server proxy map and manages session-pinned upstream clients.
Factory helpers for constructing per-server MCP proxies.
ProxyMount dataclass ¶
Container for one configured proxy mount and its client registry.Source code in
src/remote_mcp_adapter/proxy/factory.py224
225
226
227
228
229
230
231
@dataclass(slots=True)
class ProxyMount:
"""Container for one configured proxy mount and its client registry."""
server: ServerConfig
proxy: FastMCPProxy
clients: SessionClientRegistry
wiring_readiness: "ServerWiringReadiness"
ServerWiringReadiness dataclass ¶
Tracks whether one server mount is fully wired for stable discovery.Source code in
src/remote_mcp_adapter/proxy/factory.py234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
@dataclass(slots=True)
class ServerWiringReadiness:
"""Tracks whether one server mount is fully wired for stable discovery."""
ready: bool = False
def is_ready(self) -> bool:
"""Return whether the server tool surface is stable for pinning."""
return self.ready
def set_ready(self, ready: bool) -> None:
"""Update readiness state.
Args:
ready: Whether the server mount is ready for stable catalog pinning.
"""
self.ready = ready
is_ready ¶
is_ready()
Return whether the server tool surface is stable for pinning.Source code in
src/remote_mcp_adapter/proxy/factory.py240
241
242
def is_ready(self) -> bool:
"""Return whether the server tool surface is stable for pinning."""
return self.ready
set_ready ¶
set_ready(ready)
Update readiness state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ready | bool | Whether the server mount is ready for stable catalog pinning. | required |
Source code in src/remote_mcp_adapter/proxy/factory.py
244 245 246 247 248 249 250 | |
SessionClientRegistry dataclass ¶
Session-aware upstream client cache for one configured server.Source code in
src/remote_mcp_adapter/proxy/factory.py 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
@dataclass(slots=True)
class SessionClientRegistry:
"""Session-aware upstream client cache for one configured server."""
server: ServerConfig
session_store: SessionStore | None = None
default_timeout_seconds: int | None = None
session_termination_retries: int = 1
metadata_cache_ttl_seconds: int = 30
bypass_list_tools_cache: bool = False
_clients: dict[str, Client] = field(default_factory=dict)
_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
def _build_headers(self, inbound_headers: Mapping[str, str] | None = None) -> dict[str, str]:
"""Build upstream headers from static and passthrough policies.
Args:
inbound_headers: Optional inbound request headers for passthrough.
Returns:
Merged header dict ready for upstream dispatch.
"""
headers = dict(self.server.upstream.static_headers)
if not inbound_headers:
return headers
lowered = {key.lower(): value for key, value in inbound_headers.items()}
for header_name in self.server.upstream.client_headers.passthrough:
value = lowered.get(header_name.lower())
if value:
headers[header_name] = value
return headers
def _validate_required_headers(self, inbound_headers: Mapping[str, str] | None) -> None:
"""Ensure required client headers are present before upstream calls.
Args:
inbound_headers: Inbound request headers to check.
Raises:
RuntimeError: If any required headers are missing.
"""
required = self.server.upstream.client_headers.required
if not required:
return
lowered = {key.lower(): value for key, value in (inbound_headers or {}).items()}
missing = [name for name in required if not lowered.get(name.lower())]
if missing:
raise RuntimeError(f"Missing required client headers for server '{self.server.id}': {', '.join(missing)}")
def _build_httpx_client_factory(self) -> Any | None:
"""Build an AsyncClient factory when insecure TLS mode is enabled."""
if not self.server.upstream.insecure_tls:
return None
def factory(**kwargs: Any) -> httpx.AsyncClient:
"""Create AsyncClient with TLS verification disabled.
Args:
**kwargs: Keyword arguments forwarded to ``httpx.AsyncClient``.
"""
kwargs.setdefault("verify", False)
return httpx.AsyncClient(**kwargs)
return factory
def _build_transport(self, headers: Mapping[str, str] | None = None) -> Any:
"""Create the concrete transport object based on upstream transport type.
Args:
headers: Optional headers to inject into the transport.
"""
httpx_client_factory = self._build_httpx_client_factory()
common_kwargs: dict[str, Any] = {"headers": dict(headers or {})}
if httpx_client_factory is not None:
common_kwargs["httpx_client_factory"] = httpx_client_factory
if self.server.upstream.transport == "sse":
return SSETransport(url=self.server.upstream.url, **common_kwargs)
return StreamableHttpTransport(url=self.server.upstream.url, **common_kwargs)
def _build_client(self, inbound_headers: Mapping[str, str] | None = None) -> Client:
"""Create a fresh fastmcp client for this server.
Args:
inbound_headers: Optional inbound request headers for passthrough.
"""
headers = self._build_headers(inbound_headers)
transport = self._build_transport(headers)
return ResilientClient(
transport=transport,
timeout=self.default_timeout_seconds,
default_timeout=self.default_timeout_seconds,
session_termination_retries=self.session_termination_retries,
metadata_cache_ttl_seconds=self.metadata_cache_ttl_seconds,
bypass_list_tools_cache=self.bypass_list_tools_cache,
)
async def get_session_client(self) -> Client:
"""Return the session-pinned client for the current MCP request context.
Returns:
Cached or freshly created upstream ``Client``.
"""
ctx = get_context()
session_id = ctx.session_id
inbound_headers: Mapping[str, str] | None = None
if ctx.request_context and ctx.request_context.request:
inbound_headers = ctx.request_context.request.headers
self._validate_required_headers(inbound_headers)
if self.session_store is not None:
await self.session_store.touch_tool_activity(self.server.id, session_id)
async with self._lock:
client = self._clients.get(session_id)
if client is None:
client = self._build_client(inbound_headers)
# Keep one upstream session open per adapter session. Per-call
# async-with scopes then nest without terminating the upstream
# MCP session on every tool/resource/prompt operation.
await client.__aenter__()
self._clients[session_id] = client
logger.info(
"Created upstream session client",
extra={"server_id": self.server.id, "session_id": session_id},
)
return client
def build_probe_client(self, *, timeout_seconds: int | float | None = None) -> Client:
"""Build an isolated one-off client for health probing.
Args:
timeout_seconds: Override probe timeout in seconds.
"""
resolved_timeout: int | float = 5
if timeout_seconds is not None:
resolved_timeout = timeout_seconds
elif self.default_timeout_seconds is not None:
resolved_timeout = min(resolved_timeout, self.default_timeout_seconds)
headers = self._build_headers()
transport = self._build_transport(headers)
return Client(transport=transport, timeout=resolved_timeout)
async def reset_cached_clients(self, *, reason: str) -> int:
"""Close and clear all cached clients for reconnect/reinitialize flow.
Args:
reason: Human-readable reason for the reset.
Returns:
Number of clients that were closed.
"""
async with self._lock:
session_clients = list(self._clients.items())
self._clients.clear()
for session_id, client in session_clients:
try:
await client.close()
logger.warning(
"Reset upstream session client due to health policy",
extra={"server_id": self.server.id, "session_id": session_id, "reason": reason},
)
except Exception:
logger.debug(
"Failed to close upstream client during reset",
extra={"server_id": self.server.id, "session_id": session_id, "reason": reason},
exc_info=True,
)
return len(session_clients)
async def close_all(self) -> None:
"""Close all cached clients for this server."""
async with self._lock:
clients = list(self._clients.values())
self._clients.clear()
for client in clients:
try:
await client.close()
except Exception:
logger.debug(
"Failed to close upstream client cleanly",
extra={"server_id": self.server.id},
exc_info=True,
)
build_probe_client ¶
build_probe_client(*, timeout_seconds=None)
Build an isolated one-off client for health probing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout_seconds | int | float | None | Override probe timeout in seconds. | None |
Source code in src/remote_mcp_adapter/proxy/factory.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
close_all async ¶
close_all()
Close all cached clients for this server.Source code in
src/remote_mcp_adapter/proxy/factory.py208
209
210
211
212
213
214
215
216
217
218
219
220
221
async def close_all(self) -> None:
"""Close all cached clients for this server."""
async with self._lock:
clients = list(self._clients.values())
self._clients.clear()
for client in clients:
try:
await client.close()
except Exception:
logger.debug(
"Failed to close upstream client cleanly",
extra={"server_id": self.server.id},
exc_info=True,
)
get_session_client async ¶
get_session_client()
Return the session-pinned client for the current MCP request context.
Returns:
| Type | Description |
|---|---|
Client | Cached or freshly created upstream |
Source code in src/remote_mcp_adapter/proxy/factory.py
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 | |
reset_cached_clients async ¶
reset_cached_clients(*, reason)
Close and clear all cached clients for reconnect/reinitialize flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason | str | Human-readable reason for the reset. | required |
Returns:
| Type | Description |
|---|---|
int | Number of clients that were closed. |
Source code in src/remote_mcp_adapter/proxy/factory.py
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 | |
build_proxy_map ¶
build_proxy_map(config, session_store=None, *, telemetry=None)
Build per-server proxy objects keyed by server id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | AdapterConfig | Full adapter configuration. | required |
session_store | SessionStore | None | Optional session store for session-aware client caching. | None |
telemetry | Any | None | Optional telemetry recorder for server transforms. | None |
Returns:
| Type | Description |
|---|---|
dict[str, ProxyMount] | Dict mapping server IDs to |
Source code in src/remote_mcp_adapter/proxy/factory.py
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 | |
remote_mcp_adapter.proxy.hooks¶
This module wires upload-consumer overrides, artifact-producer overrides, local helper tools, and local resources into each proxy surface.
Proxy tool override wiring for configured adapters.
AdapterWireState dataclass ¶
Tracks idempotent wiring state across retries.Source code in
src/remote_mcp_adapter/proxy/hooks.py68
69
70
71
72
73
74
75
76
@dataclass(slots=True)
class AdapterWireState:
"""Tracks idempotent wiring state across retries."""
providers_added: set[str] = field(default_factory=set)
local_resources_added: set[str] = field(default_factory=set)
local_tools_added: set[str] = field(default_factory=set)
registered_tools_by_server: dict[str, set[str]] = field(default_factory=dict)
visibility_transform_added: set[str] = field(default_factory=set)
OverrideTool ¶
Bases: Tool
Tool wrapper that preserves upstream schema and delegates to custom handler.Source code in
src/remote_mcp_adapter/proxy/hooks.py 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
class OverrideTool(Tool):
"""Tool wrapper that preserves upstream schema and delegates to custom handler."""
_handler: ToolHandler = PrivateAttr()
def __init__(self, handler: ToolHandler, **kwargs: Any):
"""Initialize the override tool.
Args:
handler: Custom async handler for tool execution.
**kwargs: Keyword arguments forwarded to ``Tool``.
"""
super().__init__(**kwargs)
self._handler = handler
async def run(self, arguments: dict[str, Any], context: Context | None = None) -> ToolResult:
"""Delegate execution to the injected custom handler.
Args:
arguments: Tool arguments dict.
context: Optional MCP context; falls back to ``get_context()``.
"""
ctx = context or get_context()
return await self._handler(arguments, ctx)
@classmethod
def from_mcp_tool(
cls,
mcp_tool: Any,
handler: ToolHandler,
*,
description: str | None = None,
parameters: dict[str, Any] | None = None,
) -> "OverrideTool":
"""Construct an OverrideTool from an upstream MCP tool, preserving its schema.
Args:
mcp_tool: Upstream MCP tool object.
handler: Custom async handler for tool execution.
description: Optional override description.
parameters: Optional override input schema.
"""
return cls(
handler=handler,
name=mcp_tool.name,
title=mcp_tool.title,
description=description if description is not None else mcp_tool.description,
parameters=parameters if parameters is not None else mcp_tool.inputSchema,
annotations=mcp_tool.annotations,
output_schema=mcp_tool.outputSchema,
icons=mcp_tool.icons,
meta=mcp_tool.meta,
tags=(mcp_tool.meta or {}).get("_fastmcp", {}).get("tags", []),
)
__init__ ¶
__init__(handler, **kwargs)
Initialize the override tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler | ToolHandler | Custom async handler for tool execution. | required |
**kwargs | Any | Keyword arguments forwarded to | {} |
Source code in src/remote_mcp_adapter/proxy/hooks.py
84 85 86 87 88 89 90 91 92 | |
from_mcp_tool classmethod ¶
from_mcp_tool(mcp_tool, handler, *, description=None, parameters=None)
Construct an OverrideTool from an upstream MCP tool, preserving its schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mcp_tool | Any | Upstream MCP tool object. | required |
handler | ToolHandler | Custom async handler for tool execution. | required |
description | str | None | Optional override description. | None |
parameters | dict[str, Any] | None | Optional override input schema. | None |
Source code in src/remote_mcp_adapter/proxy/hooks.py
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 | |
run async ¶
run(arguments, context=None)
Delegate execution to the injected custom handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arguments | dict[str, Any] | Tool arguments dict. | required |
context | Context | None | Optional MCP context; falls back to | None |
Source code in src/remote_mcp_adapter/proxy/hooks.py
94 95 96 97 98 99 100 101 102 | |
wire_adapters async ¶
wire_adapters(*, config, proxy_map, store, state=None, upload_credentials=None, artifact_download_credentials=None, telemetry=None)
Register configured adapter overrides on each server proxy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | AdapterConfig | Full adapter configuration. | required |
proxy_map | dict[str, ProxyMount] | Server-id to | required |
store | SessionStore | Session store for adapter operations. | required |
state | AdapterWireState | None | Optional wiring state to enable idempotent retries. | None |
upload_credentials | UploadCredentialManager | None | Optional upload credential manager. | None |
artifact_download_credentials | ArtifactDownloadCredentialManager | None | Optional download credential manager. | None |
telemetry | 'AdapterTelemetry | None' | Optional telemetry manager. | None |
Returns:
| Type | Description |
|---|---|
dict[str, bool] | Dict mapping server id to whether wiring succeeded. |
Source code in src/remote_mcp_adapter/proxy/hooks.py
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 | |
remote_mcp_adapter.telemetry.manager¶
This module owns the async telemetry queue and OpenTelemetry emission flow.
Asynchronous telemetry manager backed by OpenTelemetry metrics/logs exporters.
AdapterTelemetry ¶
Async telemetry facade for OpenTelemetry metrics and optional log export.Source code in
src/remote_mcp_adapter/telemetry/manager.py 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
class AdapterTelemetry:
"""Async telemetry facade for OpenTelemetry metrics and optional log export."""
def __init__(self, *, config: TelemetryConfig) -> None:
"""Initialize the telemetry manager.
Args:
config: Resolved telemetry configuration section.
"""
self._config = config
self._enabled = bool(config.enabled)
self._queue: asyncio.Queue[TelemetryEvent] = asyncio.Queue(maxsize=config.max_queue_size)
self._worker_task: asyncio.Task[None] | None = None
self._stop_event = asyncio.Event()
self._metrics_api_module: Any | None = None
self._atexit_registered = False
self._meter_provider: Any | None = None
self._logger_provider: Any | None = None
self._otel_log_handler: Any | None = None
self._http_requests_total = None
self._http_request_duration = None
self._upload_batches_total = None
self._upload_files_total = None
self._upload_bytes_total = None
self._auth_rejections_total = None
self._upstream_tool_calls_total = None
self._upstream_tool_call_duration = None
self._upstream_ping_total = None
self._upstream_ping_latency = None
self._circuit_breaker_state = None
self._persistence_policy_transitions_total = None
self._nonce_operations_total = None
self._upload_credentials_total = None
self._artifact_downloads_total = None
self._artifact_download_bytes_total = None
self._artifact_download_duration = None
self._upload_failures_total = None
self._request_rejections_total = None
self._adapter_wiring_runs_total = None
self._adapter_wiring_not_ready_servers = None
self._cleanup_cycles_total = None
self._cleanup_removed_records_total = None
self._sessions_lifecycle_total = None
self._tool_definition_drift_total = None
@classmethod
def from_config(cls, resolved_config: AdapterConfig) -> "AdapterTelemetry":
"""Construct telemetry manager from adapter config.
Args:
resolved_config: Full adapter configuration.
"""
return cls(config=resolved_config.telemetry)
@property
def enabled(self) -> bool:
"""Return whether telemetry emission is enabled."""
return self._enabled
async def start(self) -> None:
"""Initialize OTel providers and start async event worker."""
if not self._enabled:
return
if self._worker_task is not None:
return
try:
metrics_api, meter_provider, resource, meter = initialize_metrics_backend(config=self._config)
except Exception:
logger.exception("OpenTelemetry dependencies are unavailable; telemetry disabled at runtime")
self._enabled = False
return
self._metrics_api_module = metrics_api
self._meter_provider = meter_provider
for attribute_name, instrument in create_metric_instruments(meter=meter).items():
setattr(self, attribute_name, instrument)
if self._config.emit_logs:
try:
self._logger_provider, self._otel_log_handler = setup_log_export(
config=self._config,
resource=resource,
root_logger=logging.getLogger(),
)
except Exception:
logger.exception("Failed to initialize OpenTelemetry log exporter; continuing with metrics only")
self._logger_provider = None
self._otel_log_handler = None
self._worker_task = asyncio.create_task(self._worker_loop(), name="telemetry-worker")
if self._config.flush_on_terminate and not self._atexit_registered:
atexit.register(self._on_process_terminate)
self._atexit_registered = True
async def shutdown(self) -> None:
"""Stop worker and flush/shutdown telemetry providers."""
if self._worker_task is None:
return
self._stop_event.set()
await self._queue.put(TelemetryEvent(kind="shutdown", payload={}))
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._queue.join(), timeout=self._config.shutdown_drain_timeout_seconds)
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._worker_task, timeout=self._config.shutdown_drain_timeout_seconds)
self._worker_task = None
if self._config.flush_on_shutdown:
self._force_flush_providers(timeout_seconds=self._config.export_timeout_seconds)
if self._otel_log_handler is not None:
logging.getLogger().removeHandler(self._otel_log_handler)
self._otel_log_handler = None
if self._logger_provider is not None:
self._logger_provider.shutdown()
self._logger_provider = None
if self._meter_provider is not None:
self._meter_provider.shutdown()
self._meter_provider = None
async def _enqueue(self, kind: str, payload: dict[str, Any]) -> None:
"""Enqueue one event, dropping when configured and queue is saturated.
Args:
kind: Event type identifier.
payload: Event data dict.
"""
if not self._enabled or self._worker_task is None:
return
event = TelemetryEvent(kind=kind, payload=payload)
if self._config.drop_on_queue_full:
try:
self._queue.put_nowait(event)
except asyncio.QueueFull:
logger.debug("Telemetry queue full; dropping event", extra={"kind": kind})
return
await self._queue.put(event)
def _enqueue_nowait(self, kind: str, payload: dict[str, Any]) -> None:
"""Synchronous best-effort queue enqueue used by sync code paths.
Args:
kind: Event type identifier.
payload: Event data dict.
"""
if not self._enabled or self._worker_task is None:
return
event = TelemetryEvent(kind=kind, payload=payload)
try:
self._queue.put_nowait(event)
except asyncio.QueueFull:
if not self._config.drop_on_queue_full:
logger.debug("Telemetry queue full; dropping sync event", extra={"kind": kind})
return
async def record_http_request(
self,
*,
method: str,
route_group: str,
status_code: int,
duration_seconds: float,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record one HTTP request metric event.
Args:
method: HTTP method (e.g. GET, POST).
route_group: Logical route group label.
status_code: HTTP response status code.
duration_seconds: Request duration in seconds.
server_id: Upstream server identifier or ``global``.
"""
await self._enqueue(
"http_request",
{
"method": method.upper(),
"route_group": route_group,
"status_code": status_code,
"duration_seconds": max(0.0, float(duration_seconds)),
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_upload_batch(self, *, server_id: str, file_count: int, bytes_total: int) -> None:
"""Record accepted upload batch metrics.
Args:
server_id: Server that received the upload.
file_count: Number of files in the batch.
bytes_total: Total bytes in the batch.
"""
await self._enqueue(
"upload_batch",
{
"server_id": server_id,
"file_count": max(0, int(file_count)),
"bytes_total": max(0, int(bytes_total)),
},
)
async def record_auth_rejection(
self,
*,
reason: str,
route_group: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record an auth rejection with bounded reason labels.
Args:
reason: Rejection reason label.
route_group: Logical route group label.
server_id: Upstream server identifier or ``global``.
"""
await self._enqueue(
"auth_rejection",
{
"reason": reason,
"route_group": route_group,
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_upstream_tool_call(
self,
*,
server_id: str,
tool_name: str,
result: str,
duration_seconds: float,
) -> None:
"""Record one upstream tool-call outcome and latency.
Args:
server_id: Target server identifier.
tool_name: Name of the tool called.
result: Outcome label (e.g. success, error).
duration_seconds: Call duration in seconds.
"""
await self._enqueue(
"upstream_tool_call",
{
"server_id": server_id,
"tool_name": tool_name,
"result": result,
"duration_seconds": max(0.0, float(duration_seconds)),
},
)
async def record_upstream_ping(
self,
*,
server_id: str,
result: str,
latency_ms: float,
state_before_probe: str,
) -> None:
"""Record active upstream ping outcome and latency.
Args:
server_id: Target server identifier.
result: Ping outcome label.
latency_ms: Ping round-trip time in milliseconds.
state_before_probe: Breaker state before the probe.
"""
await self._enqueue(
"upstream_ping",
{
"server_id": server_id,
"result": result,
"latency_ms": max(0.0, float(latency_ms)),
"state_before_probe": state_before_probe,
},
)
async def record_persistence_policy_transition(
self,
*,
action: str,
source: str,
policy: str,
configured_backend: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record one persistence-policy transition event.
Args:
action: Transition action label.
source: Transition trigger source.
policy: Policy name.
configured_backend: Originally configured backend.
server_id: Upstream server identifier or ``global``.
"""
await self._enqueue(
"persistence_policy",
{
"action": action,
"source": source,
"policy": policy,
"configured_backend": configured_backend,
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
def record_persistence_policy_transition_nowait(
self,
*,
action: str,
source: str,
policy: str,
configured_backend: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Synchronous best-effort variant for policy transitions.
Args:
action: Transition action label.
source: Transition trigger source.
policy: Policy name.
configured_backend: Originally configured backend.
"""
self._enqueue_nowait(
"persistence_policy",
{
"action": action,
"source": source,
"policy": policy,
"configured_backend": configured_backend,
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_nonce_operation(
self,
*,
operation: str,
result: str,
backend: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record reserve/consume nonce outcomes by backend.
Args:
operation: Nonce operation name.
result: Operation result label.
backend: Nonce store backend name.
"""
await self._enqueue(
"nonce_operation",
{
"operation": operation,
"result": result,
"backend": backend,
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_upload_credential_event(
self,
*,
operation: str,
result: str,
backend: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record signed upload credential issue/validation outcomes.
Args:
operation: Credential operation name.
result: Operation result label.
backend: Nonce store backend name.
"""
await self._enqueue(
"upload_credential",
{
"operation": operation,
"result": result,
"backend": backend,
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_artifact_download(
self,
*,
server_id: str,
result: str,
auth_mode: str,
duration_seconds: float,
size_bytes: int = 0,
) -> None:
"""Record artifact download attempts, latency, and served bytes.
Args:
server_id: Server identifier.
result: Outcome label (for example ``success`` or ``not_found``).
auth_mode: Access mode (for example ``signed_url`` or ``session_context``).
duration_seconds: Download handling duration in seconds.
size_bytes: Served bytes for successful downloads.
"""
await self._enqueue(
"artifact_download",
{
"server_id": (server_id or GLOBAL_SERVER_ID),
"result": result,
"auth_mode": auth_mode,
"duration_seconds": max(0.0, float(duration_seconds)),
"size_bytes": max(0, int(size_bytes)),
},
)
async def record_upload_failure(self, *, server_id: str, reason: str) -> None:
"""Record one upload endpoint failure reason.
Args:
server_id: Server identifier.
reason: Failure reason label.
"""
await self._enqueue(
"upload_failure",
{
"server_id": (server_id or GLOBAL_SERVER_ID),
"reason": reason,
},
)
async def record_request_rejection(
self,
*,
server_id: str,
route_group: str,
reason: str,
status_code: int,
) -> None:
"""Record one non-auth request rejection emitted by middleware.
Args:
server_id: Server identifier.
route_group: Normalized route group label.
reason: Rejection reason label.
status_code: HTTP status code returned for the rejection.
"""
await self._enqueue(
"request_rejection",
{
"server_id": (server_id or GLOBAL_SERVER_ID),
"route_group": route_group,
"reason": reason,
"status_code": int(status_code),
},
)
async def record_adapter_wiring_run(
self,
*,
result: str,
total_servers: int,
not_ready_servers: int,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record one adapter wiring pass summary.
Args:
result: Wiring pass outcome label.
total_servers: Total configured server count.
not_ready_servers: Servers not ready after wiring.
"""
await self._enqueue(
"adapter_wiring",
{
"result": result,
"total_servers": max(0, int(total_servers)),
"not_ready_servers": max(0, int(not_ready_servers)),
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_cleanup_cycle(
self,
*,
result: dict[str, int],
status: str,
server_id: str = GLOBAL_SERVER_ID,
) -> None:
"""Record cleanup cycle summary and removed-record counts.
Args:
result: Dict mapping bucket names to removed-record counts.
status: Cycle outcome label.
"""
await self._enqueue(
"cleanup_cycle",
{
"status": status,
"result": {key: int(value) for key, value in result.items()},
"server_id": (server_id or GLOBAL_SERVER_ID),
},
)
async def record_session_lifecycle(self, *, event: str, server_id: str) -> None:
"""Record session lifecycle transitions (create/revive/expire/tombstone).
Args:
event: Lifecycle event label.
server_id: Server the session belongs to.
"""
await self._enqueue(
"session_lifecycle",
{
"event": event,
"server_id": server_id,
},
)
async def record_tool_definition_drift(
self,
*,
server_id: str,
mode: str,
block_strategy: str,
outcome: str,
) -> None:
"""Record one tool-definition drift event.
Args:
server_id: Server identifier.
mode: Enforcement mode in effect (warn or block).
block_strategy: Effective block strategy.
outcome: Result label emitted by the adapter.
"""
await self._enqueue(
"tool_definition_drift",
{
"server_id": (server_id or GLOBAL_SERVER_ID),
"mode": mode,
"block_strategy": block_strategy,
"outcome": outcome,
},
)
async def set_circuit_breaker_state(self, *, server_id: str, state: str) -> None:
"""Record current circuit breaker state using synchronous gauge.
Args:
server_id: Server identifier.
state: Breaker state label (closed, half_open, open).
"""
await self._enqueue(
"breaker_state",
{
"server_id": server_id,
"state": state,
},
)
async def _drain_event_batch(self) -> list[TelemetryEvent]:
"""Wait for one event and drain additional queued events up to batch size.
Returns:
List of drained events. Empty list means periodic timeout occurred.
"""
try:
first_event = await asyncio.wait_for(self._queue.get(), timeout=self._config.periodic_flush_seconds)
except asyncio.TimeoutError:
if self._meter_provider is not None or self._logger_provider is not None:
self._force_flush_providers(timeout_seconds=self._config.export_timeout_seconds)
return []
drained_events = [first_event]
batch_limit = max(1, int(self._config.queue_batch_size))
while len(drained_events) < batch_limit:
try:
drained_events.append(self._queue.get_nowait())
except asyncio.QueueEmpty:
break
return drained_events
def _process_drained_events(self, drained_events: list[TelemetryEvent]) -> bool:
"""Process one drained event batch.
Args:
drained_events: Telemetry events drained from queue.
Returns:
True when a shutdown marker was seen in the batch.
"""
stop_requested = False
for event in drained_events:
if event.kind == "shutdown":
stop_requested = True
self._queue.task_done()
continue
try:
self._handle_event(event)
except Exception:
logger.exception("Failed to handle telemetry event", extra={"kind": event.kind})
finally:
self._queue.task_done()
return stop_requested
async def _worker_loop(self) -> None:
"""Drain queued telemetry events and write to OTel instruments."""
loop = asyncio.get_running_loop()
last_flush_at = loop.time()
while True:
drained_events = await self._drain_event_batch()
if not drained_events:
last_flush_at = loop.time()
continue
stop_requested = self._process_drained_events(drained_events)
now = loop.time()
if (now - last_flush_at) >= float(self._config.periodic_flush_seconds):
self._force_flush_providers(timeout_seconds=self._config.export_timeout_seconds)
last_flush_at = now
if stop_requested:
break
def _force_flush_providers(self, *, timeout_seconds: int) -> None:
"""Force-flush metric/log providers with bounded best-effort timeout.
Args:
timeout_seconds: Maximum flush wait time in seconds.
"""
timeout_millis = max(1, int(timeout_seconds)) * 1000
if self._logger_provider is not None:
with contextlib.suppress(Exception):
try:
self._logger_provider.force_flush(timeout_millis=timeout_millis)
except TypeError:
self._logger_provider.force_flush()
if self._meter_provider is not None:
with contextlib.suppress(Exception):
try:
self._meter_provider.force_flush(timeout_millis=timeout_millis)
except TypeError:
self._meter_provider.force_flush()
def _on_process_terminate(self) -> None:
"""Best-effort synchronous flush for interpreter termination paths."""
if not self._enabled:
return
while True:
try:
event = self._queue.get_nowait()
except asyncio.QueueEmpty:
break
if event.kind != "shutdown":
with contextlib.suppress(Exception):
self._handle_event(event)
self._queue.task_done()
if self._config.flush_on_terminate:
self._force_flush_providers(timeout_seconds=self._config.export_timeout_seconds)
def _handle_event(self, event: TelemetryEvent) -> None:
"""Delegate event dispatch to the event_dispatch module.
Args:
event: Telemetry event to handle.
"""
handle_event(manager=self, event=event)
__init__ ¶
__init__(*, config)
Initialize the telemetry manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | TelemetryConfig | Resolved telemetry configuration section. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
from_config classmethod ¶
from_config(resolved_config)
Construct telemetry manager from adapter config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resolved_config | AdapterConfig | Full adapter configuration. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
76 77 78 79 80 81 82 83 | |
record_adapter_wiring_run async ¶
record_adapter_wiring_run(*, result, total_servers, not_ready_servers, server_id=GLOBAL_SERVER_ID)
Record one adapter wiring pass summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result | str | Wiring pass outcome label. | required |
total_servers | int | Total configured server count. | required |
not_ready_servers | int | Servers not ready after wiring. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 | |
record_artifact_download async ¶
record_artifact_download(*, server_id, result, auth_mode, duration_seconds, size_bytes=0)
Record artifact download attempts, latency, and served bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
result | str | Outcome label (for example | required |
auth_mode | str | Access mode (for example | required |
duration_seconds | float | Download handling duration in seconds. | required |
size_bytes | int | Served bytes for successful downloads. | 0 |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_auth_rejection async ¶
record_auth_rejection(*, reason, route_group, server_id=GLOBAL_SERVER_ID)
Record an auth rejection with bounded reason labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason | str | Rejection reason label. | required |
route_group | str | Logical route group label. | required |
server_id | str | Upstream server identifier or | GLOBAL_SERVER_ID |
Source code in src/remote_mcp_adapter/telemetry/manager.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
record_cleanup_cycle async ¶
record_cleanup_cycle(*, result, status, server_id=GLOBAL_SERVER_ID)
Record cleanup cycle summary and removed-record counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result | dict[str, int] | Dict mapping bucket names to removed-record counts. | required |
status | str | Cycle outcome label. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | |
record_http_request async ¶
record_http_request(*, method, route_group, status_code, duration_seconds, server_id=GLOBAL_SERVER_ID)
Record one HTTP request metric event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method | str | HTTP method (e.g. GET, POST). | required |
route_group | str | Logical route group label. | required |
status_code | int | HTTP response status code. | required |
duration_seconds | float | Request duration in seconds. | required |
server_id | str | Upstream server identifier or | GLOBAL_SERVER_ID |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_nonce_operation async ¶
record_nonce_operation(*, operation, result, backend, server_id=GLOBAL_SERVER_ID)
Record reserve/consume nonce outcomes by backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation | str | Nonce operation name. | required |
result | str | Operation result label. | required |
backend | str | Nonce store backend name. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | |
record_persistence_policy_transition async ¶
record_persistence_policy_transition(*, action, source, policy, configured_backend, server_id=GLOBAL_SERVER_ID)
Record one persistence-policy transition event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action | str | Transition action label. | required |
source | str | Transition trigger source. | required |
policy | str | Policy name. | required |
configured_backend | str | Originally configured backend. | required |
server_id | str | Upstream server identifier or | GLOBAL_SERVER_ID |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_persistence_policy_transition_nowait ¶
record_persistence_policy_transition_nowait(*, action, source, policy, configured_backend, server_id=GLOBAL_SERVER_ID)
Synchronous best-effort variant for policy transitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action | str | Transition action label. | required |
source | str | Transition trigger source. | required |
policy | str | Policy name. | required |
configured_backend | str | Originally configured backend. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_request_rejection async ¶
record_request_rejection(*, server_id, route_group, reason, status_code)
Record one non-auth request rejection emitted by middleware.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
route_group | str | Normalized route group label. | required |
reason | str | Rejection reason label. | required |
status_code | int | HTTP status code returned for the rejection. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_session_lifecycle async ¶
record_session_lifecycle(*, event, server_id)
Record session lifecycle transitions (create/revive/expire/tombstone).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event | str | Lifecycle event label. | required |
server_id | str | Server the session belongs to. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
record_tool_definition_drift async ¶
record_tool_definition_drift(*, server_id, mode, block_strategy, outcome)
Record one tool-definition drift event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
mode | str | Enforcement mode in effect (warn or block). | required |
block_strategy | str | Effective block strategy. | required |
outcome | str | Result label emitted by the adapter. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_upload_batch async ¶
record_upload_batch(*, server_id, file_count, bytes_total)
Record accepted upload batch metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server that received the upload. | required |
file_count | int | Number of files in the batch. | required |
bytes_total | int | Total bytes in the batch. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
record_upload_credential_event async ¶
record_upload_credential_event(*, operation, result, backend, server_id=GLOBAL_SERVER_ID)
Record signed upload credential issue/validation outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation | str | Credential operation name. | required |
result | str | Operation result label. | required |
backend | str | Nonce store backend name. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
record_upload_failure async ¶
record_upload_failure(*, server_id, reason)
Record one upload endpoint failure reason.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
reason | str | Failure reason label. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
446 447 448 449 450 451 452 453 454 455 456 457 458 459 | |
record_upstream_ping async ¶
record_upstream_ping(*, server_id, result, latency_ms, state_before_probe)
Record active upstream ping outcome and latency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Target server identifier. | required |
result | str | Ping outcome label. | required |
latency_ms | float | Ping round-trip time in milliseconds. | required |
state_before_probe | str | Breaker state before the probe. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
record_upstream_tool_call async ¶
record_upstream_tool_call(*, server_id, tool_name, result, duration_seconds)
Record one upstream tool-call outcome and latency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Target server identifier. | required |
tool_name | str | Name of the tool called. | required |
result | str | Outcome label (e.g. success, error). | required |
duration_seconds | float | Call duration in seconds. | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
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 | |
set_circuit_breaker_state async ¶
set_circuit_breaker_state(*, server_id, state)
Record current circuit breaker state using synchronous gauge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
state | str | Breaker state label (closed, half_open, open). | required |
Source code in src/remote_mcp_adapter/telemetry/manager.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
shutdown async ¶
shutdown()
Stop worker and flush/shutdown telemetry providers.Source code in
src/remote_mcp_adapter/telemetry/manager.py126
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
async def shutdown(self) -> None:
"""Stop worker and flush/shutdown telemetry providers."""
if self._worker_task is None:
return
self._stop_event.set()
await self._queue.put(TelemetryEvent(kind="shutdown", payload={}))
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._queue.join(), timeout=self._config.shutdown_drain_timeout_seconds)
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._worker_task, timeout=self._config.shutdown_drain_timeout_seconds)
self._worker_task = None
if self._config.flush_on_shutdown:
self._force_flush_providers(timeout_seconds=self._config.export_timeout_seconds)
if self._otel_log_handler is not None:
logging.getLogger().removeHandler(self._otel_log_handler)
self._otel_log_handler = None
if self._logger_provider is not None:
self._logger_provider.shutdown()
self._logger_provider = None
if self._meter_provider is not None:
self._meter_provider.shutdown()
self._meter_provider = None
start async ¶
start()
Initialize OTel providers and start async event worker.Source code in
src/remote_mcp_adapter/telemetry/manager.py 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
async def start(self) -> None:
"""Initialize OTel providers and start async event worker."""
if not self._enabled:
return
if self._worker_task is not None:
return
try:
metrics_api, meter_provider, resource, meter = initialize_metrics_backend(config=self._config)
except Exception:
logger.exception("OpenTelemetry dependencies are unavailable; telemetry disabled at runtime")
self._enabled = False
return
self._metrics_api_module = metrics_api
self._meter_provider = meter_provider
for attribute_name, instrument in create_metric_instruments(meter=meter).items():
setattr(self, attribute_name, instrument)
if self._config.emit_logs:
try:
self._logger_provider, self._otel_log_handler = setup_log_export(
config=self._config,
resource=resource,
root_logger=logging.getLogger(),
)
except Exception:
logger.exception("Failed to initialize OpenTelemetry log exporter; continuing with metrics only")
self._logger_provider = None
self._otel_log_handler = None
self._worker_task = asyncio.create_task(self._worker_loop(), name="telemetry-worker")
if self._config.flush_on_terminate and not self._atexit_registered:
atexit.register(self._on_process_terminate)
self._atexit_registered = True
TelemetryEvent dataclass ¶
Queued telemetry event payload.Source code in
src/remote_mcp_adapter/telemetry/manager.py21
22
23
24
25
26
@dataclass(slots=True, frozen=True)
class TelemetryEvent:
"""Queued telemetry event payload."""
kind: str
payload: dict[str, Any]
remote_mcp_adapter.core.storage.store¶
This module manages sessions, uploads, artifacts, cleanup, quota enforcement, and related state transitions.
Session, upload, artifact, cleanup, and quota state management.
SessionStore ¶
Server-aware state manager for sessions, uploads, and artifacts.Source code in
src/remote_mcp_adapter/core/storage/store.py 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
class SessionStore:
"""Server-aware state manager for sessions, uploads, and artifacts."""
_STATE_LOCK_NAME = "session_store_state"
def __init__(
self,
config: AdapterConfig,
*,
state_repository: StateRepository | None = None,
lock_provider: LockProvider | None = None,
telemetry: TelemetryManager | None = None,
):
"""Initialize the session store.
Args:
config: Full adapter configuration.
state_repository: Optional persistence backend (defaults to in-memory).
lock_provider: Optional lock provider (defaults to in-memory).
telemetry: Optional telemetry recorder.
"""
self._config = config
self._storage_root = Path(config.storage.root).resolve()
self._uploads_root = self._storage_root / "uploads" / "sessions"
self._artifacts_root = self._storage_root / "artifacts" / "sessions"
self._state_repository = state_repository or InMemoryStateRepository()
self._lock_provider = lock_provider or InMemoryLockProvider()
self._telemetry = telemetry
self._ops = StoreOps(
config=config,
storage_root=self._storage_root,
upload_session_dir=self.upload_session_dir,
artifact_session_dir=self.artifact_session_dir,
)
@property
def storage_root(self) -> Path:
"""Resolved absolute path to the shared storage root directory."""
return self._storage_root
def upload_session_dir(self, session_id: str) -> Path:
"""Return per-session uploads directory path.
Args:
session_id: Session identifier.
"""
return self._uploads_root / session_id
def artifact_session_dir(self, session_id: str) -> Path:
"""Return per-session artifacts directory path.
Args:
session_id: Session identifier.
"""
return self._artifacts_root / session_id
@staticmethod
def _session_key(server_id: str, session_id: str) -> SessionKey:
"""Build the canonical (server_id, session_id) repository key.
Args:
server_id: Server identifier.
session_id: Session identifier.
"""
return (server_id, session_id)
@staticmethod
def _artifact_is_committed(record: ArtifactRecord) -> bool:
"""Return True when the artifact has been fully written and committed.
Args:
record: Artifact record to check.
"""
return record.visibility_state == "committed"
def replace_backends(self, *, state_repository: StateRepository, lock_provider: LockProvider) -> None:
"""Replace persistence backends for policy-driven runtime fallback.
Args:
state_repository: New state repository to use.
lock_provider: New lock provider to use.
"""
self._state_repository = state_repository
self._lock_provider = lock_provider
async def _persist_session_state(self, state: SessionState) -> None:
"""Persist one session state through the configured repository.
Args:
state: Session state to persist.
"""
key = self._session_key(state.server_id, state.session_id)
await self._state_repository.set_session(key, state)
async def ensure_session(self, server_id: str, session_id: str) -> SessionState:
"""Get or create state for ``(server_id, session_id)``.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Existing or newly created ``SessionState``.
Raises:
ToolError: If the maximum active sessions limit is exceeded.
"""
key = self._session_key(server_id, session_id)
now = now_ts()
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
tombstone = await self._state_repository.get_tombstone(key)
if tombstone is not None:
if tombstone.terminal_reason is not None:
if tombstone.expires_at > now:
raise TerminalSessionInvalidatedError(self._terminal_session_message(tombstone.terminal_reason))
await self._state_repository.pop_tombstone(key)
logger.info(
"Expired terminal session tombstone removed during session lookup",
extra={"server_id": server_id, "session_id": session_id},
)
elif tombstone.expires_at > now:
state = tombstone.state
state.touch(now)
await self._persist_session_state(state)
await self._state_repository.pop_tombstone(key)
logger.info(
"Session revived from tombstone",
extra={"server_id": server_id, "session_id": session_id},
)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(event="revived", server_id=server_id)
return state
else:
await self._state_repository.pop_tombstone(key)
logger.info(
"Expired tombstone removed during session lookup",
extra={"server_id": server_id, "session_id": session_id},
)
state = await self._state_repository.get_session(key)
if state is None:
max_active = self._config.sessions.max_active
active_sessions = await self._state_repository.session_count()
if max_active is not None and active_sessions >= max_active:
raise ToolError("Maximum active sessions exceeded.")
state = SessionState(server_id=server_id, session_id=session_id, created_at=now, last_accessed=now)
await self._persist_session_state(state)
logger.info(
"Session created",
extra={"server_id": server_id, "session_id": session_id},
)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(event="created", server_id=server_id)
return state
@staticmethod
def _terminal_session_message(reason: str) -> str:
"""Build the session-invalidated message shown to clients.
Args:
reason: Human-readable invalidation reason.
Returns:
Error message instructing the client to start a new session.
"""
return (
f"{reason} This adapter session was invalidated. "
"Start a new Mcp-Session-Id to accept the updated upstream state."
)
async def get_session(self, server_id: str, session_id: str) -> SessionState | None:
"""Return existing session state, if any.
Args:
server_id: Server identifier.
session_id: Session identifier.
"""
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
return await self._state_repository.get_session(self._session_key(server_id, session_id))
async def get_session_trust_context(self, server_id: str, session_id: str) -> SessionTrustContext | None:
"""Return the bound trust context for one session, if any.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Bound trust context or ``None`` when the session has not bound one.
"""
state = await self.get_session(server_id, session_id)
if state is None:
return None
return state.trust_context
async def get_terminal_session_reason(self, server_id: str, session_id: str) -> str | None:
"""Return the terminal invalidation reason for a session, if any.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Terminal invalidation reason or ``None``.
"""
key = self._session_key(server_id, session_id)
now = now_ts()
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
tombstone = await self._state_repository.get_tombstone(key)
if tombstone is None or tombstone.terminal_reason is None:
return None
if tombstone.expires_at <= now:
await self._state_repository.pop_tombstone(key)
logger.info(
"Expired terminal session tombstone removed during reason lookup",
extra={"server_id": server_id, "session_id": session_id},
)
return None
return tombstone.terminal_reason
async def invalidate_session(
self,
*,
server_id: str,
session_id: str,
reason: str,
) -> None:
"""Invalidate one adapter session and block reuse of the same session id.
Args:
server_id: Server identifier.
session_id: Session identifier.
reason: Human-readable invalidation reason.
"""
key = self._session_key(server_id, session_id)
now = now_ts()
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
existing_tombstone = await self._state_repository.get_tombstone(key)
if existing_tombstone is not None and existing_tombstone.terminal_reason == reason:
if existing_tombstone.expires_at > now:
return
await self._state_repository.pop_tombstone(key)
existing_tombstone = None
state = await self._state_repository.pop_session(key)
if state is None:
state = (
existing_tombstone.state
if existing_tombstone is not None
else SessionState(
server_id=server_id,
session_id=session_id,
created_at=now,
last_accessed=now,
)
)
await self._state_repository.pop_tombstone(key)
await self._ops.purge_state_files_async(state)
state.uploads.clear()
state.artifacts.clear()
state.in_flight = 0
state.touch(now)
expires_at = now + self._config.sessions.tombstone_ttl_seconds
await self._state_repository.set_tombstone(
key,
SessionTombstone(
state=state,
expires_at=expires_at,
terminal_reason=reason,
),
)
logger.warning(
"Session invalidated",
extra={"server_id": server_id, "session_id": session_id, "reason": reason},
)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(event="tool_definition_invalidated", server_id=server_id)
async def bind_or_validate_session_trust_context(
self,
*,
server_id: str,
session_id: str,
trust_context: SessionTrustContext,
) -> None:
"""Bind or validate the adapter trust context for one session.
Args:
server_id: Server identifier.
session_id: Session identifier.
trust_context: Request-derived trust context to enforce.
Raises:
SessionTrustContextMismatchError: If the request does not match the
trust context already bound to the session.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
existing = state.trust_context
if existing is None:
state.trust_context = trust_context
state.touch()
await self._persist_session_state(state)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(event="auth_context_bound", server_id=server_id)
return
if existing == trust_context:
return
raise SessionTrustContextMismatchError(self._session_trust_context_mismatch_message())
@staticmethod
def _session_trust_context_mismatch_message() -> str:
"""Build the client-facing error for a bound session-context mismatch.
Returns:
Error message instructing the client to reuse the same auth context
or start a new adapter session.
"""
return (
"This adapter session is already bound to a different authenticated request context. "
"Retry with the same adapter auth token that established the session, or start a new Mcp-Session-Id."
)
async def get_tool_definition_baseline(self, server_id: str, session_id: str) -> ToolDefinitionBaseline | None:
"""Return the pinned tool-definition baseline for one session, if present.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Pinned baseline or ``None`` when the session has not pinned one yet.
"""
state = await self.get_session(server_id, session_id)
if state is None:
return None
return state.tool_definition_baseline
async def set_tool_definition_baseline(
self,
server_id: str,
session_id: str,
baseline: ToolDefinitionBaseline,
) -> None:
"""Persist the pinned tool-definition baseline for one session.
Args:
server_id: Server identifier.
session_id: Session identifier.
baseline: Baseline to persist.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
state.tool_definition_baseline = baseline
state.touch()
await self._persist_session_state(state)
async def get_tool_definition_drift_summary(self, server_id: str, session_id: str) -> ToolDefinitionDriftSummary | None:
"""Return the last drift summary for one session, if present.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Stored drift summary or ``None``.
"""
state = await self.get_session(server_id, session_id)
if state is None:
return None
return state.tool_definition_drift_summary
async def set_tool_definition_drift_summary(
self,
server_id: str,
session_id: str,
summary: ToolDefinitionDriftSummary,
) -> None:
"""Persist the last tool-definition drift summary for one session.
Args:
server_id: Server identifier.
session_id: Session identifier.
summary: Drift summary to persist.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
state.tool_definition_drift_summary = summary
state.touch()
await self._persist_session_state(state)
async def clear_tool_definition_drift_summary(self, server_id: str, session_id: str) -> None:
"""Clear any persisted tool-definition drift summary for one session.
Args:
server_id: Server identifier.
session_id: Session identifier.
"""
state = await self.get_session(server_id, session_id)
if state is None:
return
async with state.lock:
if state.tool_definition_drift_summary is None:
return
state.tool_definition_drift_summary = None
state.touch()
await self._persist_session_state(state)
async def touch_tool_activity(self, server_id: str, session_id: str) -> None:
"""Touch session activity for tool-call related operations.
Args:
server_id: Server identifier.
session_id: Session identifier.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
state.touch()
await self._persist_session_state(state)
async def begin_in_flight(self, server_id: str, session_id: str) -> None:
"""Increment in-flight counter for cleanup decisions.
Args:
server_id: Server identifier.
session_id: Session identifier.
Raises:
ToolError: If the per-session in-flight limit is exceeded.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
max_in_flight = self._config.sessions.max_in_flight_per_session
if max_in_flight is not None and state.in_flight >= max_in_flight:
raise ToolError("Maximum in-flight requests exceeded for session.")
state.in_flight += 1
state.touch()
await self._persist_session_state(state)
async def end_in_flight(self, server_id: str, session_id: str) -> None:
"""Decrement in-flight counter for cleanup decisions.
Args:
server_id: Server identifier.
session_id: Session identifier.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
state.in_flight = max(0, state.in_flight - 1)
state.touch()
await self._persist_session_state(state)
async def allocate_upload_path(
self,
*,
server_id: str,
session_id: str,
filename: str,
upload_id: str | None = None,
) -> tuple[str, Path, str]:
"""Allocate storage path for a staged upload.
Args:
server_id: Server identifier.
session_id: Session identifier.
filename: Client-supplied filename.
upload_id: Optional explicit upload ID.
Returns:
Tuple of ``(upload_id, abs_path, rel_path)``.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
normalized_upload_id = upload_id or uuid4().hex
safe_name = sanitize_filename(filename, default_name="upload")
upload_dir = self.upload_session_dir(session_id) / normalized_upload_id
abs_path = ensure_within_base(upload_dir / safe_name, self._storage_root)
await asyncio.to_thread(abs_path.parent.mkdir, parents=True, exist_ok=True)
rel_path = abs_path.relative_to(self._storage_root).as_posix()
state.touch()
await self._persist_session_state(state)
return normalized_upload_id, abs_path, rel_path
async def register_upload(
self,
*,
server_id: str,
session_id: str,
upload_id: str,
abs_path: Path,
mime_type: str | None = None,
sha256: str | None = None,
) -> UploadRecord:
"""Register a completed upload in session state.
Args:
server_id: Server identifier.
session_id: Session identifier.
upload_id: Unique upload identifier.
abs_path: Absolute filesystem path of the uploaded file.
mime_type: Optional MIME type override.
sha256: Optional pre-computed SHA-256 digest.
Returns:
The registered ``UploadRecord``.
Raises:
FileNotFoundError: If the upload file does not exist.
ToolError: If quota limits are exceeded.
"""
state = await self.ensure_session(server_id, session_id)
abs_path = ensure_within_base(abs_path, self._storage_root)
if not await asyncio.to_thread(abs_path.exists):
raise FileNotFoundError(f"Upload file not found: {abs_path}")
size_bytes = await asyncio.to_thread(_file_size_bytes, abs_path)
now = now_ts()
digest = sha256 or await asyncio.to_thread(sha256_file, abs_path)
guessed_mime = mime_type or mimetypes.guess_type(abs_path.name)[0] or "application/octet-stream"
record = UploadRecord(
server_id=server_id,
session_id=session_id,
upload_id=upload_id,
filename=abs_path.name,
abs_path=abs_path,
rel_path=abs_path.relative_to(self._storage_root).as_posix(),
mime_type=guessed_mime,
size_bytes=size_bytes,
sha256=digest,
created_at=now,
last_accessed=now,
last_updated=now,
)
async with state.lock:
try:
self._ops.enforce_session_quota(state, incoming_bytes=size_bytes)
await self._ops.enforce_global_storage_quota()
except ToolError:
await self._persist_session_state(state)
await asyncio.to_thread(abs_path.unlink, missing_ok=True)
with contextlib.suppress(OSError):
await asyncio.to_thread(abs_path.parent.rmdir)
raise
state.uploads[upload_id] = record
state.touch(now)
await self._persist_session_state(state)
return record
async def resolve_upload_handle(
self,
*,
server_id: str,
session_id: str,
handle: str,
uri_scheme: str = "upload://",
) -> UploadRecord:
"""Resolve and touch an ``upload://`` handle for the current session.
Args:
server_id: Server identifier.
session_id: Session identifier.
handle: Upload handle string.
uri_scheme: URI scheme prefix for parsing.
Returns:
The resolved ``UploadRecord``.
Raises:
ValueError: If the handle session does not match.
KeyError: If the upload ID is unknown.
"""
match = UPLOAD_HANDLE_RE.fullmatch(handle)
if match:
handle_session_id, upload_id = match.group(1), match.group(2)
else:
handle_session_id, upload_id = parse_session_scoped_uri(handle, uri_scheme)
if handle_session_id != session_id:
raise ValueError("Upload handle session mismatch.")
state = await self.ensure_session(server_id, session_id)
async with state.lock:
record = state.uploads.get(upload_id)
if record is None:
raise KeyError(f"Unknown upload handle id: {upload_id}")
record.touch()
state.touch(record.last_accessed)
await self._persist_session_state(state)
return record
async def remove_uploads(
self,
*,
server_id: str,
session_id: str,
upload_ids: list[str],
) -> int:
"""Remove multiple upload records/files and persist state once.
Args:
server_id: Server identifier.
session_id: Session identifier.
upload_ids: List of upload IDs to remove.
Returns:
Number of uploads actually removed.
"""
if not upload_ids:
return 0
state = await self.ensure_session(server_id, session_id)
removed_count = 0
async with state.lock:
for upload_id in upload_ids:
removed, _ = await self._ops.remove_upload_record_async(state, upload_id)
if removed:
removed_count += 1
if removed_count:
state.touch()
await self._persist_session_state(state)
if removed_count:
await self._ops.purge_empty_session_dirs_async(session_id)
logger.info(
"Removed upload batch",
extra={"server_id": server_id, "session_id": session_id, "removed_count": removed_count},
)
return removed_count
async def allocate_artifact_path(
self,
*,
server_id: str,
session_id: str,
filename: str | None,
default_ext: str | None = None,
artifact_id: str | None = None,
tool_name: str | None = None,
expose_as_resource: bool = True,
) -> tuple[str, Path, str]:
"""Allocate and pre-register path for an artifact output file.
Args:
server_id: Server identifier.
session_id: Session identifier.
filename: Optional client-supplied filename.
default_ext: Fallback file extension.
artifact_id: Optional explicit artifact ID.
tool_name: Name of the tool producing this artifact.
expose_as_resource: Whether to expose the artifact as an MCP resource.
Returns:
Tuple of ``(artifact_id, abs_path, rel_path)``.
Raises:
ToolError: If the per-session artifact limit is exceeded.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
max_per_session = self._config.artifacts.max_per_session
if max_per_session is not None and len(state.artifacts) >= max_per_session:
raise ToolError("Maximum artifacts per session exceeded.")
normalized_artifact_id = artifact_id or uuid4().hex
default_name = f"artifact-{normalized_artifact_id}"
safe_name = sanitize_filename(filename, default_name=default_name, default_ext=default_ext)
artifact_dir = self.artifact_session_dir(session_id) / normalized_artifact_id
abs_path = ensure_within_base(artifact_dir / safe_name, self._storage_root)
await asyncio.to_thread(abs_path.parent.mkdir, parents=True, exist_ok=True)
rel_path = abs_path.relative_to(self._storage_root).as_posix()
now = now_ts()
record = ArtifactRecord(
server_id=server_id,
session_id=session_id,
artifact_id=normalized_artifact_id,
filename=safe_name,
abs_path=abs_path,
rel_path=rel_path,
mime_type=mimetypes.guess_type(safe_name)[0] or "application/octet-stream",
size_bytes=0,
created_at=now,
last_accessed=now,
last_updated=now,
tool_name=tool_name,
expose_as_resource=expose_as_resource,
visibility_state="pending",
)
state.artifacts[normalized_artifact_id] = record
state.touch(now)
await self._persist_session_state(state)
return normalized_artifact_id, abs_path, rel_path
async def finalize_artifact(
self,
*,
server_id: str,
session_id: str,
artifact_id: str,
mime_type: str | None = None,
) -> ArtifactRecord:
"""Finalize artifact metadata after file materialization.
Args:
server_id: Server identifier.
session_id: Session identifier.
artifact_id: Artifact to finalize.
mime_type: Optional MIME type override.
Returns:
The finalized ``ArtifactRecord``.
Raises:
KeyError: If the artifact ID is unknown.
FileNotFoundError: If the artifact file is missing.
ToolError: If quota limits are exceeded after finalization.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
record = state.artifacts.get(artifact_id)
if record is None:
raise KeyError(f"Unknown artifact id: {artifact_id}")
if not await asyncio.to_thread(record.abs_path.exists):
raise FileNotFoundError(f"Artifact file missing: {record.abs_path}")
resolved_mime_type = mime_type or mimetypes.guess_type(record.filename)[0] or record.mime_type
# If upstream wrote to a placeholder name (e.g., "artifact"), attach a
# stable extension from detected MIME so URIs and downloads are meaningful.
if not Path(record.filename).suffix:
inferred_ext = _preferred_extension_for_mime(resolved_mime_type)
if inferred_ext:
candidate_abs_path = ensure_within_base(
record.abs_path.with_name(f"{record.filename}{inferred_ext}"),
self._storage_root,
)
candidate_exists = await asyncio.to_thread(candidate_abs_path.exists)
if not candidate_exists:
await asyncio.to_thread(record.abs_path.rename, candidate_abs_path)
record.abs_path = candidate_abs_path
record.filename = candidate_abs_path.name
record.rel_path = candidate_abs_path.relative_to(self._storage_root).as_posix()
previous_size = record.size_bytes
record.size_bytes = await asyncio.to_thread(_file_size_bytes, record.abs_path)
growth_bytes = max(0, record.size_bytes - previous_size)
try:
self._ops.enforce_session_quota(state, incoming_bytes=growth_bytes)
await self._ops.enforce_global_storage_quota()
except ToolError:
self._ops.remove_artifact_record(state, artifact_id)
await self._persist_session_state(state)
raise
record.mime_type = resolved_mime_type
record.visibility_state = "committed"
record.touch()
state.touch(record.last_accessed)
await self._persist_session_state(state)
return record
async def get_artifact(
self,
*,
server_id: str,
session_id: str,
artifact_id: str,
include_pending: bool = False,
) -> ArtifactRecord:
"""Resolve and touch one artifact record for a session.
Args:
server_id: Server identifier.
session_id: Session identifier.
artifact_id: Artifact to resolve.
include_pending: When True, return artifacts not yet committed.
Returns:
The resolved ``ArtifactRecord``.
Raises:
KeyError: If the artifact ID is unknown or not committed.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
record = state.artifacts.get(artifact_id)
if record is None:
raise KeyError(f"Unknown artifact id: {artifact_id}")
if not include_pending and not self._artifact_is_committed(record):
raise KeyError(f"Unknown artifact id: {artifact_id}")
record.touch()
state.touch(record.last_accessed)
await self._persist_session_state(state)
return record
async def list_artifacts(
self,
*,
server_id: str,
session_id: str,
touch: bool = False,
) -> list[ArtifactRecord]:
"""List artifact records for a session.
Args:
server_id: Server identifier.
session_id: Session identifier.
touch: When True, update access timestamps.
Returns:
List of committed ``ArtifactRecord`` instances.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
records = [record for record in state.artifacts.values() if self._artifact_is_committed(record)]
if touch:
now = now_ts()
for record in records:
record.touch(now)
state.touch(now)
await self._persist_session_state(state)
return records
async def resolve_artifact_uri(
self,
*,
server_id: str,
session_id: str,
artifact_uri: str,
uri_scheme: str = "artifact://",
) -> ArtifactRecord:
"""Resolve and touch an ``artifact://`` URI for the current session.
Args:
server_id: Server identifier.
session_id: Session identifier.
artifact_uri: Artifact URI string.
uri_scheme: URI scheme prefix for parsing.
Returns:
The resolved ``ArtifactRecord``.
Raises:
ValueError: If the URI session does not match.
"""
match = ARTIFACT_URI_RE.fullmatch(artifact_uri)
if match:
uri_session_id, artifact_id = match.group(1), match.group(2)
else:
uri_session_id, artifact_id = parse_session_scoped_uri(artifact_uri, uri_scheme)
if uri_session_id != session_id:
raise ValueError("Artifact URI session mismatch.")
return await self.get_artifact(server_id=server_id, session_id=session_id, artifact_id=artifact_id)
async def get_session_snapshot(self, server_id: str, session_id: str) -> dict[str, object]:
"""Return lightweight session metadata for diagnostics.
Args:
server_id: Server identifier.
session_id: Session identifier.
Returns:
Dict with session timestamps, counts, and in-flight status.
"""
state = await self.ensure_session(server_id, session_id)
async with state.lock:
return {
"server_id": state.server_id,
"session_id": state.session_id,
"created_at": state.created_at,
"last_accessed": state.last_accessed,
"created_at_iso": datetime.fromtimestamp(state.created_at, tz=timezone.utc).isoformat(),
"last_accessed_iso": datetime.fromtimestamp(state.last_accessed, tz=timezone.utc).isoformat(),
"uploads_count": len(state.uploads),
"artifacts_count": len(state.artifacts),
"in_flight": state.in_flight,
}
async def iter_sessions(self) -> list[SessionState]:
"""Return a snapshot list of all active session states."""
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
session_items = await self._state_repository.list_session_items()
return [state for _, state in session_items]
async def _tombstone_or_delete_session(self, key: SessionKey, state: SessionState, now: float) -> str:
"""Apply configured idle-expiry behavior for one session.
Args:
key: Session repository key.
state: Session state to tombstone or delete.
now: Current epoch timestamp.
Returns:
``'tombstoned'`` or ``'deleted'``.
"""
if self._config.sessions.allow_revival:
expires_at = now + self._config.sessions.tombstone_ttl_seconds
await self._state_repository.set_tombstone(key, SessionTombstone(state=state, expires_at=expires_at))
return "tombstoned"
await self._ops.purge_state_files_async(state)
return "deleted"
async def cleanup_once(self) -> dict[str, int]:
"""Run one cleanup cycle for TTL expiry and idle session management.
Returns:
Dict with counts of expired sessions, removed uploads/artifacts,
tombstones, and orphan files.
"""
now = now_ts()
removed_uploads = 0
removed_artifacts = 0
expired_sessions = 0
tombstoned_sessions = 0
removed_tombstones = 0
removed_dangling_upload_records = 0
removed_dangling_artifact_records = 0
removed_orphan_files = 0
referenced_paths: set[str] = set()
pending_artifact_cutoff = now - self._config.storage.orphan_sweeper_grace_seconds
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
session_items = list(await self._state_repository.list_session_items())
for key, tombstone in list(await self._state_repository.list_tombstone_items()):
if tombstone.expires_at <= now:
await self._state_repository.pop_tombstone(key)
await self._ops.purge_state_files_async(tombstone.state)
removed_tombstones += 1
logger.info(
"Expired tombstone purged",
extra={
"server_id": tombstone.state.server_id,
"session_id": tombstone.state.session_id,
"expires_at": tombstone.expires_at,
},
)
else:
for upload in tombstone.state.uploads.values():
referenced_paths.add(str(upload.abs_path.resolve()))
for artifact in tombstone.state.artifacts.values():
referenced_paths.add(str(artifact.abs_path.resolve()))
for key, state in session_items:
async with state.lock:
state_changed = False
session_removed = False
for upload in list(state.uploads.values()):
if not await asyncio.to_thread(upload.abs_path.exists):
removed, _ = await self._ops.remove_upload_record_async(state, upload.upload_id)
if removed:
removed_dangling_upload_records += 1
state_changed = True
for artifact in list(state.artifacts.values()):
is_pending_stale = (
artifact.visibility_state != "committed" and artifact.last_updated < pending_artifact_cutoff
)
if is_pending_stale or not await asyncio.to_thread(artifact.abs_path.exists):
removed, _ = await self._ops.remove_artifact_record_async(state, artifact.artifact_id)
if removed:
removed_dangling_artifact_records += 1
state_changed = True
upload_ttl = self._config.uploads.ttl_seconds
if upload_ttl is not None:
cutoff = now - upload_ttl
for upload in list(state.uploads.values()):
if upload.last_accessed < cutoff:
removed, _ = await self._ops.remove_upload_record_async(state, upload.upload_id)
if removed:
removed_uploads += 1
state_changed = True
artifact_ttl = self._config.artifacts.ttl_seconds
if artifact_ttl is not None:
cutoff = now - artifact_ttl
for artifact in list(state.artifacts.values()):
if artifact.last_accessed < cutoff:
removed, _ = await self._ops.remove_artifact_record_async(state, artifact.artifact_id)
if removed:
removed_artifacts += 1
state_changed = True
await self._ops.purge_empty_session_dirs_async(state.session_id)
idle_ttl = self._config.sessions.idle_ttl_seconds
if idle_ttl is not None and state.in_flight == 0 and (now - state.last_accessed) > idle_ttl:
await self._state_repository.pop_session(key)
outcome = await self._tombstone_or_delete_session(key, state, now)
session_removed = True
if outcome == "tombstoned":
tombstoned_sessions += 1
logger.info(
"Session idle-expired and tombstoned",
extra={"server_id": state.server_id, "session_id": state.session_id},
)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(
event="idle_expired_tombstoned",
server_id=state.server_id,
)
else:
expired_sessions += 1
logger.info(
"Session idle-expired and deleted",
extra={"server_id": state.server_id, "session_id": state.session_id},
)
if self._telemetry is not None:
await self._telemetry.record_session_lifecycle(
event="idle_expired_deleted",
server_id=state.server_id,
)
else:
for upload in state.uploads.values():
referenced_paths.add(str(upload.abs_path.resolve()))
for artifact in state.artifacts.values():
referenced_paths.add(str(artifact.abs_path.resolve()))
if state_changed and not session_removed:
await self._persist_session_state(state)
if self._config.storage.orphan_sweeper_enabled:
orphan_cutoff = now - self._config.storage.orphan_sweeper_grace_seconds
removed_orphan_files += await self._ops.purge_orphan_files_async(
root=self._uploads_root,
referenced_paths=referenced_paths,
older_than_epoch=orphan_cutoff,
)
removed_orphan_files += await self._ops.purge_orphan_files_async(
root=self._artifacts_root,
referenced_paths=referenced_paths,
older_than_epoch=orphan_cutoff,
)
return {
"expired_sessions": expired_sessions,
"tombstoned_sessions": tombstoned_sessions,
"removed_tombstones": removed_tombstones,
"removed_uploads": removed_uploads,
"removed_artifacts": removed_artifacts,
"removed_dangling_upload_records": removed_dangling_upload_records,
"removed_dangling_artifact_records": removed_dangling_artifact_records,
"removed_orphan_files": removed_orphan_files,
}
async def shutdown(self, mode: Literal["keep_files", "delete_files"] = "keep_files") -> None:
"""Release in-memory state and optionally delete storage directories.
Args:
mode: ``'keep_files'`` preserves disk data; ``'delete_files'`` purges
all upload and artifact files.
"""
if mode == "keep_files":
return
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
session_states, tombstones = await self._state_repository.drain()
if mode == "delete_files":
for state in session_states:
await self._ops.purge_state_files_async(state)
for tombstone in tombstones:
await self._ops.purge_state_files_async(tombstone.state)
await asyncio.to_thread(shutil.rmtree, self._uploads_root, True)
await asyncio.to_thread(shutil.rmtree, self._artifacts_root, True)
__init__ ¶
__init__(config, *, state_repository=None, lock_provider=None, telemetry=None)
Initialize the session store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | AdapterConfig | Full adapter configuration. | required |
state_repository | StateRepository | None | Optional persistence backend (defaults to in-memory). | None |
lock_provider | LockProvider | None | Optional lock provider (defaults to in-memory). | None |
telemetry | TelemetryManager | None | Optional telemetry recorder. | None |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
allocate_artifact_path async ¶
allocate_artifact_path(*, server_id, session_id, filename, default_ext=None, artifact_id=None, tool_name=None, expose_as_resource=True)
Allocate and pre-register path for an artifact output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
filename | str | None | Optional client-supplied filename. | required |
default_ext | str | None | Fallback file extension. | None |
artifact_id | str | None | Optional explicit artifact ID. | None |
tool_name | str | None | Name of the tool producing this artifact. | None |
expose_as_resource | bool | Whether to expose the artifact as an MCP resource. | True |
Returns:
| Type | Description |
|---|---|
tuple[str, Path, str] | Tuple of |
Raises:
| Type | Description |
|---|---|
ToolError | If the per-session artifact limit is exceeded. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
allocate_upload_path async ¶
allocate_upload_path(*, server_id, session_id, filename, upload_id=None)
Allocate storage path for a staged upload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
filename | str | Client-supplied filename. | required |
upload_id | str | None | Optional explicit upload ID. | None |
Returns:
| Type | Description |
|---|---|
tuple[str, Path, str] | Tuple of |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
artifact_session_dir ¶
artifact_session_dir(session_id)
Return per-session artifacts directory path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
114 115 116 117 118 119 120 | |
begin_in_flight async ¶
begin_in_flight(server_id, session_id)
Increment in-flight counter for cleanup decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Raises:
| Type | Description |
|---|---|
ToolError | If the per-session in-flight limit is exceeded. |
Source code in src/remote_mcp_adapter/core/storage/store.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | |
bind_or_validate_session_trust_context async ¶
bind_or_validate_session_trust_context(*, server_id, session_id, trust_context)
Bind or validate the adapter trust context for one session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
trust_context | SessionTrustContext | Request-derived trust context to enforce. | required |
Raises:
| Type | Description |
|---|---|
SessionTrustContextMismatchError | If the request does not match the trust context already bound to the session. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
cleanup_once async ¶
cleanup_once()
Run one cleanup cycle for TTL expiry and idle session management.
Returns:
| Type | Description |
|---|---|
dict[str, int] | Dict with counts of expired sessions, removed uploads/artifacts, |
dict[str, int] | tombstones, and orphan files. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 | |
clear_tool_definition_drift_summary async ¶
clear_tool_definition_drift_summary(server_id, session_id)
Clear any persisted tool-definition drift summary for one session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | |
end_in_flight async ¶
end_in_flight(server_id, session_id)
Decrement in-flight counter for cleanup decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
506 507 508 509 510 511 512 513 514 515 516 517 | |
ensure_session async ¶
ensure_session(server_id, session_id)
Get or create state for (server_id, session_id).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
SessionState | Existing or newly created |
Raises:
| Type | Description |
|---|---|
ToolError | If the maximum active sessions limit is exceeded. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
finalize_artifact async ¶
finalize_artifact(*, server_id, session_id, artifact_id, mime_type=None)
Finalize artifact metadata after file materialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
artifact_id | str | Artifact to finalize. | required |
mime_type | str | None | Optional MIME type override. | None |
Returns:
| Type | Description |
|---|---|
ArtifactRecord | The finalized |
Raises:
| Type | Description |
|---|---|
KeyError | If the artifact ID is unknown. |
FileNotFoundError | If the artifact file is missing. |
ToolError | If quota limits are exceeded after finalization. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
get_artifact async ¶
get_artifact(*, server_id, session_id, artifact_id, include_pending=False)
Resolve and touch one artifact record for a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
artifact_id | str | Artifact to resolve. | required |
include_pending | bool | When True, return artifacts not yet committed. | False |
Returns:
| Type | Description |
|---|---|
ArtifactRecord | The resolved |
Raises:
| Type | Description |
|---|---|
KeyError | If the artifact ID is unknown or not committed. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
get_session async ¶
get_session(server_id, session_id)
Return existing session state, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
236 237 238 239 240 241 242 243 244 | |
get_session_snapshot async ¶
get_session_snapshot(server_id, session_id)
Return lightweight session metadata for diagnostics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
dict[str, object] | Dict with session timestamps, counts, and in-flight status. |
Source code in src/remote_mcp_adapter/core/storage/store.py
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 | |
get_session_trust_context async ¶
get_session_trust_context(server_id, session_id)
Return the bound trust context for one session, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
SessionTrustContext | None | Bound trust context or |
Source code in src/remote_mcp_adapter/core/storage/store.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
get_terminal_session_reason async ¶
get_terminal_session_reason(server_id, session_id)
Return the terminal invalidation reason for a session, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
str | None | Terminal invalidation reason or |
Source code in src/remote_mcp_adapter/core/storage/store.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
get_tool_definition_baseline async ¶
get_tool_definition_baseline(server_id, session_id)
Return the pinned tool-definition baseline for one session, if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
ToolDefinitionBaseline | None | Pinned baseline or |
Source code in src/remote_mcp_adapter/core/storage/store.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
get_tool_definition_drift_summary async ¶
get_tool_definition_drift_summary(server_id, session_id)
Return the last drift summary for one session, if present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Returns:
| Type | Description |
|---|---|
ToolDefinitionDriftSummary | None | Stored drift summary or |
Source code in src/remote_mcp_adapter/core/storage/store.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
invalidate_session async ¶
invalidate_session(*, server_id, session_id, reason)
Invalidate one adapter session and block reuse of the same session id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
reason | str | Human-readable invalidation reason. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
iter_sessions async ¶
iter_sessions()
Return a snapshot list of all active session states.Source code in
src/remote_mcp_adapter/core/storage/store.py938
939
940
941
942
async def iter_sessions(self) -> list[SessionState]:
"""Return a snapshot list of all active session states."""
async with self._lock_provider.hold(self._STATE_LOCK_NAME):
session_items = await self._state_repository.list_session_items()
return [state for _, state in session_items]
list_artifacts async ¶
list_artifacts(*, server_id, session_id, touch=False)
List artifact records for a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
touch | bool | When True, update access timestamps. | False |
Returns:
| Type | Description |
|---|---|
list[ArtifactRecord] | List of committed |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
register_upload async ¶
register_upload(*, server_id, session_id, upload_id, abs_path, mime_type=None, sha256=None)
Register a completed upload in session state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
upload_id | str | Unique upload identifier. | required |
abs_path | Path | Absolute filesystem path of the uploaded file. | required |
mime_type | str | None | Optional MIME type override. | None |
sha256 | str | None | Optional pre-computed SHA-256 digest. | None |
Returns:
| Type | Description |
|---|---|
UploadRecord | The registered |
Raises:
| Type | Description |
|---|---|
FileNotFoundError | If the upload file does not exist. |
ToolError | If quota limits are exceeded. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
remove_uploads async ¶
remove_uploads(*, server_id, session_id, upload_ids)
Remove multiple upload records/files and persist state once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
upload_ids | list[str] | List of upload IDs to remove. | required |
Returns:
| Type | Description |
|---|---|
int | Number of uploads actually removed. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
replace_backends ¶
replace_backends(*, state_repository, lock_provider)
Replace persistence backends for policy-driven runtime fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_repository | StateRepository | New state repository to use. | required |
lock_provider | LockProvider | New lock provider to use. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
141 142 143 144 145 146 147 148 149 | |
resolve_artifact_uri async ¶
resolve_artifact_uri(*, server_id, session_id, artifact_uri, uri_scheme='artifact://')
Resolve and touch an artifact:// URI for the current session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
artifact_uri | str | Artifact URI string. | required |
uri_scheme | str | URI scheme prefix for parsing. | 'artifact://' |
Returns:
| Type | Description |
|---|---|
ArtifactRecord | The resolved |
Raises:
| Type | Description |
|---|---|
ValueError | If the URI session does not match. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
resolve_upload_handle async ¶
resolve_upload_handle(*, server_id, session_id, handle, uri_scheme='upload://')
Resolve and touch an upload:// handle for the current session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
handle | str | Upload handle string. | required |
uri_scheme | str | URI scheme prefix for parsing. | 'upload://' |
Returns:
| Type | Description |
|---|---|
UploadRecord | The resolved |
Raises:
| Type | Description |
|---|---|
ValueError | If the handle session does not match. |
KeyError | If the upload ID is unknown. |
Source code in src/remote_mcp_adapter/core/storage/store.py
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 | |
set_tool_definition_baseline async ¶
set_tool_definition_baseline(server_id, session_id, baseline)
Persist the pinned tool-definition baseline for one session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
baseline | ToolDefinitionBaseline | Baseline to persist. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
set_tool_definition_drift_summary async ¶
set_tool_definition_drift_summary(server_id, session_id, summary)
Persist the last tool-definition drift summary for one session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
summary | ToolDefinitionDriftSummary | Drift summary to persist. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
shutdown async ¶
shutdown(mode='keep_files')
Release in-memory state and optionally delete storage directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode | Literal['keep_files', 'delete_files'] |
| 'keep_files' |
Source code in src/remote_mcp_adapter/core/storage/store.py
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 | |
touch_tool_activity async ¶
touch_tool_activity(server_id, session_id)
Touch session activity for tool-call related operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_id | str | Server identifier. | required |
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
475 476 477 478 479 480 481 482 483 484 485 | |
upload_session_dir ¶
upload_session_dir(session_id)
Return per-session uploads directory path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id | str | Session identifier. | required |
Source code in src/remote_mcp_adapter/core/storage/store.py
106 107 108 109 110 111 112 | |
Next steps¶
- Previous topic: Public API - user-facing modules and entry points.
- See also: Troubleshooting - common failures and practical fixes.