|
| 1 | +import { SdkError, SdkErrorCode } from '../errors/sdkErrors.js'; |
| 2 | +import type { JSONObject, Result } from '../types/types.js'; |
| 3 | +import type { AnySchema, SchemaOutput } from '../util/schema.js'; |
| 4 | +import { parseSchema } from '../util/schema.js'; |
| 5 | +import type { BaseContext, NotificationOptions, RequestOptions } from './protocol.js'; |
| 6 | + |
| 7 | +/** |
| 8 | + * The subset of `Client`/`Server` that {@linkcode ExtensionHandle} delegates to. |
| 9 | + * |
| 10 | + * @internal |
| 11 | + */ |
| 12 | +export interface ExtensionHost<ContextT extends BaseContext> { |
| 13 | + setCustomRequestHandler<P extends AnySchema>( |
| 14 | + method: string, |
| 15 | + paramsSchema: P, |
| 16 | + handler: (params: SchemaOutput<P>, ctx: ContextT) => Result | Promise<Result> |
| 17 | + ): void; |
| 18 | + setCustomNotificationHandler<P extends AnySchema>( |
| 19 | + method: string, |
| 20 | + paramsSchema: P, |
| 21 | + handler: (params: SchemaOutput<P>) => void | Promise<void> |
| 22 | + ): void; |
| 23 | + sendCustomRequest<R extends AnySchema>( |
| 24 | + method: string, |
| 25 | + params: Record<string, unknown> | undefined, |
| 26 | + resultSchema: R, |
| 27 | + options?: RequestOptions |
| 28 | + ): Promise<SchemaOutput<R>>; |
| 29 | + sendCustomNotification(method: string, params?: Record<string, unknown>, options?: NotificationOptions): Promise<void>; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Options for {@linkcode Client.extension} / {@linkcode Server.extension}. |
| 34 | + */ |
| 35 | +export interface ExtensionOptions<P extends AnySchema> { |
| 36 | + /** |
| 37 | + * Schema to validate the peer's `capabilities.extensions[id]` blob against. When provided, |
| 38 | + * {@linkcode ExtensionHandle.getPeerSettings | getPeerSettings()} returns the parsed value |
| 39 | + * (typed as `SchemaOutput<P>`) or `undefined` if the peer's blob does not match. |
| 40 | + */ |
| 41 | + peerSchema: P; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * A scoped handle for registering and sending custom JSON-RPC methods belonging to a single |
| 46 | + * SEP-2133 extension. |
| 47 | + * |
| 48 | + * Obtained via {@linkcode Client.extension} or {@linkcode Server.extension}. Creating a handle |
| 49 | + * declares the extension in `capabilities.extensions[id]` so it is advertised during `initialize`. |
| 50 | + * Handlers registered through the handle are thus structurally guaranteed to belong to a declared |
| 51 | + * extension. |
| 52 | + * |
| 53 | + * Send-side methods respect `enforceStrictCapabilities`: when strict, sending throws if the peer |
| 54 | + * did not advertise the same extension ID; when lax (the default), sends proceed regardless and |
| 55 | + * {@linkcode getPeerSettings} returns `undefined`. |
| 56 | + */ |
| 57 | +export class ExtensionHandle<Local extends JSONObject, Peer = JSONObject, ContextT extends BaseContext = BaseContext> { |
| 58 | + private _peerSettingsCache?: { value: Peer | undefined }; |
| 59 | + |
| 60 | + /** |
| 61 | + * @internal Use {@linkcode Client.extension} or {@linkcode Server.extension} to construct. |
| 62 | + */ |
| 63 | + constructor( |
| 64 | + private readonly _host: ExtensionHost<ContextT>, |
| 65 | + /** The SEP-2133 extension identifier (e.g. `io.modelcontextprotocol/ui`). */ |
| 66 | + public readonly id: string, |
| 67 | + /** The local settings object advertised in `capabilities.extensions[id]`. */ |
| 68 | + public readonly settings: Local, |
| 69 | + private readonly _getPeerExtensionSettings: () => JSONObject | undefined, |
| 70 | + private readonly _enforceStrictCapabilities: boolean, |
| 71 | + private readonly _peerSchema?: AnySchema |
| 72 | + ) {} |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns the peer's `capabilities.extensions[id]` settings, or `undefined` if the peer did not |
| 76 | + * advertise this extension or (when `peerSchema` was provided) if the peer's blob fails |
| 77 | + * validation. The result is parsed once and cached. |
| 78 | + */ |
| 79 | + getPeerSettings(): Peer | undefined { |
| 80 | + if (this._peerSettingsCache) { |
| 81 | + return this._peerSettingsCache.value; |
| 82 | + } |
| 83 | + const raw = this._getPeerExtensionSettings(); |
| 84 | + if (raw === undefined) { |
| 85 | + // Don't cache: peer may not have connected yet. |
| 86 | + return undefined; |
| 87 | + } |
| 88 | + let value: Peer | undefined; |
| 89 | + if (this._peerSchema === undefined) { |
| 90 | + value = raw as Peer; |
| 91 | + } else { |
| 92 | + const parsed = parseSchema(this._peerSchema, raw); |
| 93 | + if (parsed.success) { |
| 94 | + value = parsed.data as Peer; |
| 95 | + } else { |
| 96 | + console.warn( |
| 97 | + `[ExtensionHandle] Peer's capabilities.extensions["${this.id}"] failed schema validation: ${parsed.error.message}` |
| 98 | + ); |
| 99 | + value = undefined; |
| 100 | + } |
| 101 | + } |
| 102 | + this._peerSettingsCache = { value }; |
| 103 | + return value; |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Registers a request handler for a custom method belonging to this extension. Delegates to |
| 108 | + * {@linkcode Protocol.setCustomRequestHandler | setCustomRequestHandler}; the collision guard |
| 109 | + * against standard MCP methods applies. |
| 110 | + */ |
| 111 | + setRequestHandler<P extends AnySchema>( |
| 112 | + method: string, |
| 113 | + paramsSchema: P, |
| 114 | + handler: (params: SchemaOutput<P>, ctx: ContextT) => Result | Promise<Result> |
| 115 | + ): void { |
| 116 | + this._host.setCustomRequestHandler(method, paramsSchema, handler); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Registers a notification handler for a custom method belonging to this extension. Delegates |
| 121 | + * to {@linkcode Protocol.setCustomNotificationHandler | setCustomNotificationHandler}. |
| 122 | + */ |
| 123 | + setNotificationHandler<P extends AnySchema>( |
| 124 | + method: string, |
| 125 | + paramsSchema: P, |
| 126 | + handler: (params: SchemaOutput<P>) => void | Promise<void> |
| 127 | + ): void { |
| 128 | + this._host.setCustomNotificationHandler(method, paramsSchema, handler); |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Sends a custom request belonging to this extension and waits for a response. |
| 133 | + * |
| 134 | + * When `enforceStrictCapabilities` is enabled and the peer did not advertise |
| 135 | + * `capabilities.extensions[id]`, throws {@linkcode SdkError} with |
| 136 | + * {@linkcode SdkErrorCode.CapabilityNotSupported}. |
| 137 | + */ |
| 138 | + sendRequest<R extends AnySchema>( |
| 139 | + method: string, |
| 140 | + params: Record<string, unknown> | undefined, |
| 141 | + resultSchema: R, |
| 142 | + options?: RequestOptions |
| 143 | + ): Promise<SchemaOutput<R>> { |
| 144 | + this._assertPeerCapability(method); |
| 145 | + return this._host.sendCustomRequest(method, params, resultSchema, options); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Sends a custom notification belonging to this extension. |
| 150 | + * |
| 151 | + * When `enforceStrictCapabilities` is enabled and the peer did not advertise |
| 152 | + * `capabilities.extensions[id]`, throws {@linkcode SdkError} with |
| 153 | + * {@linkcode SdkErrorCode.CapabilityNotSupported}. |
| 154 | + */ |
| 155 | + sendNotification(method: string, params?: Record<string, unknown>, options?: NotificationOptions): Promise<void> { |
| 156 | + this._assertPeerCapability(method); |
| 157 | + return this._host.sendCustomNotification(method, params, options); |
| 158 | + } |
| 159 | + |
| 160 | + private _assertPeerCapability(method: string): void { |
| 161 | + if (this._enforceStrictCapabilities && this._getPeerExtensionSettings() === undefined) { |
| 162 | + throw new SdkError( |
| 163 | + SdkErrorCode.CapabilityNotSupported, |
| 164 | + `Peer does not support extension "${this.id}" (required for ${method})` |
| 165 | + ); |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments