All checks were successful
check agents / check (push) Successful in 10s
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight individual declarative agents (individual-agents/), with their KAB workflow exports. Shared check, render and import scripts, the alz-discovery-sample MCP server, the crucible-kab-dev deploy profile, deployment docs, platform issue reports and the source material. Agent steps time out at 20 minutes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
221 lines
8.9 KiB
Python
221 lines
8.9 KiB
Python
"""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, 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()]
|
|
|
|
|
|
__all__ = [
|
|
"VENDOR",
|
|
"SCHEMA_KEY",
|
|
"CONNECTION_KEY",
|
|
"VERIFY_TOOL_KEY",
|
|
"schema_meta",
|
|
"verify_tool_from_initialize",
|
|
"from_params",
|
|
"bind",
|
|
"unbind",
|
|
"active",
|
|
"fingerprint",
|
|
"redact",
|
|
"scrub",
|
|
"missing_fields",
|
|
]
|