Skip to content

v1.0.0

Latest

Choose a tag to compare

@clerk-cookie clerk-cookie released this 20 Nov 22:48
· 4 commits to main since this release

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 Clerk suffix, mcpAuth, withClerkMcpAuth and 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 }) ./express
    mcpAuthClerk (Hono) mcpAuth({ resourceUrl }); install @clerk/backend >= 3.19.0, or supply a compatible clerkClient ./hono
    await mcpAuth(verifyToken) mcpAuth({ verifyToken }) ./express
    mcpAuth(verifyToken) mcpAuth({ verifyToken }) ./hono
    experimental_withMcpAuth (aliased as withMcpAuth) from mcp-adapter, with verifyClerkToken withClerkMcpAuth(handler, { resourceUrl }) from @clerk/mcp-tools/next ./next
    protectedResourceHandlerClerk(properties) protectedResourceMetadataHandler({ resourceUrl, properties }) ./express, ./hono, ./next
    protectedResourceHandler({ authServerUrl }) For a non-Clerk server, return generateProtectedResourceMetadata({ authServerUrl, resourceUrl, properties }) from your own route, with metadataCorsHeaders. The adapters' protectedResourceMetadataHandler derives the authorization server from the Clerk publishable key ./express, ./hono, ./next
    authServerMetadataHandlerClerk authorizationServerMetadataHandler() ./express, ./hono, ./next
    metadataCorsOptionsRequestHandler metadataCorsHandler ./next
    streamableHttpHandler(server) or streamableHttpHandler(createServer) streamableHttpHandler(createServer, StreamableHTTPServerTransport) ./express
    streamableHttpHandler(createServer) streamableHttpHandler(createServer, WebStandardStreamableHTTPServerTransport) ./hono
    completeOAuthHandler from ./next completeOAuthHandler from ./next/client ./next/client
    corsHeaders metadataCorsHeaders ./server
    generateClerkProtectedResourceMetadata generateProtectedResourceMetadata ./server
    generateProtectedResourceMetadata output Same function name; defaults now contain only resource, authorization_servers, and bearer_methods_supported: ['header']. Add other fields through properties; setting properties.resource throws ./server
    fetchClerkAuthorizationServerMetadata fetchAuthorizationServerMetadata ./server
    verifyClerkToken toClerkAuthInfo(requestState.toAuth(), token) only after authenticateRequest(req, { acceptsToken: 'oauth_token', audience: resourceUrl }); otherwise use mcpAuth({ clerkClient, resourceUrl }) or withClerkMcpAuth(handler, { clerkClient, resourceUrl }) ./server, ./next
    getClientBySessionId getMcpClientBySessionId ./client
    completeAuthWithCode completeOAuth ./client
    CreateDynamicallyRegisteredMcpClientParams CreateDynamicallyRegisteredMcpClientOptions ./client
    CreateKnownCredentialsMcpClientParams CreateKnownCredentialsMcpClientOptions ./client
    McpClientReturnType McpClientConnection ./client
    ClientData McpClientData ./client
    default export of ./stores/fs createFsStore() ./stores/fs
    ./feedback, ./create-browser-session ./tools subpath
    FEEDBACK_KINDS, FEEDBACK_IMPACTS from ./feedback Same constants, re-exported from ./tools ./tools
    SUBMIT_FEEDBACK_DESCRIPTION from ./feedback Use submitFeedbackTool(options)[1].description ./tools
    submitFeedbackInputSchema from ./feedback Use submitFeedbackTool(options)[1].inputSchema ./tools
    FeedbackToolExtra from ./feedback Not re-exported by ./tools; derive the callback argument type with Parameters<SubmitFeedbackTool[2]>[1] ./tools
    browserSessionInputSchema from ./create-browser-session Use createBrowserSessionTool(options)[1].inputSchema ./tools
    browserSessionToolText(destinationUrl) from ./create-browser-session Use createBrowserSessionTool(options)[1].title and .description, with options.destinationUrl ./tools
    validateBrowserSessionOptions(options) from ./create-browser-session createBrowserSessionTool(options) validates options at setup; createBrowserSession(request, options) validates before making the request ./tools
    browserSessionErrorMessage(error) from ./create-browser-session The tool formats its error result's content; for programmatic handling, read _meta[ERROR_CODE_META_KEY], or catch BrowserSessionError from createBrowserSession and use its code ./tools
    Legacy root resolution of @clerk/mcp-tools via main: "dist/" main is removed; use an explicit exported subpath such as @clerk/mcp-tools/server or @clerk/mcp-tools/tools package entry
    ./stores ./stores/fs, ./stores/redis, ./stores/postgres, ./stores/sqlite subpath

    Other breaking changes:

    • MCP servers are now discoverable by default. A new discoverable option on mcpAuth, withClerkMcpAuth and a custom verifyToken, also accepted by protectedResourceMetadataHandler, defaults to true: anyone can connect (initialize with notifications/initialized, or server/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 do notifications/cancelled, notifications/progress, and notifications/roots/list_changed, which are not checked against the caller. Set discoverable: false to keep 0.9 behavior, a token for every MCP request. A new publicAccess option names the tools, resources and prompts that may also be called without a token; naming any with discoverable: false is a TypeScript error and a Clerk error: at startup (empty placeholders, tools: [] and [] or false for resources and prompts, are accepted), and a discoverable other than true or false throws too. discoverable is 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 discoverable mcpAuth reads the body that express.json() parsed, so mount it before mcpAuth. Without it, as in Hono after a middleware that read c.req.raw, a request without a token gets the 401 challenge as in 0.9, and mcpAuth logs a one-time Clerk warning: naming the fix. If you serve MCP with a stateful transport of your own, one that issues an Mcp-Session-Id, set discoverable: false: on a discoverable server anyone can open sessions with initialize without a token, which hold server state until they time out and which a client without a token can't end, since the DELETE needs a token and the MCP SDK client doesn't start sign-in for it; and a client that connected without a token keeps its Mcp-Session-Id after it signs in, so a server that reads the user at initialize to set up per-session state sees undefined there for the signed-in calls that follow. notifications/cancelled and notifications/progress always need a token, so a client without one can't cancel or report progress on another user's requests. The stateless streamableHttpHandler never starts a session.

    • mcpAuth and withClerkMcpAuth reject unknown option keys at setup with a Clerk error:, including typos such as requiredScope instead of requiredScopes. A defined, non-function verifyToken is also rejected at setup instead of falling through to Clerk verification at request time. onAuthFailure is accepted only by the Next.js auth and metadata handlers; properties belongs only to the metadata handlers. Passing both clerkClient and verifyToken also throws instead of silently using the custom verifier and skipping Clerk's audience check. Choose clerkClient with resourceUrl, or verifyToken.

    • New in 1.0.0: when resourceUrl is configured and a custom verifyToken reports a resource, it is checked against resourceUrl. 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 when resourceUrl includes /mcp, or /mcp/ when resourceUrl is /mcp, receives a 401 invalid_token challenge.

    • isClerkAuthInfo now requires private object provenance, so a custom verifier cannot forge Clerk identity with extra.verifiedBy: 'clerk'. toClerkAuthInfo still sets that public field, and the adapters preserve provenance when attaching resourceMetadataUrl. Hand-built objects and copies made outside the library fail the guard.

    • Clerk-verified tokens must have resourceUrl as their audience (aud), or they get a 401. Your instance must issue aud: Clerk enables it when you add the first MCP server in the Clerk Dashboard. The client must send resource matching resourceUrl when requesting a token. The first audience rejection logs a Clerk 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, so https://MCP.example.com:443/mcp matches an aud of https://mcp.example.com:443/mcp. Peer minimums are now @clerk/express 2.1.70, @clerk/nextjs 7.9.5, and @clerk/backend 3.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 Host or forwarded headers. Origin-form requests retain Express's trust proxy behavior; a single configured resourceUrl remains authoritative.

    • In Next.js, the protected resource metadata's resource is <origin>/mcp (from the route path) instead of the origin, so tokens issued for the origin are re-challenged.

    • A custom verifyToken must return a finite expiresAt and a non-empty clientId, or the token gets a 401 invalid_token challenge (cause code token-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 makes exp and client_id REQUIRED in a JWT access token. Auth info from toClerkAuthInfo needs no expiresAt, but must come from authenticateRequest(req, { acceptsToken: 'oauth_token', audience: resourceUrl }) via requestState.toAuth(), never from auth({ acceptsToken: 'oauth_token' }) alone. Otherwise use mcpAuth({ clerkClient, resourceUrl }) or withClerkMcpAuth(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 infinite expiresAt also gets token-claims-missing, not token-expired, including on auth info from toClerkAuthInfo. Catch the errors your JWT library throws for a token it rejects, such as JWTExpired from jose, and return undefined or throw an McpTokenVerificationError, so the token gets the 401 challenge; any other error the verifier throws gets a server_error answer, and the client keeps the token.

    • @modelcontextprotocol/sdk and zod are 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 to McpClientStore, 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 without compareAndSet keep working as before, reading and then writing the session, which leaves that race open; the file system store, meant for development, has no compareAndSet.

  • ae60dea: Add Server Card discovery (beta). generateServerCard in @clerk/mcp-tools/server builds 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 $schema and static streamable HTTP remote. Public repository, website, and HTTP icon URLs reject credentials, while website fragments remain allowed. serverCardHandler in @clerk/mcp-tools/hono and @clerk/mcp-tools/next serves it with public CORS, a weak ETag and conditional GET/HEAD, configurable public caching (an hour by default, with invalid values including null rejected at setup), and a 421 for an origin no listed resourceUrl has. Versions may be free-form or carry x labels in prerelease or build metadata, but version ranges are rejected. Every error is sent with Cache-Control: no-store. Discovery responses send their own ETag, Cache-Control, and Content-Length, and preserve ETag exposure and error no-store, when earlier middleware sets CORS, validator, cache, or length headers. Neither needs Clerk keys or an MCP SDK.

    Add AI Catalog discovery (beta). generateAICatalog in @clerk/mcp-tools/server builds a minimal AI Catalog (specVersion 0.9) against the v0.9 release candidate pinned at Agent-Card/ai-catalog@19208af (#141); 1.0 is reserved for the final specification. Entries link one MCP Server Card by an explicit logical identifier, a required displayName (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.91 trustManifest, { identity, identityType?, attestations? } with an absolute URI identity (not http, data, file, or javascript, nor an https URL with credentials) and attestations of { type, uri, digest?, mediaType? } whose uri is an https URL or a data: 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 recommends urn:air:{publisher}:{name}[:{kind}]; this open identifier format is not enforced as a required scheme. aiCatalogHandler in @clerk/mcp-tools/hono and @clerk/mcp-tools/next serves it as application/ai-catalog+json with the same public CORS, conditional requests, and caching as serverCardHandler. The Next.js route handlers answer every method a route exports, including their own CORS preflight, so export one handler as GET, HEAD, OPTIONS, and the other methods.

    Serve both through Express. serverCardHandler and aiCatalogHandler in @clerk/mcp-tools/express answer as the Hono handlers do, selecting a listed resourceUrl by the origin Express gives the app (X-Forwarded-* only under trust proxy), and answering a request without a Host header that parses with a 400 only when a list of resourceUrls 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 one aiCatalogHandler at 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_feedback now 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. impact is optional, since an agent reporting mid-task may not know how the task ends yet. A new SUBMIT_FEEDBACK_INSTRUCTIONS export from @clerk/mcp-tools/tools holds a sentence to add to your server's instructions. This is the wording Clerk's hosted MCP server uses, where it raised how often agents report.

  • 691eb45: Breaking: raise the optional @modelcontextprotocol/sdk peer and development dependency floors to ^1.32.0, and the optional @modelcontextprotocol/server peer 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/server 2.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 and completeOAuth throws for them: reconnect once with createKnownCredentialsMcpClient or createDynamicallyRegisteredMcpClient. 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: createBrowserSession now awaits its request before returning. A refused request (for example a hostile path) 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 resourceUrl is omitted or a list: origin-form requests from a trusted proxy vary on X-Forwarded-Host and X-Forwarded-Proto, preserving existing Vary fields so shared caches distinguish forwarded origins.
  • 61a3c1e: Fix two Postgres store bugs. read now 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, so completeOAuth works 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 from CREATE 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.tools lists create_browser_session, which requires a Clerk identity: calls without a token otherwise return not_authenticated without starting sign-in.