Skip to content

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.py
224
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.py
234
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.py
240
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:

NameTypeDescriptionDefault
readybool

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
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

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:

NameTypeDescriptionDefault
timeout_secondsint | 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
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)

close_all async

close_all()

Close all cached clients for this server.

Source code in src/remote_mcp_adapter/proxy/factory.py
208
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:

TypeDescription
Client

Cached or freshly created upstream Client.

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
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

reset_cached_clients async

reset_cached_clients(*, reason)

Close and clear all cached clients for reconnect/reinitialize flow.

Parameters:

NameTypeDescriptionDefault
reasonstr

Human-readable reason for the reset.

required

Returns:

TypeDescription
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
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)

build_proxy_map

build_proxy_map(config, session_store=None, *, telemetry=None)

Build per-server proxy objects keyed by server id.

Parameters:

NameTypeDescriptionDefault
configAdapterConfig

Full adapter configuration.

required
session_storeSessionStore | None

Optional session store for session-aware client caching.

None
telemetryAny | None

Optional telemetry recorder for server transforms.

None

Returns:

TypeDescription
dict[str, ProxyMount]

Dict mapping server IDs to ProxyMount instances.

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
def build_proxy_map(
    config: AdapterConfig,
    session_store: SessionStore | None = None,
    *,
    telemetry: Any | None = None,
) -> dict[str, ProxyMount]:
    """Build per-server proxy objects keyed by server id.

    Args:
        config: Full adapter configuration.
        session_store: Optional session store for session-aware client caching.
        telemetry: Optional telemetry recorder for server transforms.

    Returns:
        Dict mapping server IDs to ``ProxyMount`` instances.
    """
    proxy_map: dict[str, ProxyMount] = {}
    for server in config.servers:
        timeout_seconds = _resolve_timeout_seconds(config, server)
        pinning_policy = resolve_tool_definition_pinning_policy(config=config, server=server)
        pinning_active = pinning_policy.enabled and session_store is not None
        wiring_readiness = ServerWiringReadiness()
        client_registry = SessionClientRegistry(
            server=server,
            session_store=session_store,
            default_timeout_seconds=timeout_seconds,
            session_termination_retries=config.sessions.upstream_session_termination_retries,
            metadata_cache_ttl_seconds=config.core.upstream_metadata_cache_ttl_seconds,
            bypass_list_tools_cache=pinning_active,
        )
        proxy = FastMCPProxy(
            name=f"MCP Proxy [{server.id}]",
            client_factory=client_registry.get_session_client,
            transforms=_build_server_transforms(
                config=config,
                server=server,
                session_store=session_store,
                telemetry=telemetry,
                wiring_readiness=wiring_readiness,
            ),
        )
        proxy_map[server.id] = ProxyMount(
            server=server,
            proxy=proxy,
            clients=client_registry,
            wiring_readiness=wiring_readiness,
        )
    return proxy_map

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.py
68
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:

NameTypeDescriptionDefault
handlerToolHandler

Custom async handler for tool execution.

required
**kwargsAny

Keyword arguments forwarded to Tool.

{}
Source code in src/remote_mcp_adapter/proxy/hooks.py
84
85
86
87
88
89
90
91
92
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

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:

NameTypeDescriptionDefault
mcp_toolAny

Upstream MCP tool object.

required
handlerToolHandler

Custom async handler for tool execution.

required
descriptionstr | None

Optional override description.

None
parametersdict[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
@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", []),
    )

run async

run(arguments, context=None)

Delegate execution to the injected custom handler.

Parameters:

NameTypeDescriptionDefault
argumentsdict[str, Any]

Tool arguments dict.

required
contextContext | None

Optional MCP context; falls back to get_context().

None
Source code in src/remote_mcp_adapter/proxy/hooks.py
 94
 95
 96
 97
 98
 99
100
101
102
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)

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:

NameTypeDescriptionDefault
configAdapterConfig

Full adapter configuration.

required
proxy_mapdict[str, ProxyMount]

Server-id to ProxyMount mapping.

required
storeSessionStore

Session store for adapter operations.

required
stateAdapterWireState | None

Optional wiring state to enable idempotent retries.

None
upload_credentialsUploadCredentialManager | None

Optional upload credential manager.

None
artifact_download_credentialsArtifactDownloadCredentialManager | None

Optional download credential manager.

None
telemetry'AdapterTelemetry | None'

Optional telemetry manager.

None

Returns:

TypeDescription
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
async def wire_adapters(
    *,
    config: AdapterConfig,
    proxy_map: dict[str, ProxyMount],
    store: SessionStore,
    state: AdapterWireState | None = None,
    upload_credentials: UploadCredentialManager | None = None,
    artifact_download_credentials: ArtifactDownloadCredentialManager | None = None,
    telemetry: "AdapterTelemetry | None" = None,
) -> dict[str, bool]:
    """Register configured adapter overrides on each server proxy.

    Args:
        config: Full adapter configuration.
        proxy_map: Server-id to ``ProxyMount`` mapping.
        store: Session store for adapter operations.
        state: Optional wiring state to enable idempotent retries.
        upload_credentials: Optional upload credential manager.
        artifact_download_credentials: Optional download credential manager.
        telemetry: Optional telemetry manager.

    Returns:
        Dict mapping server id to whether wiring succeeded.
    """
    wire_state = state or AdapterWireState()
    server_status: dict[str, bool] = {}

    for server in config.servers:
        mount = proxy_map[server.id]
        helper_tool_name = get_upload_url_tool_name(server.id)

        upload_consumers = [adapter for adapter in server.adapters if isinstance(adapter, UploadConsumerAdapterConfig)]
        artifact_producers = [adapter for adapter in server.adapters if isinstance(adapter, ArtifactProducerAdapterConfig)]
        upload_helper_enabled = bool(upload_consumers and config.uploads.enabled)
        is_disabled = _build_disabled_matcher(server.disabled_tools)

        helper_disabled = is_disabled(helper_tool_name)
        if helper_disabled and upload_helper_enabled:
            logger.info(
                "Upload helper tool suppressed by disabled_tools",
                extra={"server_id": server.id, "tool_name": helper_tool_name},
            )
        if upload_helper_enabled and not helper_disabled and server.id not in wire_state.local_resources_added:
            register_upload_workflow_resource(
                mount=mount,
                upload_endpoint_tool_name=helper_tool_name,
            )
            wire_state.local_resources_added.add(server.id)
        if upload_helper_enabled and not helper_disabled and server.id not in wire_state.local_tools_added:
            register_get_upload_url_tool(
                mount=mount,
                config=config,
                upload_credentials=upload_credentials,
            )
            wire_state.local_tools_added.add(server.id)
        if server.id not in wire_state.providers_added:
            mount.proxy.add_provider(
                SessionArtifactProvider(
                    store=store,
                    server_id=server.id,
                    uri_scheme=config.artifacts.uri_scheme,
                    enabled=config.artifacts.enabled and config.artifacts.expose_as_resources,
                )
            )
            wire_state.providers_added.add(server.id)

        if not upload_consumers and not artifact_producers and not server.disabled_tools:
            mount.wiring_readiness.set_ready(True)
            server_status[server.id] = True
            continue

        try:
            upstream_tool_map = await _list_upstream_tools(mount)
        except Exception as exc:
            logger.warning(
                "Failed to list upstream tools while wiring adapters for server '%s' on '%s'",
                server.id,
                server.mount_path,
                extra={"server_id": server.id, "mount_path": server.mount_path, "error": str(exc)},
            )
            mount.wiring_readiness.set_ready(False)
            server_status[server.id] = False
            continue

        if server.disabled_tools and server.id not in wire_state.visibility_transform_added:
            disabled_names = {name for name in upstream_tool_map if is_disabled(name)}
            if disabled_names:
                logger.info(
                    "Applying disabled_tools suppression via Visibility transform",
                    extra={"server_id": server.id, "disabled_names": sorted(disabled_names)},
                )
                mount.proxy.add_transform(Visibility(False, names=disabled_names))
                wire_state.visibility_transform_added.add(server.id)

        registered_tools = wire_state.registered_tools_by_server.setdefault(server.id, set())
        for adapter in upload_consumers:
            for tool_name in adapter.tools:
                if tool_name in registered_tools:
                    continue
                if is_disabled(tool_name):
                    logger.info(
                        "Upload consumer tool suppressed by disabled_tools",
                        extra={"server_id": server.id, "tool_name": tool_name},
                    )
                    continue
                upstream_tool = upstream_tool_map.get(tool_name)
                if upstream_tool is None:
                    logger.warning(
                        "Configured upload_consumer tool not found upstream",
                        extra={"server_id": server.id, "tool_name": tool_name},
                    )
                    continue

                handler = _build_upload_consumer_handler(
                    store=store,
                    mount=mount,
                    config=config,
                    adapter=adapter,
                    tool_name=tool_name,
                    upload_endpoint_tool_name=helper_tool_name,
                    telemetry=telemetry,
                )
                mount.proxy.add_tool(
                    _build_upload_consumer_override_tool(
                        upstream_tool=upstream_tool,
                        handler=handler,
                        adapter=adapter,
                        upload_endpoint_tool_name=helper_tool_name,
                        config=config,
                        server=server,
                    )
                )
                hide_upstream_tool_names(proxy=mount.proxy, tool_names={tool_name})
                registered_tools.add(tool_name)

        for adapter in artifact_producers:
            for tool_name in adapter.tools:
                if tool_name in registered_tools:
                    continue
                if is_disabled(tool_name):
                    logger.info(
                        "Artifact producer tool suppressed by disabled_tools",
                        extra={"server_id": server.id, "tool_name": tool_name},
                    )
                    continue
                upstream_tool = upstream_tool_map.get(tool_name)
                if upstream_tool is None:
                    logger.warning(
                        "Configured artifact_producer tool not found upstream",
                        extra={"server_id": server.id, "tool_name": tool_name},
                    )
                    continue

                handler = _build_artifact_producer_handler(
                    store=store,
                    mount=mount,
                    config=config,
                    adapter=adapter,
                    tool_name=tool_name,
                    artifact_download_credentials=artifact_download_credentials,
                    telemetry=telemetry,
                )
                mount.proxy.add_tool(OverrideTool.from_mcp_tool(upstream_tool, handler=handler))
                hide_upstream_tool_names(proxy=mount.proxy, tool_names={tool_name})
                registered_tools.add(tool_name)
        mount.wiring_readiness.set_ready(True)
        server_status[server.id] = True

    return server_status

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)

enabled property

enabled

Return whether telemetry emission is enabled.

__init__

__init__(*, config)

Initialize the telemetry manager.

Parameters:

NameTypeDescriptionDefault
configTelemetryConfig

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
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

from_config classmethod

from_config(resolved_config)

Construct telemetry manager from adapter config.

Parameters:

NameTypeDescriptionDefault
resolved_configAdapterConfig

Full adapter configuration.

required
Source code in src/remote_mcp_adapter/telemetry/manager.py
76
77
78
79
80
81
82
83
@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)

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:

NameTypeDescriptionDefault
resultstr

Wiring pass outcome label.

required
total_serversint

Total configured server count.

required
not_ready_serversint

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
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),
        },
    )

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
resultstr

Outcome label (for example success or not_found).

required
auth_modestr

Access mode (for example signed_url or session_context).

required
duration_secondsfloat

Download handling duration in seconds.

required
size_bytesint

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
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)),
        },
    )

record_auth_rejection async

record_auth_rejection(*, reason, route_group, server_id=GLOBAL_SERVER_ID)

Record an auth rejection with bounded reason labels.

Parameters:

NameTypeDescriptionDefault
reasonstr

Rejection reason label.

required
route_groupstr

Logical route group label.

required
server_idstr

Upstream server identifier or global.

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
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),
        },
    )

record_cleanup_cycle async

record_cleanup_cycle(*, result, status, server_id=GLOBAL_SERVER_ID)

Record cleanup cycle summary and removed-record counts.

Parameters:

NameTypeDescriptionDefault
resultdict[str, int]

Dict mapping bucket names to removed-record counts.

required
statusstr

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
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),
        },
    )

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:

NameTypeDescriptionDefault
methodstr

HTTP method (e.g. GET, POST).

required
route_groupstr

Logical route group label.

required
status_codeint

HTTP response status code.

required
duration_secondsfloat

Request duration in seconds.

required
server_idstr

Upstream server identifier or global.

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
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),
        },
    )

record_nonce_operation async

record_nonce_operation(*, operation, result, backend, server_id=GLOBAL_SERVER_ID)

Record reserve/consume nonce outcomes by backend.

Parameters:

NameTypeDescriptionDefault
operationstr

Nonce operation name.

required
resultstr

Operation result label.

required
backendstr

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
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),
        },
    )

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:

NameTypeDescriptionDefault
actionstr

Transition action label.

required
sourcestr

Transition trigger source.

required
policystr

Policy name.

required
configured_backendstr

Originally configured backend.

required
server_idstr

Upstream server identifier or global.

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
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),
        },
    )

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:

NameTypeDescriptionDefault
actionstr

Transition action label.

required
sourcestr

Transition trigger source.

required
policystr

Policy name.

required
configured_backendstr

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
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),
        },
    )

record_request_rejection async

record_request_rejection(*, server_id, route_group, reason, status_code)

Record one non-auth request rejection emitted by middleware.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
route_groupstr

Normalized route group label.

required
reasonstr

Rejection reason label.

required
status_codeint

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
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),
        },
    )

record_session_lifecycle async

record_session_lifecycle(*, event, server_id)

Record session lifecycle transitions (create/revive/expire/tombstone).

Parameters:

NameTypeDescriptionDefault
eventstr

Lifecycle event label.

required
server_idstr

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
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,
        },
    )

record_tool_definition_drift async

record_tool_definition_drift(*, server_id, mode, block_strategy, outcome)

Record one tool-definition drift event.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
modestr

Enforcement mode in effect (warn or block).

required
block_strategystr

Effective block strategy.

required
outcomestr

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
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,
        },
    )

record_upload_batch async

record_upload_batch(*, server_id, file_count, bytes_total)

Record accepted upload batch metrics.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server that received the upload.

required
file_countint

Number of files in the batch.

required
bytes_totalint

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
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)),
        },
    )

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:

NameTypeDescriptionDefault
operationstr

Credential operation name.

required
resultstr

Operation result label.

required
backendstr

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
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),
        },
    )

record_upload_failure async

record_upload_failure(*, server_id, reason)

Record one upload endpoint failure reason.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
reasonstr

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
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,
        },
    )

record_upstream_ping async

record_upstream_ping(*, server_id, result, latency_ms, state_before_probe)

Record active upstream ping outcome and latency.

Parameters:

NameTypeDescriptionDefault
server_idstr

Target server identifier.

required
resultstr

Ping outcome label.

required
latency_msfloat

Ping round-trip time in milliseconds.

required
state_before_probestr

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
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,
        },
    )

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:

NameTypeDescriptionDefault
server_idstr

Target server identifier.

required
tool_namestr

Name of the tool called.

required
resultstr

Outcome label (e.g. success, error).

required
duration_secondsfloat

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
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)),
        },
    )

set_circuit_breaker_state async

set_circuit_breaker_state(*, server_id, state)

Record current circuit breaker state using synchronous gauge.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
statestr

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
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,
        },
    )

shutdown async

shutdown()

Stop worker and flush/shutdown telemetry providers.

Source code in src/remote_mcp_adapter/telemetry/manager.py
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
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.py
21
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)

storage_root property

storage_root

Resolved absolute path to the shared storage root directory.

__init__

__init__(config, *, state_repository=None, lock_provider=None, telemetry=None)

Initialize the session store.

Parameters:

NameTypeDescriptionDefault
configAdapterConfig

Full adapter configuration.

required
state_repositoryStateRepository | None

Optional persistence backend (defaults to in-memory).

None
lock_providerLockProvider | None

Optional lock provider (defaults to in-memory).

None
telemetryTelemetryManager | 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
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,
    )

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
filenamestr | None

Optional client-supplied filename.

required
default_extstr | None

Fallback file extension.

None
artifact_idstr | None

Optional explicit artifact ID.

None
tool_namestr | None

Name of the tool producing this artifact.

None
expose_as_resourcebool

Whether to expose the artifact as an MCP resource.

True

Returns:

TypeDescription
tuple[str, Path, str]

Tuple of (artifact_id, abs_path, rel_path).

Raises:

TypeDescription
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
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

allocate_upload_path async

allocate_upload_path(*, server_id, session_id, filename, upload_id=None)

Allocate storage path for a staged upload.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
filenamestr

Client-supplied filename.

required
upload_idstr | None

Optional explicit upload ID.

None

Returns:

TypeDescription
tuple[str, Path, str]

Tuple of (upload_id, abs_path, rel_path).

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
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

artifact_session_dir

artifact_session_dir(session_id)

Return per-session artifacts directory path.

Parameters:

NameTypeDescriptionDefault
session_idstr

Session identifier.

required
Source code in src/remote_mcp_adapter/core/storage/store.py
114
115
116
117
118
119
120
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

begin_in_flight async

begin_in_flight(server_id, session_id)

Increment in-flight counter for cleanup decisions.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Raises:

TypeDescription
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
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)

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
trust_contextSessionTrustContext

Request-derived trust context to enforce.

required

Raises:

TypeDescription
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
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())

cleanup_once async

cleanup_once()

Run one cleanup cycle for TTL expiry and idle session management.

Returns:

TypeDescription
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
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,
    }

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

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
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)

end_in_flight async

end_in_flight(server_id, session_id)

Decrement in-flight counter for cleanup decisions.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

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
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)

ensure_session async

ensure_session(server_id, session_id)

Get or create state for (server_id, session_id).

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
SessionState

Existing or newly created SessionState.

Raises:

TypeDescription
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
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

finalize_artifact async

finalize_artifact(*, server_id, session_id, artifact_id, mime_type=None)

Finalize artifact metadata after file materialization.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
artifact_idstr

Artifact to finalize.

required
mime_typestr | None

Optional MIME type override.

None

Returns:

TypeDescription
ArtifactRecord

The finalized ArtifactRecord.

Raises:

TypeDescription
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
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

get_artifact async

get_artifact(*, server_id, session_id, artifact_id, include_pending=False)

Resolve and touch one artifact record for a session.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
artifact_idstr

Artifact to resolve.

required
include_pendingbool

When True, return artifacts not yet committed.

False

Returns:

TypeDescription
ArtifactRecord

The resolved ArtifactRecord.

Raises:

TypeDescription
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
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

get_session async

get_session(server_id, session_id)

Return existing session state, if any.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
Source code in src/remote_mcp_adapter/core/storage/store.py
236
237
238
239
240
241
242
243
244
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))

get_session_snapshot async

get_session_snapshot(server_id, session_id)

Return lightweight session metadata for diagnostics.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
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
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,
        }

get_session_trust_context async

get_session_trust_context(server_id, session_id)

Return the bound trust context for one session, if any.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
SessionTrustContext | None

Bound trust context or None when the session has not bound one.

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
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

get_terminal_session_reason async

get_terminal_session_reason(server_id, session_id)

Return the terminal invalidation reason for a session, if any.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
str | None

Terminal invalidation reason or None.

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
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

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
ToolDefinitionBaseline | None

Pinned baseline or None when the session has not pinned one yet.

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
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

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required

Returns:

TypeDescription
ToolDefinitionDriftSummary | None

Stored drift summary or None.

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
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

invalidate_session async

invalidate_session(*, server_id, session_id, reason)

Invalidate one adapter session and block reuse of the same session id.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
reasonstr

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
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)

iter_sessions async

iter_sessions()

Return a snapshot list of all active session states.

Source code in src/remote_mcp_adapter/core/storage/store.py
938
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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
touchbool

When True, update access timestamps.

False

Returns:

TypeDescription
list[ArtifactRecord]

List of committed ArtifactRecord instances.

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
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

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
upload_idstr

Unique upload identifier.

required
abs_pathPath

Absolute filesystem path of the uploaded file.

required
mime_typestr | None

Optional MIME type override.

None
sha256str | None

Optional pre-computed SHA-256 digest.

None

Returns:

TypeDescription
UploadRecord

The registered UploadRecord.

Raises:

TypeDescription
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
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

remove_uploads async

remove_uploads(*, server_id, session_id, upload_ids)

Remove multiple upload records/files and persist state once.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
upload_idslist[str]

List of upload IDs to remove.

required

Returns:

TypeDescription
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
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

replace_backends

replace_backends(*, state_repository, lock_provider)

Replace persistence backends for policy-driven runtime fallback.

Parameters:

NameTypeDescriptionDefault
state_repositoryStateRepository

New state repository to use.

required
lock_providerLockProvider

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
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

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
artifact_uristr

Artifact URI string.

required
uri_schemestr

URI scheme prefix for parsing.

'artifact://'

Returns:

TypeDescription
ArtifactRecord

The resolved ArtifactRecord.

Raises:

TypeDescription
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
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)

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
handlestr

Upload handle string.

required
uri_schemestr

URI scheme prefix for parsing.

'upload://'

Returns:

TypeDescription
UploadRecord

The resolved UploadRecord.

Raises:

TypeDescription
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
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

set_tool_definition_baseline async

set_tool_definition_baseline(server_id, session_id, baseline)

Persist the pinned tool-definition baseline for one session.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
baselineToolDefinitionBaseline

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
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)

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:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

Session identifier.

required
summaryToolDefinitionDriftSummary

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
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)

shutdown async

shutdown(mode='keep_files')

Release in-memory state and optionally delete storage directories.

Parameters:

NameTypeDescriptionDefault
modeLiteral['keep_files', 'delete_files']

'keep_files' preserves disk data; 'delete_files' purges all upload and artifact 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
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)

touch_tool_activity async

touch_tool_activity(server_id, session_id)

Touch session activity for tool-call related operations.

Parameters:

NameTypeDescriptionDefault
server_idstr

Server identifier.

required
session_idstr

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
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)

upload_session_dir

upload_session_dir(session_id)

Return per-session uploads directory path.

Parameters:

NameTypeDescriptionDefault
session_idstr

Session identifier.

required
Source code in src/remote_mcp_adapter/core/storage/store.py
106
107
108
109
110
111
112
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

Next steps

  • Previous topic: Public API - user-facing modules and entry points.
  • See also: Troubleshooting - common failures and practical fixes.