Capstone 13: Stateless MCP Server with Registry and Governance
Production MCP is not one server process. It is a chain of contracts: publishable metadata, live discovery, a stateless request envelope, authorization, policy, audit, and deployment evidence.
Learning Objectives
- Implement the stateless MCP request and result envelope.
- Keep Registry metadata separate from live protocol discovery.
- Build deterministic, cache-aware tool discovery.
- Enforce issuer, audience, scope, and approval policy for every tool call.
- Deploy Streamable HTTP without session affinity.
- Prove behavior at the wire, authorization, policy, registry, and audit boundaries.
Required MCP Prerequisite Path
Complete the four linked Phase 13 lessons in order before treating this capstone as production-ready:
- Lesson 28 defines the tool, schema, content, pagination, completion, routing, and error contracts this server must expose.
- Lesson 29 defines cancellation races, deadlines, idempotency, backpressure, retry, and reconnect behavior.
- Lesson 30 defines namespace, provenance, admission pin, Registry status, drift, ledger, and rollback evidence.
- Lesson 31 defines golden and negative transcripts, strict version eras, SDK differential checks, proxy proof, redaction, health, and release gating.
The capstone integrates those artifacts. It does not replace them with one happy-path SDK test.
The Problem
An internal platform needs read-only data tools and a small set of state-changing tools. Developers must be able to discover the server, understand how to connect, inspect its live capabilities, and call only the operations they are authorized to use.
The difficult part is not registering a function. The difficult part is keeping six different truths aligned:
server.jsonsays where the server can be installed or reached.server/discoversays what the live process supports now.- Every request says which protocol revision and client capabilities it uses.
- Authorization binds a caller to the correct issuer, resource, and scopes.
- Policy decides whether this specific action may run.
- Audit evidence records what crossed the boundary without leaking secrets or sensitive payloads.
If any one of these drifts, the platform may list a server that cannot be reached, route an incompatible client, accept a token minted for another resource, or expose a destructive action without the expected review.
The Two Discovery Layers
The Registry and the live MCP server answer different questions.
| Layer | Contract | Question it answers |
|---|---|---|
| Publication | server.json and Registry API | What is this server, where is its package or remote endpoint, and how is it configured? |
| Runtime | server/discover | Which protocol versions, capabilities, extensions, and server identity does this process support? |
The official Registry uses a versioned server.json schema. A remote entry can name a Streamable HTTP URL:
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "com.example/internal-readonly",
"title": "Internal Read-Only Tools",
"description": "Read-only incident and data lookup tools.",
"version": "1.0.0",
"remotes": [
{
"type": "streamable-http",
"url": "https://mcp.internal.example.com/readonly"
}
]
}The Registry schema version and the MCP protocol revision are independent. Do not rewrite one date to match the other. Validate each document against its own contract.
Schema validity does not prove namespace ownership. A publisher verified for example.com uses the reverse-DNS namespace com.example/* or one of its child namespaces. The Registry authentication flow proves that ownership. Keeping the domain labels in their ordinary order names a different namespace.
The stdlib model's validate_registry_document function is intentionally a partial remote-profile validator. It checks the official required namedescriptionand version fields; the optional title; the published name and length constraints; concrete-version shape; and each streamable-http or sse remote's HTTP(S) URL shape. It additionally requires a non-empty remotes list because this capstone always live-probes a remote. validate_publisher_namespace separately checks the name against the verified publisher domain, while validate_runtime_alignment compares the publication name and version with live serverInfo. The official schema also supports package-only records and more remote fields. Before publication, validate the entire document with the pinned official JSON Schema or mcp-publisher; do not present this dependency-free subset as full schema validation.
The server must implement server/discover; a client may call it before other methods. This capstone client does so after resolving the endpoint, and receives the current protocol revision and live capabilities:
{
"resultType": "complete",
"supportedVersions": ["2026-07-28"],
"capabilities": {
"tools": {
"listChanged": false
}
},
"_meta": {
"io.modelcontextprotocol/serverInfo": {
"name": "com.example/internal-readonly",
"version": "1.0.0"
}
},
"ttlMs": 3600000,
"cacheScope": "public"
}A private catalog may index extra ownership, review, or lifecycle data, but it must not invent that data as MCP wire fields or root server.json fields. Store organizational policy beside the published record. When public custom metadata is necessary, use the Registry's _meta.io.modelcontextprotocol.registry/publisher-provided extension and stay within its 4 KB limit.
Stateless MCP Core
MCP revision 2026-07-28 removes protocol sessions and the initialize / notifications/initialized handshake. It also removes Mcp-Session-Id.
Every request carries protocol context in params._meta:
{
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {
"name": "internal-platform-client",
"version": "1.0.0"
}
}The version and capabilities are request facts, not connection facts. A load balancer may send consecutive requests to different healthy replicas because either replica can validate the request from the message itself.
Ordinary results include resultType: "complete". Servers should place their identity in _meta.io.modelcontextprotocol/serverInfo on each result. A missing or non-string protocol version is invalid params -32602. Error -32022 is only for a supplied string that is unsupported, with exactly {"supported": ["2026-07-28"], "requested": "..."} as its data.
Cacheable discovery
tools/list must be deterministic for the same effective tool set. The result includes:
ttlMsa freshness hint for the client;cacheScopeeitherpublicorprivate;- a stable tool order so identical lists can reuse prompt caches;
resultType: "complete"and server identity metadata.
Per-user authorization should normally produce cacheScope: "private". Do not put user-specific tool visibility behind a shared public cache.
Streamable HTTP
A network server exposes one MCP endpoint that accepts POST. Each JSON-RPC request or notification gets its own POST.
For a request, the server returns either one JSON object or an SSE stream scoped to that request. A long-lived subscriptions/listen request carries opted-in change notifications. There is no standalone GET stream, session DELETE, session header, or Last-Event-ID replay in the current transport.
Each request includes:
MCP-Protocol-Versionmatching the body metadata;Mcp-Methodmatching the JSON-RPC method;Mcp-Namefortools/callresources/readandprompts/get;Accept: application/json, text/event-stream.
Reject mismatched mirrored headers with the specified -32020 error. Validate Originbind local development servers to loopback, authenticate remote clients, and treat a closed request-scoped SSE response as cancellation.
Authorization and Policy
Transport metadata is not authorization. Validate authorization on every call.
For remote servers:
- Discover protected-resource metadata.
- Select the authorization server for that resource.
- Prefer Client ID Metadata Documents for client registration. Treat Dynamic Client Registration as compatibility support.
- Send the resource indicator during authorization.
- Validate a returned
issvalue against the authorization server recorded for the flow. - Key client credentials by issuer. Never reuse registration data across issuers.
- Validate token issuer, audience or resource, expiry, and scopes at the MCP server.
- Apply a second policy decision to the concrete tool and arguments.
Tool annotations such as readOnlyHint and destructiveHint help clients present risk. They are not trusted authorization controls.
Approval is a record, not a magic scope
A state-changing call needs an approval record bound to the actor, tool, normalized arguments or digest, target environment, expiry, and one-time or repeat-use policy. A chat message alone is not proof of approval.
The Python model hashes canonical JSON with sorted keys, then binds that digest with the token subject, tool name, server URL, and expiry. Replaying the record after changing even one argument fails before the handler runs. Approval is separate evidence, not a scope added to the access token.
Keep high-risk tools on a separately reviewable surface when that materially reduces blast radius. Separation is useful only if credentials, policy, deployment identity, and audit controls are also separate.
Build It
1. Model publication metadata
Create and schema-validate server.json. Include a stable name inside the namespace authenticated for the publisher, plus version, description, official repository or packages metadata when applicable, and a remote or stdio transport. Keep secrets as declared environment-variable inputs, never literal values.
2. Implement live discovery
Implement server/discover before any feature RPC. Advertise supported protocol versions, capabilities, extensions, and server identity. Add a version rejection case using -32022.
3. Implement the stateless envelope
Require protocol version and client capabilities in every request. Return resultType and server identity in every result. Remove initialization state, connection-scoped capability caches, and session identifiers.
4. Build the tool surface
Start with two read-only tools and one state-changing tool. Give each a bounded JSON Schema, precise description, deterministic result shape, and honest annotations. Add output schemas when clients rely on structured results.
5. Add cache-aware listing
Return tools in stable order with ttlMs and cacheScope. Exercise cache expiry and list-change notification behavior separately.
6. Add authorization and policy
Validate issuer, audience, expiry, and scope. Run a policy decision for every tool call. Bind approvals to exact high-risk actions. Deny missing or stale approvals before executing a handler.
7. Separate registry and runtime validation
Validate the static server.json record, then probe the remote endpoint with server/discover. Report drift when the published remote, identity, version, or required capabilities disagree with the live process.
8. Add audit evidence
Record actor, issuer, resource, tool, policy decision, request identifier, trace context, latency, and outcome. Redact or digest sensitive arguments and results before persistence. Keep the audit sink outside model-visible context.
9. Exercise horizontal scaling
Place two stateless replicas behind a load balancer. Send at least 100 concurrent requests. Demonstrate that correctness does not depend on affinity. If a tool needs cross-call state, mint an explicit opaque handle and store it in a shared durable system.
10. Cross the real wire
Run conformance checks against the actual server binary. Capture request headers and JSON bodies, not only SDK objects. Exercise wrong version, header mismatch, missing scope, wrong audience, malformed arguments, handler failure, cancellation, and cache expiry.
Required Evidence Pack
A submission is incomplete until it contains all five evidence classes:
| Evidence | Minimum proof | Source lesson |
|---|---|---|
| Wire | Redacted raw headers and JSON-RPC bodies for golden and negative cases, including metadata type failure, header mismatch, unsupported version, missing or unknown resultTypenotification no-response, and response ID matching | Lesson 31 |
| Proxy | The same stable case run directly and through the deployed intermediary, with ingress, origin, and egress status and body digests; prove protocol errors are not collapsed into generic 500 responses and streaming is not buffered | Lessons 29 and 31 |
| Admission | Verified publisher namespace, immutable Registry record digest, artifact or remote provenance, live server/discover identity and capability observation, descriptor pin, current Registry status, and admission-ledger event | Lesson 30 |
| Retry | A cancellation-versus-completion race, explicit timeout, safe read retry, mutation idempotency key, reconnect refetch, and proof that request cancellation cannot silently become durable task cancellation | Lesson 29 |
| Rollback | Exact previous version, admission and artifact digests, descriptor pin, active Registry status, current health window, route restoration result, and redacted decision evidence | Lessons 30 and 31 |
Store a digest of the redacted pack with the release. If any class is missing, hold the release. Do not infer proxy behavior from an in-process dispatcher, admission from Registry presence, retry safety from a new JSON-RPC id, or rollback readiness from “the previous deployment.”
Local Reference Models
The Python model demonstrates registry metadata, reverse-DNS publisher namespace validation, publication-to-runtime identity checks, live discovery, deterministic tool listing, per-request metadata, trusted-issuer, audience, expiry, and scope checks, action-bound approvals, a documented partial Registry validator, policy, and audit without opening a network socket:
cd phases/19-capstone-projects/13-mcp-server-with-registry
python3 code/main.py
python3 -m unittest discover -s code/tests -vThe TypeScript project exposes the stateless JSON-RPC shape over stdio without an MCP SDK. Its tools/call path enforces the same bounded input schemas advertised by tools/list; invalid arguments for a known tool return a complete result with isError: true without invoking the executor:
cd phases/19-capstone-projects/13-mcp-server-with-registry/code/ts
npm install
npm run typecheck
npm test
npm run demoThese models prove local contract logic. They do not prove HTTP headers, OAuth exchange, Registry publication, OPA integration, load balancing, or collector receipt.
Wire Example
POST /mcp HTTP/1.1
Host: mcp.internal.example.com
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: postgres.readonly
Authorization: Bearer REDACTED
{
"jsonrpc": "2.0",
"id": 42,
"method": "tools/call",
"params": {
"name": "postgres.readonly",
"arguments": {"sql": "SELECT 1"},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {
"name": "internal-platform-client",
"version": "1.0.0"
}
}
}
}Ship It
Ship a repository containing:
- a schema-valid
server.json; - read-only and state-changing server surfaces;
server/discoverdeterministictools/listand policy-gatedtools/call;- a Streamable HTTP deployment with two interchangeable replicas;
- authorization and approval integration;
- a Registry publisher or private Registry API adapter;
- policy definitions and action-bound approval records;
- redacted audit output and trace propagation;
- wire and proxy failure evidence;
- admission, retry, health, and rollback evidence with a digest of the redacted pack.
| Weight | Criterion | Evidence |
|---|---|---|
| 25 | Protocol correctness | Stateless request metadata, discovery, results, headers, and negative cases |
| 20 | Authorization | Issuer, audience, expiry, scope, and action-bound approval cases |
| 15 | Registry integrity | Valid server.jsonpublication record, live discovery probe, and drift report |
| 15 | Policy and safety | Allow, deny, malformed, stale approval, and sensitive-data cases |
| 15 | Scale and reliability | Two replicas, no affinity dependency, cancellation, timeout, and recovery |
| 10 | Auditability | Redacted receiver-side audit and trace evidence |
Exercises
- Change the published remote URL while leaving the live server unchanged. Make the registry validation report the exact drift.
- Send
tools/listtwice with identical inputs and prove byte-stable tool order. Then expirettlMsand refresh. - Send a valid body with a different
MCP-Protocol-Versionheader. Return-32020and do not invoke policy or the tool. - Mint a token for the read-only server and present it to the state-changing server. Prove audience validation fails before the handler runs.
- Bind an approval to one normalized argument digest. Change one field and prove the approval cannot be replayed.
- Route consecutive calls to alternating replicas. Replace hidden process memory with an explicit shared handle wherever the workflow needs persistence.
- Break a request-scoped SSE connection and retry with a new JSON-RPC request ID. Verify that no
Last-Event-IDrecovery path is used.
Key Terms
| Term | What people say | What it actually means |
|---|---|---|
| Stateless MCP | "No state anywhere" | No protocol session; cross-call state is explicit and server-managed |
server.json | "The tool manifest" | Registry metadata for naming, packaging, configuration, and transports |
server/discover | "The handshake" | A normal mandatory RPC for live versions and capabilities, not a session initializer |
| Cache scope | "Can I cache it?" | Whether a cacheable result is safe for shared or private reuse |
| Policy decision | "The token allows it" | A separate decision over actor, tool, target, arguments, and context |
| Approval record | "A human clicked yes" | Evidence bound to one actor and consequential action under an expiry policy |
| Explicit handle | "A session ID" | Ordinary application data for named server-managed state, not protocol connection state |
Further Reading
Check what you learned
6 questions. Answer each one to see why.
Why does this capstone use both server.json and server/discover?
The full code
Every file for this lesson. Copy it, run it, then change it.
"""Stateless MCP server, registry metadata, policy, and audit simulation.
This stdlib-only model keeps two discovery layers separate:
* ``server.json`` describes installation and remote transport metadata to a
registry.
* ``server/discover`` reports live protocol versions and capabilities.
It does not open a network listener, validate a real OAuth token, call OPA, or
publish to a registry. Run with ``python3 code/main.py`` from the lesson root.
"""
from __future__ import annotations
import hashlib
import json
import re
import time
from copy import deepcopy
from dataclasses import asdict, dataclass, field
from typing import Callable
PROTOCOL_VERSION = "2026-07-28"
REGISTRY_SCHEMA = "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json"
PUBLISHER_DOMAIN = "example.com"
SERVER_NAME_RE = re.compile(r"^[a-zA-Z0-9.-]+/[a-zA-Z0-9._-]+$")
DOMAIN_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
REMOTE_URL_RE = re.compile(r"^https?://\S+$")
VERSION_RANGE_RE = re.compile(r"(?:^[~^<>=]|[*]|(?:^|\.)x(?:$|\.))", re.IGNORECASE)
def request_meta() -> dict:
return {
"io.modelcontextprotocol/protocolVersion": PROTOCOL_VERSION,
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {
"name": "registry-capstone-client",
"version": "1.0.0",
},
}
def error(code: int, message: str, data: dict | None = None) -> dict:
detail = {"code": code, "message": message}
if data is not None:
detail["data"] = data
return {"error": detail}
def validate_meta(meta: object) -> dict | None:
if not isinstance(meta, dict):
return error(-32602, "params._meta must be an object")
requested = meta.get("io.modelcontextprotocol/protocolVersion")
if not isinstance(requested, str):
return error(-32602, "protocolVersion must be a string")
if requested != PROTOCOL_VERSION:
return error(
-32022,
"Unsupported protocol version",
{"supported": [PROTOCOL_VERSION], "requested": requested},
)
if not isinstance(meta.get("io.modelcontextprotocol/clientCapabilities"), dict):
return error(-32602, "clientCapabilities must be an object")
return None
@dataclass(frozen=True)
class ToolSchema:
name: str
required_scope: str
destructive: bool
description: str
input_schema: dict
Handler = Callable[[dict], dict]
@dataclass
class MCPServer:
name: str
title: str
description: str
version: str
url: str
trusted_issuer: str
tools: dict[str, ToolSchema] = field(default_factory=dict)
handlers: dict[str, Handler] = field(default_factory=dict)
@property
def server_info(self) -> dict:
return {"name": self.name, "version": self.version}
def register(self, schema: ToolSchema, handler: Handler) -> None:
if schema.name in self.tools:
raise ValueError(f"duplicate tool: {schema.name}")
self.tools[schema.name] = schema
self.handlers[schema.name] = handler
def result(self, **fields: object) -> dict:
return {
"resultType": "complete",
**fields,
"_meta": {"io.modelcontextprotocol/serverInfo": self.server_info},
}
def discover(self, meta: dict) -> dict:
invalid = validate_meta(meta)
if invalid:
return invalid
return self.result(
supportedVersions=[PROTOCOL_VERSION],
capabilities={"tools": {"listChanged": False}},
ttlMs=3_600_000,
cacheScope="public",
)
def tools_list(self, meta: dict) -> dict:
invalid = validate_meta(meta)
if invalid:
return invalid
tools = [
{
"name": tool.name,
"description": tool.description,
"inputSchema": tool.input_schema,
"annotations": {
"readOnlyHint": not tool.destructive,
"destructiveHint": tool.destructive,
},
}
for tool in sorted(self.tools.values(), key=lambda item: item.name)
]
return self.result(tools=tools, ttlMs=60_000, cacheScope="private")
def registry_document(self) -> dict:
return {
"$schema": REGISTRY_SCHEMA,
"name": self.name,
"title": self.title,
"description": self.description,
"version": self.version,
"remotes": [{"type": "streamable-http", "url": self.url}],
}
@dataclass(frozen=True)
class Token:
user: str
issuer: str
audience: str
scopes: frozenset[str]
expires_at: float
def has_scope(self, scope: str) -> bool:
return scope in self.scopes
def is_expired(self, now: float) -> bool:
return now >= self.expires_at
def arguments_digest(args: dict) -> str:
normalized = json.dumps(
args,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class ApprovalRecord:
actor: str
tool: str
arguments_digest: str
target: str
expires_at: float
@classmethod
def for_action(
cls,
actor: str,
tool: str,
args: dict,
target: str,
expires_at: float,
) -> ApprovalRecord:
return cls(actor, tool, arguments_digest(args), target, expires_at)
def authorize(
self,
actor: str,
tool: str,
args: dict,
target: str,
now: float,
) -> tuple[bool, str]:
if self.actor != actor:
return False, "approval actor does not match token subject"
if self.tool != tool:
return False, "approval tool does not match requested tool"
if self.target != target:
return False, "approval target does not match this server"
if self.arguments_digest != arguments_digest(args):
return False, "approval arguments do not match requested action"
if now >= self.expires_at:
return False, "approval has expired"
return True, "ok"
def policy_decide(
server: MCPServer,
tool: str,
token: Token,
args: dict,
now: float,
approval: ApprovalRecord | None = None,
) -> tuple[bool, str]:
if token.issuer != server.trusted_issuer:
return False, "token issuer is not trusted by this server"
if token.audience != server.url:
return False, "token audience does not match this server"
if token.is_expired(now):
return False, "token has expired"
schema = server.tools.get(tool)
if schema is None:
return False, f"no such tool: {tool}"
if not token.has_scope(schema.required_scope):
return False, f"missing scope: {schema.required_scope}"
if len(json.dumps(args)) > 8192:
return False, "payload too large"
if schema.destructive:
if approval is None:
return False, "destructive tool requires an action-bound approval"
approved, reason = approval.authorize(
token.user,
tool,
args,
server.url,
now,
)
if not approved:
return False, reason
return True, "ok"
def redact(payload: dict) -> dict:
text = json.dumps(payload)
text = re.sub(r"[\w.+-]+@[\w-]+\.[\w.-]+", "[email]", text)
text = re.sub(r"\b\d{3}-\d{2}-\d{4}\b", "[ssn]", text)
return json.loads(text)
@dataclass(frozen=True)
class AuditEntry:
ts: float
user: str
issuer: str
tool: str
outcome: str
args_redacted: dict
response_redacted: dict
def dispatch(
server: MCPServer,
token: Token,
tool: str,
args: dict,
meta: dict,
audit: list[AuditEntry],
approval: ApprovalRecord | None = None,
) -> dict:
invalid = validate_meta(meta)
if invalid:
return invalid
now = time.time()
allowed, reason = policy_decide(server, tool, token, args, now, approval)
if not allowed:
audit.append(
AuditEntry(now, token.user, token.issuer, tool, f"denied:{reason}", redact(args), {})
)
return error(-32000, reason)
try:
response = server.handlers[tool](args)
except Exception as exc:
audit.append(
AuditEntry(now, token.user, token.issuer, tool, "handler_error", redact(args), {})
)
return server.result(
content=[{"type": "text", "text": str(exc)}],
isError=True,
)
audit.append(
AuditEntry(
now,
token.user,
token.issuer,
tool,
"allowed",
redact(args),
redact(response),
)
)
return server.result(
content=[{"type": "text", "text": json.dumps(response)}],
structuredContent=response,
isError=False,
)
def validate_registry_document(document: object) -> list[str]:
"""Validate the official fields used by this lesson's remote-only profile.
This dependency-free subset is not a replacement for validation against
the complete pinned Registry JSON Schema before publication.
"""
if not isinstance(document, dict):
return ["server.json must be an object"]
issues: list[str] = []
for key in ("name", "description", "version"):
if key not in document:
issues.append(f"missing {key}")
schema_uri = document.get("$schema")
if "$schema" in document and schema_uri != REGISTRY_SCHEMA:
issues.append("unsupported registry schema")
name = document.get("name")
if "name" in document and (
not isinstance(name, str)
or not 3 <= len(name) <= 200
or SERVER_NAME_RE.fullmatch(name) is None
):
issues.append("name must match namespace/server and be 3-200 characters")
description = document.get("description")
if "description" in document and (
not isinstance(description, str) or not 1 <= len(description) <= 100
):
issues.append("description must be a 1-100 character string")
title = document.get("title")
if "title" in document and (
not isinstance(title, str) or not 1 <= len(title) <= 100
):
issues.append("title must be a 1-100 character string")
version = document.get("version")
if "version" in document and (
not isinstance(version, str)
or not 1 <= len(version) <= 255
or VERSION_RANGE_RE.search(version) is not None
or version.casefold() == "latest"
):
issues.append("version must be one concrete 1-255 character version")
remotes = document.get("remotes")
if not isinstance(remotes, list) or not remotes:
issues.append("remote profile requires a non-empty remotes list")
else:
for index, remote in enumerate(remotes):
if not isinstance(remote, dict):
issues.append(f"remotes[{index}] must be an object")
continue
if remote.get("type") not in {"streamable-http", "sse"}:
issues.append(f"remotes[{index}].type must be streamable-http or sse")
remote_url = remote.get("url")
if not isinstance(remote_url, str) or REMOTE_URL_RE.fullmatch(remote_url) is None:
issues.append(f"remotes[{index}].url must be an http(s) URL template")
return issues
def reverse_dns_namespace(domain: str) -> str:
normalized = domain.casefold().rstrip(".")
labels = normalized.split(".")
if len(labels) < 2 or any(DOMAIN_LABEL_RE.fullmatch(label) is None for label in labels):
raise ValueError("publisher domain must be a valid multi-label DNS name")
return ".".join(reversed(labels))
def validate_publisher_namespace(document: object, verified_domain: str) -> list[str]:
"""Check domain ownership outside the server.json shape contract."""
if not isinstance(document, dict) or not isinstance(document.get("name"), str):
return []
namespace = document["name"].partition("/")[0]
expected = reverse_dns_namespace(verified_domain)
if namespace != expected and not namespace.startswith(f"{expected}."):
return [
f"name namespace must be {expected} or its child for verified domain {verified_domain}"
]
return []
def validate_runtime_alignment(document: dict, discovery: object) -> list[str]:
"""Compare publication identity with the live server/discover identity."""
if not isinstance(discovery, dict):
return ["server/discover result must be an object"]
meta = discovery.get("_meta")
server_info = (
meta.get("io.modelcontextprotocol/serverInfo") if isinstance(meta, dict) else None
)
if not isinstance(server_info, dict):
return ["server/discover must include serverInfo for registry drift checks"]
issues: list[str] = []
if server_info.get("name") != document.get("name"):
issues.append("runtime serverInfo.name does not match server.json name")
if server_info.get("version") != document.get("version"):
issues.append("runtime serverInfo.version does not match server.json version")
return issues
@dataclass
class Registry:
publisher_domain: str = PUBLISHER_DOMAIN
entries: dict[str, dict] = field(default_factory=dict)
runtime_discovery: dict[str, dict] = field(default_factory=dict)
def register(self, server: MCPServer) -> None:
document = server.registry_document()
issues = validate_registry_document(document)
issues.extend(validate_publisher_namespace(document, self.publisher_domain))
if issues:
raise ValueError("; ".join(issues))
discovery = server.discover(request_meta())
if "error" in discovery:
raise ValueError("runtime discovery failed")
alignment_issues = validate_runtime_alignment(document, discovery)
if alignment_issues:
raise ValueError("; ".join(alignment_issues))
self.entries[server.name] = deepcopy(document)
self.runtime_discovery[server.name] = deepcopy(discovery)
def search(self, query: str) -> list[str]:
needle = query.casefold()
return sorted(
name
for name, entry in self.entries.items()
if needle in name.casefold()
or needle in entry["title"].casefold()
or needle in entry["description"].casefold()
)
def build_readonly_server() -> MCPServer:
server = MCPServer(
name="com.example/internal-readonly",
title="Internal Read-Only Tools",
description="Read-only incident and data lookup tools.",
version="1.0.0",
url="https://mcp.internal.example.com/readonly",
trusted_issuer="https://auth.internal.example.com",
)
server.register(
ToolSchema(
"postgres.readonly",
"postgres:query:readonly",
False,
"Run an approved read-only query.",
{
"type": "object",
"properties": {"sql": {"type": "string"}},
"required": ["sql"],
"additionalProperties": False,
},
),
lambda args: {"rows": [[1]], "sql": args["sql"]},
)
server.register(
ToolSchema(
"s3.list",
"s3:list",
False,
"List objects in one approved bucket.",
{
"type": "object",
"properties": {"bucket": {"type": "string"}},
"required": ["bucket"],
"additionalProperties": False,
},
),
lambda args: {"bucket": args["bucket"], "objects": ["a/b.txt"]},
)
return server
def build_destructive_server() -> MCPServer:
server = MCPServer(
name="com.example/internal-destructive",
title="Internal Destructive Tools",
description="State-changing tools behind explicit approval.",
version="1.0.0",
url="https://mcp.internal.example.com/destructive",
trusted_issuer="https://auth.internal.example.com",
)
server.register(
ToolSchema(
"jira.create",
"jira:write",
True,
"Create one Jira issue after explicit approval.",
{
"type": "object",
"properties": {"title": {"type": "string"}},
"required": ["title"],
"additionalProperties": False,
},
),
lambda args: {"id": "PROJ-99", "title": args["title"], "created": True},
)
return server
def main() -> None:
readonly = build_readonly_server()
destructive = build_destructive_server()
registry = Registry()
registry.register(readonly)
registry.register(destructive)
audit: list[AuditEntry] = []
readonly_token = Token(
"u42",
readonly.trusted_issuer,
readonly.url,
frozenset({"postgres:query:readonly", "s3:list"}),
time.time() + 3_600,
)
approved_token = Token(
"u42",
destructive.trusted_issuer,
destructive.url,
frozenset({"jira:write"}),
time.time() + 3_600,
)
approved_args = {"title": "new bug"}
approval = ApprovalRecord.for_action(
approved_token.user,
"jira.create",
approved_args,
destructive.url,
time.time() + 900,
)
print("=== registry metadata and runtime discovery ===")
print(json.dumps(registry.entries[readonly.name], indent=2))
print(json.dumps(registry.runtime_discovery[readonly.name], indent=2))
print("tools:", json.dumps(readonly.tools_list(request_meta()), indent=2))
print("\n=== policy-gated calls ===")
print(
dispatch(
readonly,
readonly_token,
"postgres.readonly",
{"sql": "SELECT 1"},
request_meta(),
audit,
)
)
print(
dispatch(
destructive,
approved_token,
"jira.create",
approved_args,
request_meta(),
audit,
approval,
)
)
print("\n=== audit log ===")
for entry in audit:
print(json.dumps(asdict(entry), sort_keys=True))
if __name__ == "__main__":
main()