Files
smeta-web/mcp_context.py
T

34 lines
773 B
Python

"""Per-request identity for domain tools shared by stdio and remote MCP."""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator
@dataclass(frozen=True)
class ToolContext:
username: str
tab_id: str
work_dir: Path
client_id: str
scopes: frozenset[str]
_current: ContextVar[ToolContext | None] = ContextVar("smeta_mcp_tool_context", default=None)
def current_tool_context() -> ToolContext | None:
return _current.get()
@contextmanager
def bind_tool_context(context: ToolContext) -> Iterator[None]:
marker = _current.set(context)
try:
yield
finally:
_current.reset(marker)