Repository navigation
Major Changes
-
1f525a6: Breaking: the existing APIs are replaced by a consolidated API across every entry point, modeled on the Clerk SDKs. Functions drop the
Clerksuffix,mcpAuth,withClerkMcpAuthand the metadata handlers share one options object, and each adapter re-exports./server. The old names are removed without deprecated aliases. The complete migration list follows.Old New Where mcpAuthClerk(Express)mcpAuth({ resourceUrl })./expressmcpAuthClerk(Hono)mcpAuth({ resourceUrl }); install@clerk/backend>= 3.19.0, or supply a compatibleclerkClient./honoawait mcpAuth(verifyToken)mcpAuth({ verifyToken })./expressmcpAuth(verifyToken)mcpAuth({ verifyToken })./honoexperimental_withMcpAuth(aliased aswithMcpAuth) frommcp-adapter, withverifyClerkTokenwithClerkMcpAuth(handler, { resourceUrl })from@clerk/mcp-tools/next./nextprotectedResourceHandlerClerk(properties)protectedResourceMetadataHandler({ resourceUrl, properties })./express,./hono,./nextprotectedResourceHandler({ authServerUrl })For a non-Clerk server, return generateProtectedResourceMetadata({ authServerUrl, resourceUrl, properties })from your own route, withmetadataCorsHeaders. The adapters'protectedResourceMetadataHandlerderives the authorization server from the Clerk publishable key./express,./hono,./nextauthServerMetadataHandlerClerkauthorizationServerMetadataHandler()./express,./hono,./nextmetadataCorsOptionsRequestHandlermetadataCorsHandler./nextstreamableHttpHandler(server)orstreamableHttpHandler(createServer)streamableHttpHandler(createServer, StreamableHTTPServerTransport)./expressstreamableHttpHandler(createServer)streamableHttpHandler(createServer, WebStandardStreamableHTTPServerTransport)./honocompleteOAuthHandlerfrom./nextcompleteOAuthHandlerfrom./next/client./next/clientcorsHeadersmetadataCorsHeaders./servergenerateClerkProtectedResourceMetadatagenerateProtectedResourceMetadata./servergenerateProtectedResourceMetadataoutputSame function name; defaults now contain only resource,authorization_servers, andbearer_methods_supported: ['header']. Add other fields throughproperties; settingproperties.resourcethrows./serverfetchClerkAuthorizationServerMetadatafetchAuthorizationServerMetadata./serververifyClerkTokentoClerkAuthInfo(requestState.toAuth(), token)only afterauthenticateRequest(req, { acceptsToken: 'oauth_token', audience: resourceUrl }); otherwise usemcpAuth({ clerkClient, resourceUrl })orwithClerkMcpAuth(handler, { clerkClient, resourceUrl })./server,./nextgetClientBySessionIdgetMcpClientBySessionId./clientcompleteAuthWithCodecompleteOAuth./clientCreateDynamicallyRegisteredMcpClientParamsCreateDynamicallyRegisteredMcpClientOptions./clientCreateKnownCredentialsMcpClientParamsCreateKnownCredentialsMcpClientOptions./clientMcpClientReturnTypeMcpClientConnection./clientClientDataMcpClientData./clientdefault export of ./stores/fscreateFsStore()./stores/fs./feedback,./create-browser-session./toolssubpath FEEDBACK_KINDS,FEEDBACK_IMPACTSfrom./feedbackSame constants, re-exported from ./tools./toolsSUBMIT_FEEDBACK_DESCRIPTIONfrom./feedbackUse submitFeedbackTool(options)[1].description./toolssubmitFeedbackInputSchemafrom./feedbackUse submitFeedbackTool(options)[1].inputSchema./toolsFeedbackToolExtrafrom./feedbackNot re-exported by ./tools; derive the callback argument type withParameters<SubmitFeedbackTool[2]>[1]./toolsbrowserSessionInputSchemafrom./create-browser-sessionUse createBrowserSessionTool(options)[1].inputSchema./toolsbrowserSessionToolText(destinationUrl)from./create-browser-sessionUse createBrowserSessionTool(options)[1].titleand.description, withoptions.destinationUrl./toolsvalidateBrowserSessionOptions(options)from./create-browser-sessioncreateBrowserSessionTool(options)validates options at setup;createBrowserSession(request, options)validates before making the request./toolsbrowserSessionErrorMessage(error)from./create-browser-sessionThe tool formats its error result's content; for programmatic handling, read_meta[ERROR_CODE_META_KEY], or catchBrowserSessionErrorfromcreateBrowserSessionand use itscode./toolsLegacy root resolution of @clerk/mcp-toolsviamain: "dist/"mainis removed; use an explicit exported subpath such as@clerk/mcp-tools/serveror@clerk/mcp-tools/toolspackage entry ./stores./stores/fs,./stores/redis,./stores/postgres,./stores/sqlitesubpath Other breaking changes:
-
MCP servers are now discoverable by default. A new
discoverableoption onmcpAuth,withClerkMcpAuthand a customverifyToken, also accepted byprotectedResourceMetadataHandler, defaults totrue: anyone can connect (initializewithnotifications/initialized, orserver/discover),ping, and list your tools, resources, resource templates and prompts, with their descriptions and schemas, the protected ones included, without a token. Calling them still needs sign-in, and so donotifications/cancelled,notifications/progress, andnotifications/roots/list_changed, which are not checked against the caller. Setdiscoverable: falseto keep 0.9 behavior, a token for every MCP request. A newpublicAccessoption names the tools, resources and prompts that may also be called without a token; naming any withdiscoverable: falseis a TypeScript error and aClerk error:at startup (empty placeholders,tools: []and[]orfalseforresourcesandprompts, are accepted), and adiscoverableother thantrueorfalsethrows too.discoverableis only about these MCP methods: protected resource metadata (RFC 9728) and the Server Card are public either way, and it is unrelated to OAuth token introspection (RFC 7662). In Express, a discoverablemcpAuthreads the body thatexpress.json()parsed, so mount it beforemcpAuth. Without it, as in Hono after a middleware that readc.req.raw, a request without a token gets the401challenge as in 0.9, andmcpAuthlogs a one-timeClerk warning:naming the fix. If you serve MCP with a stateful transport of your own, one that issues anMcp-Session-Id, setdiscoverable: false: on a discoverable server anyone can open sessions withinitializewithout a token, which hold server state until they time out and which a client without a token can't end, since theDELETEneeds a token and the MCP SDK client doesn't start sign-in for it; and a client that connected without a token keeps itsMcp-Session-Idafter it signs in, so a server that reads the user atinitializeto set up per-session state seesundefinedthere for the signed-in calls that follow.notifications/cancelledandnotifications/progressalways need a token, so a client without one can't cancel or report progress on another user's requests. The statelessstreamableHttpHandlernever starts a session. -
mcpAuthandwithClerkMcpAuthreject unknown option keys at setup with aClerk error:, including typos such asrequiredScopeinstead ofrequiredScopes. A defined, non-functionverifyTokenis also rejected at setup instead of falling through to Clerk verification at request time.onAuthFailureis accepted only by the Next.js auth and metadata handlers;propertiesbelongs only to the metadata handlers. Passing bothclerkClientandverifyTokenalso throws instead of silently using the custom verifier and skipping Clerk's audience check. ChooseclerkClientwithresourceUrl, orverifyToken. -
New in 1.0.0: when
resourceUrlis configured and a customverifyTokenreports aresource, it is checked againstresourceUrl. Version 0.9.0 did not perform this check. Letter case in the scheme and host, default ports and the root path's trailing slash are normalized; a non-root trailing slash must match exactly, and a reported resource with a fragment is always rejected. A different resource, such as the bare origin whenresourceUrlincludes/mcp, or/mcp/whenresourceUrlis/mcp, receives a401invalid_tokenchallenge. -
isClerkAuthInfonow requires private object provenance, so a custom verifier cannot forge Clerk identity withextra.verifiedBy: 'clerk'.toClerkAuthInfostill sets that public field, and the adapters preserve provenance when attachingresourceMetadataUrl. Hand-built objects and copies made outside the library fail the guard. -
Clerk-verified tokens must have
resourceUrlas their audience (aud), or they get a401. Your instance must issueaud: Clerk enables it when you add the first MCP server in the Clerk Dashboard. The client must sendresourcematchingresourceUrlwhen requesting a token. The first audience rejection logs aClerk warning:once per auth middleware instance, with these prerequisites and the backend minimum, without logging the token or its claims. The check accepts the forms Clerk issues for it, including the one that keeps a default port with a lowercased scheme and host, sohttps://MCP.example.com:443/mcpmatches anaudofhttps://mcp.example.com:443/mcp. Peer minimums are now@clerk/express2.1.70,@clerk/nextjs7.9.5, and@clerk/backend3.19.0. -
Express uses an absolute-form request-target's scheme and authority for resource selection, authentication challenges, and protected resource metadata, ignoring a conflicting
Hostor forwarded headers. Origin-form requests retain Express'strust proxybehavior; a single configuredresourceUrlremains authoritative. -
In Next.js, the protected resource metadata's
resourceis<origin>/mcp(from the route path) instead of the origin, so tokens issued for the origin are re-challenged. -
A custom
verifyTokenmust return a finiteexpiresAtand a non-emptyclientId, or the token gets a401invalid_tokenchallenge (cause codetoken-claims-missing). MCP authorization 2025-06-18 and later has servers validate tokens per OAuth 2.1 section 5.2, which includes checking expiry, and RFC 9068 section 2.2 makesexpandclient_idREQUIRED in a JWT access token. Auth info fromtoClerkAuthInfoneeds noexpiresAt, but must come fromauthenticateRequest(req, { acceptsToken: 'oauth_token', audience: resourceUrl })viarequestState.toAuth(), never fromauth({ acceptsToken: 'oauth_token' })alone. Otherwise usemcpAuth({ clerkClient, resourceUrl })orwithClerkMcpAuth(handler, { clerkClient, resourceUrl }). The audience check is required by RFC 9068 section 4 and RFC 7519 section 4.1.3; RFC 8707 section 2 relates the requested resource to the token's audience. A NaN or infiniteexpiresAtalso getstoken-claims-missing, nottoken-expired, including on auth info fromtoClerkAuthInfo. Catch the errors your JWT library throws for a token it rejects, such asJWTExpiredfromjose, and returnundefinedor throw anMcpTokenVerificationError, so the token gets the401challenge; any other error the verifier throws gets aserver_erroranswer, and the client keeps the token. -
@modelcontextprotocol/sdkandzodare now optional peers; list them in your own dependencies if you import the SDK or use./tools.
-
Minor Changes
-
b6dfc3c: Add an optional
compareAndSet(key, expected, value)method toMcpClientStore, and implement it in the Redis, Postgres and SQLite stores. When a store has it, the client saves a session only if it is unchanged since the save read it, and otherwise reads it and checks the authorization server binding again. Two processes saving the same session at once, such as two OAuth callbacks or token refreshes, can then no longer both bind it: the later save is rejected for an issuer other than the one the earlier save bound, and overlapping saves for the same issuer keep both changes. A save that loses to other saves 10 times in a row throws. Custom stores withoutcompareAndSetkeep working as before, reading and then writing the session, which leaves that race open; the file system store, meant for development, has nocompareAndSet. -
ae60dea: Add Server Card discovery (beta).
generateServerCardin@clerk/mcp-tools/serverbuilds an MCP Server Card from a validated, supported subset of the extension: name, version, description, optional title, website, icons, repository, and namespaced JSON_meta, with a generated$schemaand static streamable HTTP remote. Public repository, website, and HTTP icon URLs reject credentials, while website fragments remain allowed.serverCardHandlerin@clerk/mcp-tools/honoand@clerk/mcp-tools/nextserves it with public CORS, a weakETagand conditionalGET/HEAD, configurable public caching (an hour by default, with invalid values includingnullrejected at setup), and a421for an origin no listedresourceUrlhas. Versions may be free-form or carryxlabels in prerelease or build metadata, but version ranges are rejected. Every error is sent withCache-Control: no-store. Discovery responses send their ownETag,Cache-Control, andContent-Length, and preserveETagexposure and errorno-store, when earlier middleware sets CORS, validator, cache, or length headers. Neither needs Clerk keys or an MCP SDK.Add AI Catalog discovery (beta).
generateAICatalogin@clerk/mcp-tools/serverbuilds a minimal AI Catalog (specVersion0.9) against the v0.9 release candidate pinned at Agent-Card/ai-catalog@19208af (#141);1.0is reserved for the final specification. Entries link one MCP Server Card by an explicit logical identifier, a requireddisplayName(optional in the RC, but required by Agentic Resource Discovery v0.91), and an https card URL (plain http only on a loopback host, for local development), which may be on another host and is never fetched. An entry may also carry an Agentic Resource Discovery v0.91trustManifest,{ identity, identityType?, attestations? }with an absolute URI identity (nothttp,data,file, orjavascript, nor an https URL with credentials) and attestations of{ type, uri, digest?, mediaType? }whoseuriis an https URL or adata:URI, validated when the catalog is created and emitted as given; omitted, the entry carries no trust data. Card URLs must be exact absolute URLs, without WHATWG URL repair or unescaped Unicode or malformed percent escapes. The RC recommendsurn:air:{publisher}:{name}[:{kind}]; this open identifier format is not enforced as a required scheme.aiCatalogHandlerin@clerk/mcp-tools/honoand@clerk/mcp-tools/nextserves it asapplication/ai-catalog+jsonwith the same public CORS, conditional requests, and caching asserverCardHandler. The Next.js route handlers answer every method a route exports, including their own CORS preflight, so export one handler asGET,HEAD,OPTIONS, and the other methods.Serve both through Express.
serverCardHandlerandaiCatalogHandlerin@clerk/mcp-tools/expressanswer as the Hono handlers do, selecting a listedresourceUrlby the origin Express gives the app (X-Forwarded-*only undertrust proxy), and answering a request without aHostheader that parses with a400only when a list ofresourceUrls needs its origin. The Express Server Card handler varies on forwarded host and protocol headers when a trusted proxy selects a listed resource URL for an origin-form request, by the same rule as the protected-resource metadata handler: only when Express trusts the immediate peer.Document serving the AI Catalog at
/.well-known/ard.json, the canonical path in Agentic Resource Discovery v0.91 section 5.1, as well as at its predecessor path/.well-known/ai-catalog.json. Mount oneaiCatalogHandlerat both paths, in Express, Hono, or Next.js, and both answer with the same body,ETag, caching, and CORS headers; the handler needs no configuration for either path. -
36f9806:
submit_feedbacknow asks agents to report a problem as soon as they find it and then continue the task, instead of once at the end of the task.impactis optional, since an agent reporting mid-task may not know how the task ends yet. A newSUBMIT_FEEDBACK_INSTRUCTIONSexport from@clerk/mcp-tools/toolsholds a sentence to add to your server'sinstructions. This is the wording Clerk's hosted MCP server uses, where it raised how often agents report. -
691eb45: Breaking: raise the optional
@modelcontextprotocol/sdkpeer and development dependency floors to^1.32.0, and the optional@modelcontextprotocol/serverpeer floor to^2.3.0, for upstream security fixes (GHSA-jm63-cq47-j5jp, GHSA-46jr-4wx8-v453 and GHSA-rvq5-wwqv-78pq affect@modelcontextprotocol/server>=2.0.0 <2.3.0). SDK 2.x users now need@modelcontextprotocol/server2.3.0 or later. Preserve the SDK's issuer-bound OAuth client information and tokens across stored sessions. Client credentials are bound to an authorization server before any authorization code is exchanged: dynamically registered credentials to the server that issued them, and known credentials to the server the MCP server names when authorization starts. A session's authorization code, client secret and refresh token are sent only to the server it is bound to, and a bound session does not register at another. The OAuth callback exchanges its code with the authorization server found when authorization started, including one found at a resource metadata URL from the MCP server's challenge, and a start that fails before the redirect leaves its session unbound. Sessions that are not bound, because an earlier version stored them or a sign-in was in progress during the upgrade, keep their access token until it is rejected, but their refresh token and client secret are not sent to any authorization server andcompleteOAuththrows for them: reconnect once withcreateKnownCredentialsMcpClientorcreateDynamicallyRegisteredMcpClient. HTTP clients use the SDK's safer redirect policy; configure the final MCP endpoint URL when a deployment redirects across origins (or redirects in a browser).
Patch Changes
- f3fcaf6:
createBrowserSessionnow awaits its request before returning. A refused request (for example a hostilepath) no longer creates an already-rejected promise that the caller only picks up a microtask later, which runtimes such as workerd report as an unhandled rejection. - f6b7032: Fix Express protected resource metadata caching when
resourceUrlis omitted or a list: origin-form requests from a trusted proxy vary onX-Forwarded-HostandX-Forwarded-Proto, preserving existingVaryfields so shared caches distinguish forwarded origins. - 61a3c1e: Fix two Postgres store bugs.
readnow returns a stored string as the string that was written: it no longer throws for a string that isn't JSON text, such as the session id the client stores for each OAuth state, socompleteOAuthworks with the Postgres store again, and it no longer turns a string such as'123'or'true'into a number or boolean. Stores that start together on a new table no longer fail with a duplicate key error fromCREATE TABLE IF NOT EXISTS: each one creates the table under an advisory lock for the table name. - cca0e40: Warn once at auth setup when
publicAccess.toolslistscreate_browser_session, which requires a Clerk identity: calls without a token otherwise returnnot_authenticatedwithout starting sign-in.