@modelcontextprotocol%2Fsdk@1.29.0.patch 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. diff --git a/dist/cjs/client/index.d.ts b/dist/cjs/client/index.d.ts
  2. index 1822bf749aec71d2bb295083d832114ee187bb67..58b859a7b32222fb5cb9f2011fdc5d010f3d05fb 100644
  3. --- a/dist/cjs/client/index.d.ts
  4. +++ b/dist/cjs/client/index.d.ts
  5. @@ -428,6 +428,8 @@ export declare class Client<RequestT extends Request = Request, NotificationT ex
  6. *
  7. * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
  8. */
  9. + callTool(params: CallToolRequest['params'], resultSchema?: undefined, options?: RequestOptions): Promise<SchemaOutput<typeof CallToolResultSchema>>;
  10. + callTool<T extends typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema>(params: CallToolRequest['params'], resultSchema: T, options?: RequestOptions): Promise<SchemaOutput<T>>;
  11. callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{
  12. [x: string]: unknown;
  13. content: ({
  14. diff --git a/dist/esm/client/index.d.ts b/dist/esm/client/index.d.ts
  15. index 1822bf749aec71d2bb295083d832114ee187bb67..58b859a7b32222fb5cb9f2011fdc5d010f3d05fb 100644
  16. --- a/dist/esm/client/index.d.ts
  17. +++ b/dist/esm/client/index.d.ts
  18. @@ -428,6 +428,8 @@ export declare class Client<RequestT extends Request = Request, NotificationT ex
  19. *
  20. * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
  21. */
  22. + callTool(params: CallToolRequest['params'], resultSchema?: undefined, options?: RequestOptions): Promise<SchemaOutput<typeof CallToolResultSchema>>;
  23. + callTool<T extends typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema>(params: CallToolRequest['params'], resultSchema: T, options?: RequestOptions): Promise<SchemaOutput<T>>;
  24. callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{
  25. [x: string]: unknown;
  26. content: ({
  27. diff --git a/dist/cjs/client/index.js b/dist/cjs/client/index.js
  28. index 6ac1da14dc7f6211ae70f7711c124b76098816d8..adb5b7bd45514a406a0f7e40b64631c101584c84 100644
  29. --- a/dist/cjs/client/index.js
  30. +++ b/dist/cjs/client/index.js
  31. @@ -288,41 +288,16 @@ class Client extends protocol_js_1.Protocol {
  32. }
  33. async connect(transport, options) {
  34. await super.connect(transport);
  35. + transport.onsessionexpired = async () => {
  36. + await this._initialize(transport);
  37. + };
  38. // When transport sessionId is already set this means we are trying to reconnect.
  39. // In this case we don't need to initialize again.
  40. if (transport.sessionId !== undefined) {
  41. return;
  42. }
  43. try {
  44. - const result = await this.request({
  45. - method: 'initialize',
  46. - params: {
  47. - protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION,
  48. - capabilities: this._capabilities,
  49. - clientInfo: this._clientInfo
  50. - }
  51. - }, types_js_1.InitializeResultSchema, options);
  52. - if (result === undefined) {
  53. - throw new Error(`Server sent invalid initialize result: ${result}`);
  54. - }
  55. - if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
  56. - throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
  57. - }
  58. - this._serverCapabilities = result.capabilities;
  59. - this._serverVersion = result.serverInfo;
  60. - // HTTP transports must set the protocol version in each header after initialization.
  61. - if (transport.setProtocolVersion) {
  62. - transport.setProtocolVersion(result.protocolVersion);
  63. - }
  64. - this._instructions = result.instructions;
  65. - await this.notification({
  66. - method: 'notifications/initialized'
  67. - });
  68. - // Set up list changed handlers now that we know server capabilities
  69. - if (this._pendingListChangedConfig) {
  70. - this._setupListChangedHandlers(this._pendingListChangedConfig);
  71. - this._pendingListChangedConfig = undefined;
  72. - }
  73. + await this._initialize(transport, options);
  74. }
  75. catch (error) {
  76. // Disconnect if initialization fails.
  77. @@ -330,6 +305,37 @@ class Client extends protocol_js_1.Protocol {
  78. throw error;
  79. }
  80. }
  81. + async _initialize(transport, options) {
  82. + const result = await this.request({
  83. + method: 'initialize',
  84. + params: {
  85. + protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION,
  86. + capabilities: this._capabilities,
  87. + clientInfo: this._clientInfo
  88. + }
  89. + }, types_js_1.InitializeResultSchema, options);
  90. + if (result === undefined) {
  91. + throw new Error(`Server sent invalid initialize result: ${result}`);
  92. + }
  93. + if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
  94. + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
  95. + }
  96. + this._serverCapabilities = result.capabilities;
  97. + this._serverVersion = result.serverInfo;
  98. + // HTTP transports must set the protocol version in each header after initialization.
  99. + if (transport.setProtocolVersion) {
  100. + transport.setProtocolVersion(result.protocolVersion);
  101. + }
  102. + this._instructions = result.instructions;
  103. + await this.notification({
  104. + method: 'notifications/initialized'
  105. + });
  106. + // Set up list changed handlers now that we know server capabilities
  107. + if (this._pendingListChangedConfig) {
  108. + this._setupListChangedHandlers(this._pendingListChangedConfig);
  109. + this._pendingListChangedConfig = undefined;
  110. + }
  111. + }
  112. /**
  113. * After initialization has completed, this will be populated with the server's reported capabilities.
  114. */
  115. diff --git a/dist/cjs/client/streamableHttp.js b/dist/cjs/client/streamableHttp.js
  116. index a29a7d3a0f14d9cd800ef5b296485237350c666f..c362ae5fe6c62c8c8eae7e2e61de1eedff5443c9 100644
  117. --- a/dist/cjs/client/streamableHttp.js
  118. +++ b/dist/cjs/client/streamableHttp.js
  119. @@ -290,7 +290,38 @@ class StreamableHTTPClientTransport {
  120. this.onclose?.();
  121. }
  122. async send(message, options) {
  123. + return this._send(message, options, false);
  124. + }
  125. + async _recoverSession(expiredSessionId) {
  126. + if (this._sessionRecovery) {
  127. + await this._sessionRecovery;
  128. + return true;
  129. + }
  130. + if (this._sessionId !== expiredSessionId)
  131. + return true;
  132. + this._sessionId = undefined;
  133. + this._sessionRecovery = Promise.resolve().then(() => this.onsessionexpired?.());
  134. try {
  135. + await this._sessionRecovery;
  136. + }
  137. + catch (error) {
  138. + this._sessionId = undefined;
  139. + await this.close();
  140. + throw error;
  141. + }
  142. + finally {
  143. + this._sessionRecovery = undefined;
  144. + }
  145. + return true;
  146. + }
  147. + async _send(message, options, isSessionRetry) {
  148. + try {
  149. + if (this._sessionRecovery && !(0, types_js_1.isInitializeRequest)(message) && !(0, types_js_1.isInitializedNotification)(message)) {
  150. + await this._sessionRecovery;
  151. + if (options?.isRequestActive?.() === false) {
  152. + throw new Error('Request is no longer active');
  153. + }
  154. + }
  155. const { resumptionToken, onresumptiontoken } = options || {};
  156. if (resumptionToken) {
  157. // If we have at last event ID, we need to reconnect the SSE stream
  158. @@ -298,6 +329,7 @@ class StreamableHTTPClientTransport {
  159. return;
  160. }
  161. const headers = await this._commonHeaders();
  162. + const requestSessionId = headers.get('mcp-session-id') ?? undefined;
  163. headers.set('content-type', 'application/json');
  164. headers.set('accept', 'application/json, text/event-stream');
  165. const init = {
  166. @@ -310,11 +342,20 @@ class StreamableHTTPClientTransport {
  167. const response = await (this._fetch ?? fetch)(this._url, init);
  168. // Handle session ID received during initialization
  169. const sessionId = response.headers.get('mcp-session-id');
  170. - if (sessionId) {
  171. + if (sessionId && (requestSessionId === undefined || this._sessionId === requestSessionId)) {
  172. this._sessionId = sessionId;
  173. }
  174. if (!response.ok) {
  175. const text = await response.text().catch(() => null);
  176. + if (response.status === 404 && requestSessionId && !isSessionRetry && !(0, types_js_1.isInitializedNotification)(message)) {
  177. + const recovered = await this._recoverSession(requestSessionId);
  178. + if (options?.isRequestActive?.() === false) {
  179. + throw new Error('Request is no longer active');
  180. + }
  181. + if (recovered) {
  182. + return this._send(message, options, true);
  183. + }
  184. + }
  185. if (response.status === 401 && this._authProvider) {
  186. // Prevent infinite recursion when server returns 401 after successful auth
  187. if (this._hasCompletedAuthFlow) {
  188. @@ -335,7 +376,7 @@ class StreamableHTTPClientTransport {
  189. // Mark that we completed auth flow
  190. this._hasCompletedAuthFlow = true;
  191. // Purposely _not_ awaited, so we don't call onerror twice
  192. - return this.send(message);
  193. + return this._send(message, options, isSessionRetry);
  194. }
  195. if (response.status === 403 && this._authProvider) {
  196. const { resourceMetadataUrl, scope, error } = (0, auth_js_1.extractWWWAuthenticateParams)(response);
  197. @@ -362,7 +403,7 @@ class StreamableHTTPClientTransport {
  198. if (result !== 'AUTHORIZED') {
  199. throw new auth_js_1.UnauthorizedError();
  200. }
  201. - return this.send(message);
  202. + return this._send(message, options, isSessionRetry);
  203. }
  204. }
  205. throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
  206. diff --git a/dist/cjs/shared/protocol.js b/dist/cjs/shared/protocol.js
  207. index 3617e787f0ba70447c99501aee7aa67584d89758..4a96d6a0328fa348b96f3869ab7e0bb77538182b 100644
  208. --- a/dist/cjs/shared/protocol.js
  209. +++ b/dist/cjs/shared/protocol.js
  210. @@ -744,7 +744,12 @@ class Protocol {
  211. }
  212. else {
  213. // No related task - send through transport normally
  214. - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {
  215. + this._transport.send(jsonrpcRequest, {
  216. + relatedRequestId,
  217. + resumptionToken,
  218. + onresumptiontoken,
  219. + isRequestActive: () => this._responseHandlers.has(messageId)
  220. + }).catch(error => {
  221. this._cleanupTimeout(messageId);
  222. reject(error);
  223. });
  224. diff --git a/dist/cjs/client/auth.d.ts b/dist/cjs/client/auth.d.ts
  225. index f4363ce7c94fbddf0e1d5943b1b26682bdbaa40e..e7dd57096e4f056bcd735d5081433beea1b32f04 100644
  226. --- a/dist/cjs/client/auth.d.ts
  227. +++ b/dist/cjs/client/auth.d.ts
  228. @@ -205,6 +205,15 @@ export declare function parseErrorResponse(input: Response | string): Promise<OA
  229. * @returns A Promise that resolves to an OAuthError instance
  230. */
  231. export declare function parseErrorResponse(input: Response | string): Promise<OAuthError>;
  232. +/**
  233. + * Selects scopes per the MCP spec and augments them for refresh token support.
  234. + */
  235. +export declare function determineScope(options: {
  236. + requestedScope?: string;
  237. + resourceMetadata?: OAuthProtectedResourceMetadata;
  238. + authServerMetadata?: AuthorizationServerMetadata;
  239. + clientMetadata: OAuthClientMetadata;
  240. +}): string | undefined;
  241. /**
  242. * Orchestrates the full auth flow with a server.
  243. *
  244. diff --git a/dist/cjs/client/auth.js b/dist/cjs/client/auth.js
  245. index c2e4fa91d26f5336889f6afa416147db75fc4872..178d7cfd96412d53bc14bbc13a8f76c11f727ee7 100644
  246. --- a/dist/cjs/client/auth.js
  247. +++ b/dist/cjs/client/auth.js
  248. @@ -7,6 +7,7 @@ exports.UnauthorizedError = void 0;
  249. exports.selectClientAuthMethod = selectClientAuthMethod;
  250. exports.parseErrorResponse = parseErrorResponse;
  251. exports.auth = auth;
  252. +exports.determineScope = determineScope;
  253. exports.isHttpsUrl = isHttpsUrl;
  254. exports.selectResourceURL = selectResourceURL;
  255. exports.extractWWWAuthenticateParams = extractWWWAuthenticateParams;
  256. @@ -186,6 +187,19 @@ async function auth(provider, options) {
  257. throw error;
  258. }
  259. }
  260. +/**
  261. + * Selects scopes per the MCP spec and augments them for refresh token support.
  262. + */
  263. +function determineScope({ requestedScope, resourceMetadata, authServerMetadata, clientMetadata }) {
  264. + let effectiveScope = requestedScope || resourceMetadata?.scopes_supported?.join(' ') || clientMetadata.scope;
  265. + if (effectiveScope &&
  266. + authServerMetadata?.scopes_supported?.includes('offline_access') &&
  267. + !effectiveScope.split(' ').includes('offline_access') &&
  268. + clientMetadata.grant_types?.includes('refresh_token')) {
  269. + effectiveScope = `${effectiveScope} offline_access`;
  270. + }
  271. + return effectiveScope;
  272. +}
  273. async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
  274. // Check if the provider has cached discovery state to skip discovery
  275. const cachedState = await provider.discoveryState?.();
  276. @@ -241,12 +255,12 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
  277. });
  278. }
  279. const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  280. - // Apply scope selection strategy (SEP-835):
  281. - // 1. WWW-Authenticate scope (passed via `scope` param)
  282. - // 2. PRM scopes_supported
  283. - // 3. Client metadata scope (user-configured fallback)
  284. - // The resolved scope is used consistently for both DCR and the authorization request.
  285. - const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope;
  286. + const resolvedScope = determineScope({
  287. + requestedScope: scope,
  288. + resourceMetadata,
  289. + authServerMetadata: metadata,
  290. + clientMetadata: provider.clientMetadata
  291. + });
  292. // Handle client registration if needed
  293. let clientInformation = await Promise.resolve(provider.clientInformation());
  294. if (!clientInformation) {
  295. @@ -741,7 +755,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
  296. if (scope) {
  297. authorizationUrl.searchParams.set('scope', scope);
  298. }
  299. - if (scope?.includes('offline_access')) {
  300. + if (scope?.split(' ').includes('offline_access')) {
  301. // if the request includes the OIDC-only "offline_access" scope,
  302. // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access
  303. // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
  304. diff --git a/dist/esm/client/auth.d.ts b/dist/esm/client/auth.d.ts
  305. index f4363ce7c94fbddf0e1d5943b1b26682bdbaa40e..e7dd57096e4f056bcd735d5081433beea1b32f04 100644
  306. --- a/dist/esm/client/auth.d.ts
  307. +++ b/dist/esm/client/auth.d.ts
  308. @@ -205,6 +205,15 @@ export declare function parseErrorResponse(input: Response | string): Promise<OA
  309. * @returns A Promise that resolves to an OAuthError instance
  310. */
  311. export declare function parseErrorResponse(input: Response | string): Promise<OAuthError>;
  312. +/**
  313. + * Selects scopes per the MCP spec and augments them for refresh token support.
  314. + */
  315. +export declare function determineScope(options: {
  316. + requestedScope?: string;
  317. + resourceMetadata?: OAuthProtectedResourceMetadata;
  318. + authServerMetadata?: AuthorizationServerMetadata;
  319. + clientMetadata: OAuthClientMetadata;
  320. +}): string | undefined;
  321. /**
  322. * Orchestrates the full auth flow with a server.
  323. *
  324. diff --git a/dist/esm/client/auth.js b/dist/esm/client/auth.js
  325. index e183040fc2bba22ca1ccc784984f3310854403b7..d367661e580ee61a96654f7af78b2af61dcad98b 100644
  326. --- a/dist/esm/client/auth.js
  327. +++ b/dist/esm/client/auth.js
  328. @@ -161,6 +161,19 @@ export async function auth(provider, options) {
  329. throw error;
  330. }
  331. }
  332. +/**
  333. + * Selects scopes per the MCP spec and augments them for refresh token support.
  334. + */
  335. +export function determineScope({ requestedScope, resourceMetadata, authServerMetadata, clientMetadata }) {
  336. + let effectiveScope = requestedScope || resourceMetadata?.scopes_supported?.join(' ') || clientMetadata.scope;
  337. + if (effectiveScope &&
  338. + authServerMetadata?.scopes_supported?.includes('offline_access') &&
  339. + !effectiveScope.split(' ').includes('offline_access') &&
  340. + clientMetadata.grant_types?.includes('refresh_token')) {
  341. + effectiveScope = `${effectiveScope} offline_access`;
  342. + }
  343. + return effectiveScope;
  344. +}
  345. async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
  346. // Check if the provider has cached discovery state to skip discovery
  347. const cachedState = await provider.discoveryState?.();
  348. @@ -216,12 +229,12 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
  349. });
  350. }
  351. const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  352. - // Apply scope selection strategy (SEP-835):
  353. - // 1. WWW-Authenticate scope (passed via `scope` param)
  354. - // 2. PRM scopes_supported
  355. - // 3. Client metadata scope (user-configured fallback)
  356. - // The resolved scope is used consistently for both DCR and the authorization request.
  357. - const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope;
  358. + const resolvedScope = determineScope({
  359. + requestedScope: scope,
  360. + resourceMetadata,
  361. + authServerMetadata: metadata,
  362. + clientMetadata: provider.clientMetadata
  363. + });
  364. // Handle client registration if needed
  365. let clientInformation = await Promise.resolve(provider.clientInformation());
  366. if (!clientInformation) {
  367. @@ -716,7 +729,7 @@ export async function startAuthorization(authorizationServerUrl, { metadata, cli
  368. if (scope) {
  369. authorizationUrl.searchParams.set('scope', scope);
  370. }
  371. - if (scope?.includes('offline_access')) {
  372. + if (scope?.split(' ').includes('offline_access')) {
  373. // if the request includes the OIDC-only "offline_access" scope,
  374. // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access
  375. // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
  376. diff --git a/dist/esm/client/index.js b/dist/esm/client/index.js
  377. index 49b12c6cd918c457420fef7ad5528a9443d1a191..2afe2e22e960f26c9d516ef135d89f8eb9e4caff 100644
  378. --- a/dist/esm/client/index.js
  379. +++ b/dist/esm/client/index.js
  380. @@ -284,41 +284,16 @@ export class Client extends Protocol {
  381. }
  382. async connect(transport, options) {
  383. await super.connect(transport);
  384. + transport.onsessionexpired = async () => {
  385. + await this._initialize(transport);
  386. + };
  387. // When transport sessionId is already set this means we are trying to reconnect.
  388. // In this case we don't need to initialize again.
  389. if (transport.sessionId !== undefined) {
  390. return;
  391. }
  392. try {
  393. - const result = await this.request({
  394. - method: 'initialize',
  395. - params: {
  396. - protocolVersion: LATEST_PROTOCOL_VERSION,
  397. - capabilities: this._capabilities,
  398. - clientInfo: this._clientInfo
  399. - }
  400. - }, InitializeResultSchema, options);
  401. - if (result === undefined) {
  402. - throw new Error(`Server sent invalid initialize result: ${result}`);
  403. - }
  404. - if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
  405. - throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
  406. - }
  407. - this._serverCapabilities = result.capabilities;
  408. - this._serverVersion = result.serverInfo;
  409. - // HTTP transports must set the protocol version in each header after initialization.
  410. - if (transport.setProtocolVersion) {
  411. - transport.setProtocolVersion(result.protocolVersion);
  412. - }
  413. - this._instructions = result.instructions;
  414. - await this.notification({
  415. - method: 'notifications/initialized'
  416. - });
  417. - // Set up list changed handlers now that we know server capabilities
  418. - if (this._pendingListChangedConfig) {
  419. - this._setupListChangedHandlers(this._pendingListChangedConfig);
  420. - this._pendingListChangedConfig = undefined;
  421. - }
  422. + await this._initialize(transport, options);
  423. }
  424. catch (error) {
  425. // Disconnect if initialization fails.
  426. @@ -326,6 +301,37 @@ export class Client extends Protocol {
  427. throw error;
  428. }
  429. }
  430. + async _initialize(transport, options) {
  431. + const result = await this.request({
  432. + method: 'initialize',
  433. + params: {
  434. + protocolVersion: LATEST_PROTOCOL_VERSION,
  435. + capabilities: this._capabilities,
  436. + clientInfo: this._clientInfo
  437. + }
  438. + }, InitializeResultSchema, options);
  439. + if (result === undefined) {
  440. + throw new Error(`Server sent invalid initialize result: ${result}`);
  441. + }
  442. + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
  443. + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
  444. + }
  445. + this._serverCapabilities = result.capabilities;
  446. + this._serverVersion = result.serverInfo;
  447. + // HTTP transports must set the protocol version in each header after initialization.
  448. + if (transport.setProtocolVersion) {
  449. + transport.setProtocolVersion(result.protocolVersion);
  450. + }
  451. + this._instructions = result.instructions;
  452. + await this.notification({
  453. + method: 'notifications/initialized'
  454. + });
  455. + // Set up list changed handlers now that we know server capabilities
  456. + if (this._pendingListChangedConfig) {
  457. + this._setupListChangedHandlers(this._pendingListChangedConfig);
  458. + this._pendingListChangedConfig = undefined;
  459. + }
  460. + }
  461. /**
  462. * After initialization has completed, this will be populated with the server's reported capabilities.
  463. */
  464. diff --git a/dist/esm/client/streamableHttp.js b/dist/esm/client/streamableHttp.js
  465. index 624172aa24ae255a67c083f9c19053343e4a0581..ac75b14545fda44aff7ff4d97cc5da884fcc627a 100644
  466. --- a/dist/esm/client/streamableHttp.js
  467. +++ b/dist/esm/client/streamableHttp.js
  468. @@ -1,5 +1,5 @@
  469. import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';
  470. -import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';
  471. +import { isInitializedNotification, isInitializeRequest, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';
  472. import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
  473. import { EventSourceParserStream } from 'eventsource-parser/stream';
  474. // Default reconnection options for StreamableHTTP connections
  475. @@ -286,7 +286,38 @@ export class StreamableHTTPClientTransport {
  476. this.onclose?.();
  477. }
  478. async send(message, options) {
  479. + return this._send(message, options, false);
  480. + }
  481. + async _recoverSession(expiredSessionId) {
  482. + if (this._sessionRecovery) {
  483. + await this._sessionRecovery;
  484. + return true;
  485. + }
  486. + if (this._sessionId !== expiredSessionId)
  487. + return true;
  488. + this._sessionId = undefined;
  489. + this._sessionRecovery = Promise.resolve().then(() => this.onsessionexpired?.());
  490. try {
  491. + await this._sessionRecovery;
  492. + }
  493. + catch (error) {
  494. + this._sessionId = undefined;
  495. + await this.close();
  496. + throw error;
  497. + }
  498. + finally {
  499. + this._sessionRecovery = undefined;
  500. + }
  501. + return true;
  502. + }
  503. + async _send(message, options, isSessionRetry) {
  504. + try {
  505. + if (this._sessionRecovery && !isInitializeRequest(message) && !isInitializedNotification(message)) {
  506. + await this._sessionRecovery;
  507. + if (options?.isRequestActive?.() === false) {
  508. + throw new Error('Request is no longer active');
  509. + }
  510. + }
  511. const { resumptionToken, onresumptiontoken } = options || {};
  512. if (resumptionToken) {
  513. // If we have at last event ID, we need to reconnect the SSE stream
  514. @@ -294,6 +325,7 @@ export class StreamableHTTPClientTransport {
  515. return;
  516. }
  517. const headers = await this._commonHeaders();
  518. + const requestSessionId = headers.get('mcp-session-id') ?? undefined;
  519. headers.set('content-type', 'application/json');
  520. headers.set('accept', 'application/json, text/event-stream');
  521. const init = {
  522. @@ -306,11 +338,20 @@ export class StreamableHTTPClientTransport {
  523. const response = await (this._fetch ?? fetch)(this._url, init);
  524. // Handle session ID received during initialization
  525. const sessionId = response.headers.get('mcp-session-id');
  526. - if (sessionId) {
  527. + if (sessionId && (requestSessionId === undefined || this._sessionId === requestSessionId)) {
  528. this._sessionId = sessionId;
  529. }
  530. if (!response.ok) {
  531. const text = await response.text().catch(() => null);
  532. + if (response.status === 404 && requestSessionId && !isSessionRetry && !isInitializedNotification(message)) {
  533. + const recovered = await this._recoverSession(requestSessionId);
  534. + if (options?.isRequestActive?.() === false) {
  535. + throw new Error('Request is no longer active');
  536. + }
  537. + if (recovered) {
  538. + return this._send(message, options, true);
  539. + }
  540. + }
  541. if (response.status === 401 && this._authProvider) {
  542. // Prevent infinite recursion when server returns 401 after successful auth
  543. if (this._hasCompletedAuthFlow) {
  544. @@ -331,7 +372,7 @@ export class StreamableHTTPClientTransport {
  545. // Mark that we completed auth flow
  546. this._hasCompletedAuthFlow = true;
  547. // Purposely _not_ awaited, so we don't call onerror twice
  548. - return this.send(message);
  549. + return this._send(message, options, isSessionRetry);
  550. }
  551. if (response.status === 403 && this._authProvider) {
  552. const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
  553. @@ -358,7 +399,7 @@ export class StreamableHTTPClientTransport {
  554. if (result !== 'AUTHORIZED') {
  555. throw new UnauthorizedError();
  556. }
  557. - return this.send(message);
  558. + return this._send(message, options, isSessionRetry);
  559. }
  560. }
  561. throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
  562. diff --git a/dist/esm/shared/protocol.js b/dist/esm/shared/protocol.js
  563. index bfa2b7120a0f50c569364ea5264e6f811076f44f..abd8dfd707c155f71dae7aeeeeaf7547368ac749 100644
  564. --- a/dist/esm/shared/protocol.js
  565. +++ b/dist/esm/shared/protocol.js
  566. @@ -740,7 +740,12 @@ export class Protocol {
  567. }
  568. else {
  569. // No related task - send through transport normally
  570. - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {
  571. + this._transport.send(jsonrpcRequest, {
  572. + relatedRequestId,
  573. + resumptionToken,
  574. + onresumptiontoken,
  575. + isRequestActive: () => this._responseHandlers.has(messageId)
  576. + }).catch(error => {
  577. this._cleanupTimeout(messageId);
  578. reject(error);
  579. });