"""The connection a request carries: which upstream account this call is for. An MCP server that talks to a third-party system needs that system's address and credentials. Taking them from environment variables makes one process serve one account for ever. Here the MCP Gateway sends them with each call, from the Vault Service, in MCP's own `_meta` field, under our vendor prefix: initialize result _meta["com.kyndryl.mcp/connection-schema"] what this server needs (JSON Schema) _meta["com.kyndryl.mcp/verify-tool"] the tool that tests a connection tools/call, resources/read, prompts/get params._meta["com.kyndryl.mcp/connection"] the values, matching that schema `_meta` is where the specification tells implementations to put their own data, so a client that does not know these keys ignores them. The values never travel in `arguments`, which is what the model writes and reads, so a credential cannot enter the model's context. The connection is bound for the life of one request and read with `active()`. It is None when the caller sent nothing; whether the server may then use its own environment is decided in server.py (REQUIRE_VAULT_CONNECTION, which is on by default). WHAT IS STANDARD AND WHAT IS OURS --------------------------------- The mechanism is standard. `_meta` is the specification's sanctioned place for implementation-specific data, with formal key-naming rules (2026-07-28, "General fields / _meta"): Prefix ... SHOULD use reverse DNS notation. Any prefix where the second label is `modelcontextprotocol` or `mcp` is reserved for MCP use ... third-party extensions use their own vendor prefix. `com.kyndryl.mcp/` satisfies that: the second label is `kyndryl`, so it is a legitimate vendor prefix and not reserved. A client that does not recognise our keys ignores them, which is exactly what `_meta` is for. The value carried is a *separate* upstream credential, never the caller's own token (the specification says a server MUST NOT pass through the token it received from its client). Only the three key names and the shape of their payloads are ours. When SEP-2127 (MCP Server Card) lands, the schema is what moves onto the card, and the key names are the only thing that changes. The third key, VERIFY_TOOL_KEY, adds very little. Checking a credential is a plain `tools/call` against an ordinary tool that appears in `tools/list` like any other: no new method, no new transport. The only question that needed answering is WHICH tool, and the alternative was for the gateway to guess by name. A server that advertises nothing here is simply not verifiable. STATELESSNESS ------------- The 2026-07-28 specification made MCP explicitly stateless: "Servers MUST NOT rely on prior requests over the same connection to establish context ... Every request supplies this metadata in its _meta field." A module-level connection built once at import is exactly the state the specification tells servers not to keep. Binding the connection per request is therefore not only what multi-tenancy needs, it is what the protocol asks for. HOW IT IS USED (server.py does all of this; a tool only calls get_connection()) ------------------------------------------------------------------------------ import mcp_connection # advertise, in the initialize result result["_meta"] = mcp_connection.schema_meta(CONNECTION_SCHEMA, verify_tool="verify_connection") # bind, for the life of one request token = mcp_connection.bind(mcp_connection.from_params(request.params)) try: ... # mcp_connection.active() anywhere below finally: mcp_connection.unbind(token) LOGS AND ERROR MESSAGES ----------------------- `scrub()` is applied to every log line, and to the `error` text of a failed tool call, so the connection's values and credential-looking URL parameters (`?key=...`) never leave the process. `redact()` does the connection values alone. Neither is applied to a successful result: a presigned URL a tool returns on purpose must survive. """ from __future__ import annotations import contextvars import hashlib import hmac import json import re import secrets from typing import Any, Callable, Dict, List, Optional VENDOR = "com.kyndryl.mcp" SCHEMA_KEY = f"{VENDOR}/connection-schema" CONNECTION_KEY = f"{VENDOR}/connection" VERIFY_TOOL_KEY = f"{VENDOR}/verify-tool" _active: contextvars.ContextVar[Optional[Dict[str, Any]]] = contextvars.ContextVar( "mcp_connection", default=None ) # Per process, so a fingerprint in a log cannot be checked against a guessed credential offline _FINGERPRINT_KEY = secrets.token_bytes(32) def schema_meta(schema: Dict[str, Any], verify_tool: Optional[str] = None) -> Dict[str, Any]: """The `_meta` object that advertises `schema` on an initialize result.""" meta: Dict[str, Any] = {SCHEMA_KEY: schema} if verify_tool: meta[VERIFY_TOOL_KEY] = verify_tool return meta def verify_tool_from_initialize(result: Optional[Dict[str, Any]]) -> Optional[str]: """The verify tool an initialize result advertises, or None. The reader half of schema_meta, here rather than in the gateway so the two ends of the key cannot drift apart. """ if not isinstance(result, dict): return None meta = result.get("_meta") if not isinstance(meta, dict): return None name = meta.get(VERIFY_TOOL_KEY) return name if isinstance(name, str) and name.strip() else None def from_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """The connection in a request's `params._meta`, or None. Anything that is not an object counts as absent: a malformed connection must not be more powerful than none at all. """ if not isinstance(params, dict): return None meta = params.get("_meta") if not isinstance(meta, dict): return None profile = meta.get(CONNECTION_KEY) return profile if isinstance(profile, dict) and profile else None def bind(profile: Optional[Dict[str, Any]]) -> contextvars.Token: """Make `profile` the connection for this request.""" return _active.set(profile) def unbind(token: contextvars.Token) -> None: try: _active.reset(token) except ValueError: _active.set(None) def active() -> Optional[Dict[str, Any]]: """The connection for this request, or None.""" return _active.get() def fingerprint(profile: Optional[Dict[str, Any]]) -> str: """A short id for a connection, safe to log and to cache on; the credential never is the key.""" if not profile: return "env" canonical = json.dumps(profile, sort_keys=True, separators=(",", ":"), default=str) return hmac.new(_FINGERPRINT_KEY, canonical.encode("utf-8"), hashlib.sha256).hexdigest()[:16] def redact(text: Any) -> str: """`text` with every value of this request's connection replaced, for logs and error replies. A tool can put a credential in an exception message without meaning to. Values shorter than four characters are left alone: replacing them would garble ordinary text. """ result = str(text) values = [v for v in (active() or {}).values() if isinstance(v, str) and len(v) >= 4] for value in sorted(values, key=len, reverse=True): result = result.replace(value, "[redacted]") return result # Query parameters that carry a credential in the URL of an upstream request _URL_CREDENTIAL = re.compile( r"([?&;](?:api[_-]?key|apikey|key|token|access[_-]?token|auth|secret|password|passwd|" r"client[_-]?secret|appid|app[_-]?id|sig|signature)=)[^&\s\"'#<>]+", re.IGNORECASE, ) def scrub(value: Any, _depth: int = 0) -> Any: """`value` with credentials taken out, for anything that is logged or sent back to a caller. Strings lose the request's connection values and the value of any credential query parameter in a URL (`?key=...`); dicts, lists and tuples are scrubbed inside. Anything else is returned as it is. Not for tool results in general: a presigned URL a tool returns on purpose would be damaged. """ if isinstance(value, str): return _URL_CREDENTIAL.sub(r"\1[redacted]", redact(value)) if _depth > 5: return value if isinstance(value, dict): return {k: scrub(v, _depth + 1) for k, v in value.items()} if isinstance(value, (list, tuple)): return type(value)(scrub(v, _depth + 1) for v in value) return value def missing_fields(profile: Optional[Dict[str, Any]], schema: Dict[str, Any]) -> List[str]: """The required fields of `schema` that `profile` does not supply.""" if not profile: return [] required = schema.get("required") or [] return [name for name in required if not str(profile.get(name) or "").strip()] def install_invalid_request_handler(app: Any, on_invalid: Optional[Callable[[str], None]] = None) -> None: """Answer a request that is not valid JSON-RPC with a JSON-RPC error that does not repeat the request. FastAPI's own answer (HTTP 422) repeats the request body under "input". The body is where the gateway puts the tenant's connection, so a request that is merely malformed (no "id", say) would get the credential back in the reply, and in the log of anything that records replies. The status stays 422; the body is a JSON-RPC error (-32600) that names only the fields at fault. `on_invalid`, if given, is called with that text, already reduced to harmless characters, so the caller can log it in its own style. Call it once, right after `app = FastAPI(...)`. FastAPI is imported here, not at module level, so the rest of this module stays importable without it. """ from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse @app.exception_handler(RequestValidationError) async def invalid_request(request, exc): names = { "body" if error.get("type") == "json_invalid" else ".".join(str(p) for p in error.get("loc", ())[1:]) or "body" for error in exc.errors() } fields = re.sub(r"[^\w.\-, ]", "?", ", ".join(sorted(names)))[:200] if on_invalid is not None: on_invalid(fields) return JSONResponse( status_code=422, content={ "jsonrpc": "2.0", "id": None, "result": None, "error": {"code": -32600, "message": "Invalid request: check " + fields}, }, ) __all__ = [ "install_invalid_request_handler", "VENDOR", "SCHEMA_KEY", "CONNECTION_KEY", "VERIFY_TOOL_KEY", "schema_meta", "verify_tool_from_initialize", "from_params", "bind", "unbind", "active", "fingerprint", "redact", "scrub", "missing_fields", ]