Repository navigation
[P31] server cards: serve and fetch Server Cards (SEP-2127) - #340
Merged
Merged
Conversation
A Server Card is a static document that describes a remote MCP server
before a client connects. The format is the one of the Server Card
extension, modelcontextprotocol/ext-server-card at 526201bb (the
snapshot SEP-2127 cites, and the head of main on 2026-10-28).
ServerCard has the fields of schema.ts. Decoding needs the required
fields and ignores unknown ones; validate() checks the rest: the
$schema value, the reverse-DNS name, version ranges, lengths, URIs and
the remote URL pattern. ServerCard(info:endpoint:protocolVersions:)
builds a card from Server.Info, with name and description overrides,
because Server.Info.name is often not reverse-DNS.
ServerCardValidator serves the card at <endpoint>/server-card as the
extension's discovery.md asks: the card's media type, an ETag, 304 for
a matching If-None-Match, Cache-Control, the CORS headers, HEAD, and
the preflight OPTIONS (If-None-Match is not a CORS-safelisted header).
Applications call response(to:) before their MCP endpoint; in a
transport's pipeline it works too, so the stateless transport passes a
validator's 304 and the stateful transport runs validators for methods
other than GET, POST and DELETE.
ServerCard.fetch sends Accept and If-None-Match, needs https or a
loopback host for the URL and the final URL, refuses bodies over 1 MiB,
and validates. cardURL(forEndpoint:), Remote.url(resolving:) for
{variable} templates, and mismatches(with:) against server/discover,
because a card is advisory. No AI Catalog discovery.
Tests: the extension's valid and invalid examples, copied with their
SHA-256 by scripts/server-card-examples.mjs, the checks, serving and
both transports, and fetching through URLProtocol mocks. The HTTP
example serves a card; the guides and design/server_cards.md describe
it.
- ServerCard.fetch streams the body through the SDK's response body reader and stops after 1 MiB + 1 byte, and refuses a larger Content-Length before reading, instead of buffering the whole response before the size check. - ServerCard.fetch checks each redirect before it is requested, with the OAuth discovery rule (https, or loopback http from loopback http, never a private IP literal); a refused redirect throws insecureURL. StreamingSession takes an optional redirect guard: a task delegate on Apple platforms, the session delegate on swift-corelibs. - The stateful HTTP server transport passes a validator's 304, so a conditional HEAD of the server card is no longer turned into 405. - HEAD of the server card carries Content-Length with the card's length, since its body is empty. - ServerCardValidator.init throws invalidCard when the card does not encode, instead of serving an empty 200 card. - cardURL(forEndpoint:) keeps the endpoint path percent-encoded, so %2F in a segment survives. - Remote.url(resolving:) percent-encodes substituted values except for unreserved characters, so a value cannot add a path, query or user or move the host; a placeholder that starts the URL is inserted as is. - ServerCardTests: the streamed-body test sends 40 MiB and allows up to 20 MiB before the cancellation reaches the mock, and the Content-Length test starts its body 0.2 s after the headers, so a loaded Linux machine does not fail them.
- Remote.url(resolving:) reports the template, not the resolved URL, when the result is not an http or https URL: substituted values can be user secrets (isSecret) and the message reaches logs. - Document that a resolved remote can be plaintext http on any host: the schema allows http:// remotes, and fetch's https rule covers the card, not its remotes. Callers check the scheme before connecting. - Look for x wildcards only in the numeric part of a version, before - or +, so 1.0.0+build.x and 1.0.0-alpha.x are single versions. - validate(), url(resolving:) and ServerCardValidator.init throw untyped errors, as fetch and the rest of the SDK's public API do. The doc still names ServerCardError. - ServerCardError conforms to LocalizedError, with the message as errorDescription, so localizedDescription is not Foundation's generic text.
- Hold the URL passed to fetch to the rules of a redirect target, with loopback hosts allowed: parse it with URLComponents, require a non-empty host, and refuse a private or reserved IP literal (OAuthURLValidator.isPrivateIPHost, which does not block loopback) before any request is made. The URL can come from an AI Catalog, and only the scheme and the loopback exception were checked, so a private or link-local address, an https URL without a host and a bracketed IPv4 or name host were requested. Host names are still not resolved; the documentation says so. - Judge a refused redirect from the hop that sent it (http.url), as OAuthRedirectGuard does, not from the first URL. A chain from loopback http through https back to loopback http was refused by the guard but reported as httpStatus 302 instead of insecureURL. - In Remote.url(resolving:), insert a value as given only when its placeholder starts the template, not whenever nothing was written yet. After a leading placeholder that resolved to nothing, the next value went in unencoded and could set the scheme and host (RFC 3986 §2.1). - Tests: the HEAD 200 and 304 answers of the stateless transport, and the loopback test server closes its socket when binding fails.
This was referenced Nov 25, 2026
varun06
previously approved these changes
Nov 25, 2026
varun06
left a comment
Contributor
There was a problem hiding this comment.
Already reviewed and still looking good.
Base automatically changed from
conformance/p30-spec-deprecations
to
rel/1.0.0
November 25, 2026 12:53
varun06
approved these changes
Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P30 (#341) · next: P32 (#339))conformance/p31-server-cardsconformance/p30-spec-deprecations(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)b433530server cards: serve and fetch Server Cards (SEP-2127)9f193d1server cards: review fixes90db10aserver cards: second-pass review fixesfd88feaserver cards: third-pass review fixesSummary
A Server Card is a static JSON document that describes a remote MCP server before a client connects: its name, version, description, endpoints and the protocol versions they serve.
ServerCardis the document with the checks of its format,ServerCardValidatorserves it at<endpoint>/server-card, andServerCard.fetchreads one. The format is the one of the Server Card extension,modelcontextprotocol/ext-server-cardat526201bb, the snapshot that SEP-2127 cites. Server Cards are outside the protocol: no capability declares them and no message carries them.Changes
The document (
Sources/MCP/Base/ServerCard.swift)ServerCardhas the fields of the extension'sschema.ts:$schema,name,version,description,title,websiteUrl,repository,icons,remotesand_meta, withRepository,Remote,InputandKeyValueInput. Decoding needs the required fields and ignores unknown ones.Remote.TransportTypeandInput.Formatare open structs.validate()andproblems()check what decoding does not: the$schemavalue, the reverse-DNS name with one/, version lengths and ranges, description and title lengths, URIs and the remote URL pattern.ServerCard(info:endpoint:protocolVersions:name:description:)builds a card fromServer.Infowith one Streamable HTTP remote. The name and the description can be passed, becauseServer.Info.nameis often not reverse-DNS andServer.initsets no description.cardURL(forEndpoint:),Remote.url(resolving:)for{variable}templates, andmismatches(with:)against aserver/discoverresult.ServerCardErrorwith an open-structReason.Serving (
Sources/MCP/Base/Transports/HTTPServer/ServerCardValidator.swift)<endpointPath>/server-card: the card asapplication/mcp-server-card+json, anETag(the first 16 bytes of the SHA-256 of the encoded card),Cache-Control: public, max-age=3600(maxAge:) and the CORS headers that the extension'sdiscovery.mdasks for.If-None-Match(weak comparison,*accepted) gets 304 and no body. HEAD gets the headers. OPTIONS gets 204 for a CORS preflight, becauseIf-None-Matchis not a CORS-safelisted header. Other methods get 405.response(to:)answers before the application's MCP endpoint. As anHTTPRequestValidator, it also works first in a transport's pipeline:StatelessHTTPServerTransportpasses a validator's 304 for methods other than POST, andStatefulHTTPServerTransportruns the validators for methods other than GET, POST and DELETE and returns their 2xx answers.HTTPHeaderName.etagand.ifNoneMatch.Fetching
ServerCard.fetch(from:session:)andfetch(from:ifNoneMatch:session:)(FetchResult: the card and itsETag, or not modified). The request sendsAcceptandIf-None-Match. The URL and the URL after redirects must behttps, orhttpon a loopback host. A body over 1 MiB is refused. The card is decoded and validated. On swift-corelibs-foundation the request gets the session'shttpAdditionalHeaders.Example, scripts and docs
Examples/http-serverserves a card; its server name is nowcom.example/http-example, andRouter.initthrows.scripts/server-card-examples.mjscopies the extension's valid and invalid examples, with their SHA-256, intoTests/MCPTests/Generated/ServerCardExamples.swift.design/server_cards.md, the server and client guides (snippetsExamples/Snippets/{Server,Client}/ServerCards.swift), the docs index,rough_edges.md, the migration guide, CHANGELOG,CLAUDE.md. ROADMAP: SEP-2127 Implemented, without AI Catalog discovery.API changes
ServerCard,ServerCard.Repository,.Remote,.Remote.TransportType,.Input,.Input.Format,.KeyValueInputServerCard.validate(),problems(),cardURL(forEndpoint:),mismatches(with:),Remote.url(resolving:)ServerCard.fetch(from:session:),fetch(from:ifNoneMatch:session:),FetchResultServerCardError,ServerCardError.ReasonServerCardValidator,response(to:)HTTPHeaderName.etag,.ifNoneMatchBehavior changes
StatelessHTTPServerTransportpasses a validator's 304 for methods other than POST.StatefulHTTPServerTransportruns its validators for methods other than GET, POST and DELETE, and returns their 2xx answers.Conformance
The harness has no Server Card scenario. Baselines unchanged (empty on every leg). Tier scores 100% at both revisions.
Tests
Tests/MCPTests/ServerCardTests.swift: the extension's valid and invalid examples, the checks, serving through both transports, and fetching throughURLProtocolmocks. Snippet tests for both guides. Atb433530,swift testpasses 1058 swift-testing tests inMCPTestsand 110 snippet tests on macOS, and 1152 tests on Linux (scripts/ci-linux.sh build-test).Review notes
Accept: RFC 9110 lets a server ignore it, and a 406 gains nothing for a document with one representation./.well-known/ai-catalog.json, a separate specification), header values with{variable}, and the MCP Registry'sserver.json.mismatches(with:)reports whatserver/discovercontradicts, and protocol versions the card claims but the server does not serve. Versions the card leaves out are not reported.Verification
swift test; DocC with warnings as errors; doc coverage;swift scripts/weave.swift --check.scripts/run-interop.sh --check; Linuxscripts/ci-linux.sh build-testand the fuzz targets.AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.