MCP Events
This page covers the experimental methods on client.experimental_events, the webhook
handler, and their public types. Create the client with
createMCPClient. See the
MCP Events guide for the application flow.
Setup
experimental_events accepts Experimental_MCPEventsConfig.
In direct mode, the store is required for subscribe, refresh, and unsubscribe.
Alternatively, configure a managed adapter as described below. Discovery works
without configuring either mode. Mount the
webhook handler before subscribing.
The methods below belong to client.experimental_events; they are not standalone imports.
Listing Events
client.experimental_events.list()
Sends events/list and returns one catalog page.
Parameters
The optional argument has these properties:
Returns
Promise<Experimental_ListEventsResult>:
See Experimental_MCPEventDefinition
for the definition fields. Pagination is explicit; this method does not fetch all pages.
Managed Subscriptions
Configure experimental_events: { adapter } to delegate subscription lifecycle
operations to a backend. The adapter configuration requires an
Experimental_MCPEventAdapter from @ai-sdk/mcp. Its
createAdapter({ transport }) method returns Experimental_MCPEventOperations bound
to the authorized account, endpoint and destination by your application or
integration package.
authenticatedTransport and eventsAdapter are supplied by your application.
Use the same authorized account for discovery and subscription management.
Never derive account identity, destination or authorization from model arguments.
Using an Adapter Helper
A backend SDK or application helper can return Experimental_MCPEventAdapter
directly. Pass the helper's result as adapter; you do not need another object
wrapper or an inline createAdapter callback:
The helper holds the authorized account and delivery configuration. AI SDK supplies
the transport type and URL to its createAdapter method internally, so the application
configures that URL only once. When a backend SDK exports this helper, import it
from that SDK instead of an application module. Use the same authorized account
for the MCP transport and the backend's subscription operations.
Implementing an Adapter Helper
Backend integration authors implement createAdapter inside their helper:
These helpers and BackendEventsConfig are illustrative application or backend
SDK code, not AI SDK exports. createBackendEventOperations returns
Experimental_MCPEventOperations bound to the authorized account, endpoint
and destination. The helper above lets an explicit mcpUrl override the transport
URL for backend operations; it does not change the MCP client's transport or
catalog discovery. The backend still authorizes the selected endpoint.
The AI SDK adapter contract is:
The interface is exported as Experimental_MCPEventAdapter. The client
calls createAdapter once, before starting the transport, and uses the returned
operations for managed subscriptions. The return value must be an object with
callable subscribe, getSubscription, listSubscriptions, and unsubscribe
methods. Nullish values, missing or non-callable methods, and Promise/thenable
results reject createMCPClient with MCPClientError before the transport starts.
Errors thrown by createAdapter also reject initialization without starting the
transport. Bound operations are no longer accepted directly in
experimental_events.adapter. To migrate existing subscription operations, wrap them explicitly:
Only reuse bound operations when their account, endpoint and destination are correct
for every client using them. The former subscription operations interface is now
exported as Experimental_MCPEventOperations; Experimental_MCPEventAdapter
names the configured integration with createAdapter.
For HTTP and SSE transport configurations, the context contains a fresh
transport: { type, url } object. url is the configured string, including its
path and query, not a resolved redirect target. Custom MCPTransport instances
receive transport: { type: 'custom' }, with no url property; arbitrary
properties on the instance are not inspected.
This is a description of the transport, not the full configuration or live
instance. Headers, auth providers, fetch functions, session callbacks and
start/send/close methods are not passed to the adapter. The transport
grouping leaves room for other client context without mixing it with transport
metadata. No negotiated protocol version is supplied before initialization.
Return separately bound operations for each client instead of mutating shared
endpoint state. Adapters may prefer their own explicit endpoint override or
resolve a configured endpoint when transport.type is 'custom'. That policy belongs to
the adapter; it does not change the client's transport or catalog discovery.
The managed backend must still authorize an endpoint before sending credentials
there. Receiving the transport URL does not grant that authorization.
Managed Operations Contract
These types are exported as Experimental_ManagedSubscription and
Experimental_ManagedSubscribeInput. Creation requires ttlMs: a positive
integer duration in milliseconds, or null to monitor until stopped. The backend
validates these values and enforces its limits. expiresAt is response-only.
Reuse the same duration and idempotency key when retrying an uncertain create result. The backend calculates the deadline once; a retry must not extend it.
Experimental_MCPEventOperations has four operations:
| Operation | Input | Result |
|---|---|---|
subscribe | Experimental_ManagedSubscribeInput | Experimental_ManagedSubscription |
getSubscription | { id, options? } | Experimental_ManagedSubscription |
listSubscriptions | Optional { cursor?, limit?, status?, options? } | { subscriptions, nextCursor? } |
unsubscribe | { id, options? } | Experimental_ManagedSubscription |
All operations return promises. The client passes inputs, cancellation/timeout options, results and errors through without retries or remapping. The adapter must implement request-option handling and retain actionable backend errors, such as consent required, quota exceeded or temporary unavailability.
Managed IDs identify backend records. expiresAt is the application's monitoring
deadline, not the upstream MCP refreshBefore grant. A pending result means
durable acceptance by the backend; upstream setup may still be running.
Stopping can return cleanupStatus: 'pending' while remote cleanup continues.
The backend owns callback URLs, secrets, upstream subscription calls, verification,
renewal and cleanup. Managed subscribe does not implicitly discover the catalog,
generate a secret, write a local store or call upstream events/subscribe.
getSubscription and listSubscriptions are adapter methods, not MCP wire methods.
The managed facade has no refresh(); the backend renews finite upstream leases
even when the application watch has no deadline.
Persist an application intent and reuse its idempotency key after an uncertain create result, within the backend's documented recovery window. A timeout or aborted request does not prove that a remote subscription was cancelled. Closing the MCP client does not unsubscribe managed watches.
Managed delivery is separate from this client. Use the backend's delivery verifier
and receiver contract; experimental_createMCPEventWebhook serves direct MCP
webhooks. Applications still own authorized routing, durable receipt acceptance
and idempotent work dispatch. The adapter does not invoke event callbacks.
Configuration and Types
Choose either experimental_events: { adapter } or experimental_events: { store }.
Mixing them is rejected in TypeScript and at runtime. validateArguments is a
direct-mode option; managed validation belongs to the backend. The unreleased
events configuration spelling is replaced by experimental_events.
createMCPClient infers Experimental_ManagedMCPClient with
Experimental_ManagedMCPEvents when an adapter is configured. Both modes use
MCPClientConfig, whose experimental_events property accepts the
Experimental_MCPEventsConfig union. Direct clients keep MCPClient and
Experimental_MCPEvents. The input and result types of each mode remain distinct.
Use satisfies MCPClientConfig when saving a configuration to retain inference of
the selected mode. A configuration whose mode is only known at runtime returns a
union of the two client types; it does not promise direct-only methods such as
refresh(). Omit experimental_events entirely for catalog discovery without a
store or adapter.
The remaining subscribe, refresh and unsubscribe sections describe direct mode.
Subscribing to Events
client.experimental_events.subscribe(options)
Discovers the named event, checks webhook support, saves a pending subscription,
and sends events/subscribe.
Parameters
options has type Experimental_SubscribeEventOptions:
Pending records are retained when subscription creation fails, because a timed-out
request might have registered remotely. Obtain the pending record's key from
your application's store and recover with refresh({ key }), or
cancel with unsubscribe({ key }). Both reuse the saved callback
identity even when no server ID was saved. Calling subscribe again
creates a new callback identity.
Returns
Promise<Experimental_SubscribeEventResult>:
The result excludes the signing secret. The store is updated with the server ID, deadline, cursor, and active status before the method resolves.
Refreshing a Subscription
client.experimental_events.refresh(options)
Loads a saved subscription by ID or storage key and sends events/subscribe with
its original name, arguments, callback URL, secret, requested lifetime, and latest
saved cursor.
The subscription is marked pending before renewal. Event deliveries return 503
until the response saves the new expiration and restores active status. If renewal
fails, the record stays pending because the server may have renewed it already;
you can retry refresh or unsubscribe using the saved ID or key.
Verified termination messages for a subscription with a saved ID are handled even
while renewal is pending. For example, if access was revoked, onTerminated can
still run and the saved subscription is removed after successful handling.
Parameters
Provide exactly one of id or key.
Returns
Promise<Experimental_SubscribeEventResult>, with the same fields as
subscribe. The new deadline and cursor are saved locally.
Your application schedules renewal before refreshBefore. The SDK does not run
a background renewal timer. Refresh reuses the saved filters without calling
validateArguments again.
Unsubscribing from Events
client.experimental_events.unsubscribe(options)
Resolves the ID or storage key to the saved name, arguments, and callback URL and
sends events/unsubscribe. It deletes the local record only after the server
succeeds.
Parameters
Provide exactly one of id or key.
Returns
Promise<void>. If the server request fails, the local record is retained.
Calling client.close() only closes the MCP connection; it does not unsubscribe.
Request Options
All four methods accept an options property with the following fields.
The listing method takes { params, options }; the other methods include
options alongside their own parameters.
Errors
The client rejects requests to servers without the events capability.
Subscription lifecycle methods require experimental_events.store; refresh and unsubscribe
also require a known subscription ID or storage key. Subscribe rejects unknown
event names, unsupported delivery modes, invalid callback URLs, signing secrets,
or lifetime settings. These checks use MCPClientError, except URL parsing may
throw TypeError.
MCP request errors, store failures, and application validation errors propagate to the caller. Event requests are not retried by the client's tool-call retry setting. See MCP client error handling.
Webhook Handler
experimental_createMCPEventWebhook()
Creates a Web Request/Response handler for experimental MCP webhook events.
It verifies callback challenges and event signatures using subscriptions saved by
client.experimental_events.subscribe.
Import
import { experimental_createMCPEventWebhook } from "@ai-sdk/mcp"
Example
Mount this route before subscribing. The handler and subscribing client must access the same private subscription store.
Parameters
The argument has type
Experimental_MCPEventWebhookOptions.
Callback Arguments
onEvent receives:
See subscription metadata and event fields for their full types.
onGap and onTerminated receive the same safe subscription metadata and a
messageId from the signed webhook-id header. Each callback receives only its
matching control payload, so no type check is needed. Deduplicate retries by
subscription ID and messageId.
onGapreceivesgap: { type: 'gap', cursor, truncated: true }. It means some events are no longer available for replay. Reconcile application state or notify the agent. The helper addstruncated: trueand saves it with the fresh cursor after the callback resolves. The subscription remains active and event delivery continues.onTerminatedreceivestermination: { type: 'terminated', error: { code, message, data? } }. It means the server has ended the subscription. Inspect the error for the reason and notify the agent. After the callback resolves, the helper deletes the saved subscription record.
Both return 204 after successful handling. State updates also occur when
the corresponding callback is omitted. Callback or storage failures return 503
for retry. Events and gaps return 503 until activation or renewal is persisted.
Termination is also accepted during pending renewal when the subscription ID is
already saved; subscriptions without a saved ID still return 503.
Controls are processed even if the saved expiration has passed. They are never
sent to onEvent or validatePayload. The helper does not run or notify an agent
automatically.
Returns
The handler accepts POST requests with Content-Type: application/json.
Pass the original request body bytes and preserve the mcp_event_subscription
query parameter added by the subscribing client. Do not parse and reserialize
the body before passing it to this handler.
The server must include webhook-id, webhook-timestamp, webhook-signature,
and X-MCP-Subscription-Id. The helper verifies Standard Webhooks v1 HMAC-SHA256
signatures and accepts signing timestamps within five minutes of the current time.
An event's eventId must match webhook-id, and its name must match the subscription.
Event Types
The following types are exported from @ai-sdk/mcp and are experimental.
The shapes below use JSONObject from @ai-sdk/provider for JSON-compatible
filter objects. Request settings are written inline because RequestOptions
is not exported from @ai-sdk/mcp.
Webhook Controls
Experimental_MCPEventControl is the union of the lifecycle payloads. onGap
receives its gap variant; onTerminated receives its terminated variant as
termination:
Unknown extension fields are preserved. Verification challenges are echoed
automatically and do not invoke onEvent, onGap, or onTerminated.
Client Methods
Experimental_MCPEvents describes the client.experimental_events property: