MCP auth and client patterns
MCP servers usually sit between an authenticated host, such as a copilot or chat agent, and a tool implementation. The SDK should not own that entire authentication story. Instead, choose one of two patterns:
- use server-owned credentials when every tool call should run as the MCP server identity
- use the caller's session token when each tool call should run as the authenticated end user
Both patterns are supported by SVIClient. The main design choice is where token ownership lives.
Pattern 1: server-owned credentials
Use this when the MCP server has its own service account or technical user and all tool calls should run with that identity.
This pattern can reuse one SVIClient process-wide because the identity is fixed:
from functools import lru_cache
import os
from mcp.server.fastmcp import FastMCP
from sasvi import SVIClient
from sasvi.auth import UsernamePasswordTokenProvider
mcp = FastMCP("sasvi")
@lru_cache(maxsize=1)
def get_svi_client() -> SVIClient:
base_url = os.environ["SASVI_BASE_URL"]
username = os.environ["SASVI_USERNAME"]
password = os.environ["SASVI_PASSWORD"]
client = SVIClient(
base_url=base_url,
auth=UsernamePasswordTokenProvider(
username=username,
password=password,
),
# Only for testing with self-signed certificates. Do not disable SSL verification in production.
verify_ssl=False,
)
client.verify_connection()
return client
@mcp.tool()
def get_reference_lists() -> list[str]:
"""Get a list of all defined VI reference lists."""
svi = get_svi_client()
reference_lists = svi.admin.reference_lists.list()
return [item.label or item.name for item in reference_lists]
This avoids running the auth flow for every tool call. UsernamePasswordTokenProvider caches and
refreshes tokens in memory when refresh tokens are available.
Server-credential notes
- Use this only when a shared server identity is acceptable for authorization and audit.
- Do not use this pattern if tools must respect each individual end user's VI permissions.
- Keep credentials in environment variables or a secret manager, not in source code.
- Close the cached client during server shutdown if your MCP framework exposes a lifecycle hook.
Example shutdown hook:
def shutdown() -> None:
if get_svi_client.cache_info().currsize:
get_svi_client().close()
Pattern 2: user session token handoff
Use this when the MCP host owns user authentication and each tool call should run as the current
user. The host or MCP framework resolves a bearer token from the active session, and the tool wraps
that token with StaticTokenProvider.
The safest default is to create an SVIClient per tool call:
from mcp.server.fastmcp import FastMCP
from sasvi import SVIClient
from sasvi.auth import StaticTokenProvider
mcp = FastMCP("sasvi")
def client_for_call(ctx) -> SVIClient:
return SVIClient(
base_url=ctx.base_url,
auth=StaticTokenProvider(ctx.access_token),
verify_ssl=ctx.verify_ssl,
)
@mcp.tool()
def get_document(ctx, entity_type_name: str, document_id: str) -> dict:
"""Read one VI document as the authenticated MCP user."""
with client_for_call(ctx) as svi:
document = svi.documents.get(
entity_type_name=entity_type_name,
document_id=document_id,
)
return {} if document is None else document.to_dict()
This keeps user identity and token lifetime outside the SDK. The SDK simply uses the token it was given.
User-token notes
- Prefer per-call clients unless you have measured a real performance issue.
- Do not share one client across users.
- The MCP host should refresh or replace tokens before they expire.
StaticTokenProviderdoes not refresh tokens; it always returns the token it was given.- Tool responses should return JSON-safe data, such as
to_dict()results, not live SDK objects.
Optional per-session client cache
If client creation overhead becomes noticeable, cache by authenticated MCP session. The cache key must isolate user, tenant, base URL, and token lifetime.
A cache must also close what it drops. functools.lru_cache cannot: it discards an evicted
client without closing it, and cache_clear() does the same to every client, so their HTTP
connection pools stay open. The store below closes a client when it is evicted, when its
session's token is replaced, when the session ends, and at shutdown, and waits for any call
still using that client to finish first.
import threading
from collections import OrderedDict
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from sasvi import SVIClient
from sasvi.auth import StaticTokenProvider
@dataclass(frozen=True)
class ClientCacheKey:
session_id: str
user_id: str
base_url: str
token_fingerprint: str
@dataclass
class _Entry:
client: SVIClient
in_use: int = 0
retired: bool = False
class SessionClients:
"""Per-session clients, each closed once it is dropped and no call is using it."""
def __init__(self, maxsize: int = 128) -> None:
self._maxsize = maxsize
self._entries: OrderedDict[ClientCacheKey, _Entry] = OrderedDict()
self._lock = threading.Lock()
@contextmanager
def client(
self, key: ClientCacheKey, access_token: str, *, verify_ssl: bool = True
) -> Iterator[SVIClient]:
with self._lock:
entry = self._entries.get(key)
dropped: list[_Entry] = []
if entry is None:
# A new token for a session replaces that session's old client.
dropped = self._pop(lambda k: k.session_id == key.session_id)
entry = _Entry(
SVIClient(
base_url=key.base_url,
auth=StaticTokenProvider(access_token),
verify_ssl=verify_ssl,
)
)
self._entries[key] = entry
while len(self._entries) > self._maxsize:
dropped.append(self._entries.popitem(last=False)[1])
else:
self._entries.move_to_end(key)
entry.in_use += 1
idle = self._retire(dropped)
self._close(idle)
try:
yield entry.client
finally:
with self._lock:
entry.in_use -= 1
idle = [entry] if entry.retired and entry.in_use == 0 else []
self._close(idle)
def end_session(self, session_id: str) -> None:
"""Drop a session's client when the session ends or its token is revoked."""
with self._lock:
idle = self._retire(self._pop(lambda k: k.session_id == session_id))
self._close(idle)
def close(self) -> None:
"""Drop every client; call this when the server shuts down."""
with self._lock:
idle = self._retire(self._pop(lambda k: True))
self._close(idle)
def _pop(self, matches) -> list[_Entry]:
return [self._entries.pop(k) for k in [k for k in self._entries if matches(k)]]
@staticmethod
def _retire(entries: list[_Entry]) -> list[_Entry]:
# Called with the lock held. A client still in use closes when its last call ends.
for entry in entries:
entry.retired = True
return [entry for entry in entries if entry.in_use == 0]
@staticmethod
def _close(entries: list[_Entry]) -> None:
for entry in entries:
entry.client.close()
Use it as with clients.client(key, token) as svi: ... inside each tool call, call
clients.end_session(session_id) when the MCP session ends, and clients.close() on
shutdown. In an async server, make the same store async: an asyncio.Lock, an async
context manager, and await client.close_async(), which closes the sync and async
transports.
Only use a cache if your MCP server knows when a token changes or a user session ends. Per-call clients are simpler and safer.
Which pattern should you use?
Use server-owned credentials when:
- the MCP server is intentionally acting as an automation identity
- all users should see the same permitted VI data
- audit records may show the server identity
- you want maximum reuse of one long-lived client
Use user token handoff when:
- tools must respect the caller's VI permissions
- audit records should reflect the end user
- the MCP host already owns login, consent, refresh, and session lifetime
- you want the cleanest separation between host authentication and SDK API access
Responsibility split
The MCP server owns:
- extracting or resolving the token from the MCP/session context
- deciding whether calls use server credentials or user credentials
- client caching boundaries
- token refresh and invalidation
- tool-level authorization and argument validation
- converting SDK objects into JSON-safe tool results
The SDK owns:
- attaching bearer tokens through
StaticTokenProvideror anotherTokenProvider - applying base URL, TLS, timeout, retry, and logging configuration
- providing typed VI domains:
documents,alerts,search,workflows,adminandcustom - redacting tokens and sensitive headers in SDK logs
Minimal token-handoff helper
If your MCP framework provides token access through a callable instead of a value, define a small provider in the MCP server:
from dataclasses import dataclass
from typing import Callable
@dataclass
class CallableTokenProvider:
get_current_token: Callable[[], str]
def get_token(self) -> str:
return self.get_current_token()
async def get_token_async(self) -> str:
return self.get_current_token()
Then pass it to SVIClient:
svi = SVIClient(
base_url=ctx.base_url,
auth=CallableTokenProvider(lambda: ctx.access_token),
)
This is useful when the framework refreshes tokens transparently and you want each SDK request to ask the session for the latest token.