@vitemcp/server 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ViteMCP.js CHANGED
@@ -201,6 +201,17 @@ var createOAuthRouter = (options) => {
201
201
  return app;
202
202
  };
203
203
 
204
+ // src/cancelResponseBody.ts
205
+ var cancelResponseBody = async (response) => {
206
+ if (!response.body) {
207
+ return;
208
+ }
209
+ try {
210
+ await response.body.cancel();
211
+ } catch {
212
+ }
213
+ };
214
+
204
215
  // src/DiscoveryDocumentCache.ts
205
216
  var DiscoveryDocumentCache = class {
206
217
  get size() {
@@ -288,6 +299,7 @@ var DiscoveryDocumentCache = class {
288
299
  throw error;
289
300
  }
290
301
  if (!res.ok) {
302
+ await cancelResponseBody(res);
291
303
  throw new Error(
292
304
  `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
293
305
  );
@@ -395,6 +407,7 @@ var readMedia = async (source, kind) => {
395
407
  signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS)
396
408
  });
397
409
  if (!response.ok) {
410
+ await cancelResponseBody(response);
398
411
  throw new Error(`Server responded with status: ${response.status}`);
399
412
  }
400
413
  rawData = Buffer.from(await response.arrayBuffer());
@@ -573,7 +586,9 @@ var ViteMCP = class {
573
586
  async embedded(uri) {
574
587
  const direct = this.#resources.find((resource) => resource.uri === uri);
575
588
  if (direct) {
576
- const loaded = await direct.load(this.#makeContext(void 0, void 0));
589
+ const loaded = await direct.load(
590
+ this.#makeContext(void 0, void 0).context
591
+ );
577
592
  const first = Array.isArray(loaded) ? loaded[0] : loaded;
578
593
  if (!first) {
579
594
  throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {
@@ -589,7 +604,7 @@ var ViteMCP = class {
589
604
  }
590
605
  const loaded = await template.load(
591
606
  params,
592
- this.#makeContext(void 0, void 0)
607
+ this.#makeContext(void 0, void 0).context
593
608
  );
594
609
  const first = Array.isArray(loaded) ? loaded[0] : loaded;
595
610
  if (!first) {
@@ -748,13 +763,14 @@ var ViteMCP = class {
748
763
  )
749
764
  },
750
765
  (async (args, ctx) => {
751
- const context = this.#makeContext(auth, ctx);
766
+ const timeout = tool.timeoutMs ? { controller: new AbortController(), ms: tool.timeoutMs } : void 0;
767
+ const { context, release } = this.#makeContext(
768
+ auth,
769
+ ctx,
770
+ timeout?.controller.signal
771
+ );
752
772
  try {
753
- const result = await (tool.timeoutMs ? withTimeout(
754
- tool.execute(args, context),
755
- tool.timeoutMs,
756
- tool.name
757
- ) : tool.execute(args, context));
773
+ const result = await (timeout ? withTimeout(tool.execute(args, context), timeout, tool.name) : tool.execute(args, context));
758
774
  return normalizeToolResult(result, tool.outputSchema !== void 0);
759
775
  } catch (error) {
760
776
  if (error instanceof UserError) {
@@ -765,6 +781,8 @@ var ViteMCP = class {
765
781
  };
766
782
  }
767
783
  throw error;
784
+ } finally {
785
+ release();
768
786
  }
769
787
  })
770
788
  );
@@ -782,16 +800,20 @@ var ViteMCP = class {
782
800
  mimeType: resource.mimeType
783
801
  },
784
802
  (async (uri, ctx) => {
785
- const context = this.#makeContext(auth, ctx);
786
- const loaded = await resource.load(context);
787
- const bodies = Array.isArray(loaded) ? loaded : [loaded];
788
- return {
789
- contents: bodies.map((body) => ({
790
- ...body,
791
- mimeType: body.mimeType ?? resource.mimeType,
792
- uri: body.uri ?? uri.toString()
793
- }))
794
- };
803
+ const { context, release } = this.#makeContext(auth, ctx);
804
+ try {
805
+ const loaded = await resource.load(context);
806
+ const bodies = Array.isArray(loaded) ? loaded : [loaded];
807
+ return {
808
+ contents: bodies.map((body) => ({
809
+ ...body,
810
+ mimeType: body.mimeType ?? resource.mimeType,
811
+ uri: body.uri ?? uri.toString()
812
+ }))
813
+ };
814
+ } finally {
815
+ release();
816
+ }
795
817
  })
796
818
  );
797
819
  }
@@ -818,16 +840,20 @@ var ViteMCP = class {
818
840
  mimeType: template.mimeType
819
841
  },
820
842
  (async (uri, args, ctx) => {
821
- const context = this.#makeContext(auth, ctx);
822
- const loaded = await template.load(args ?? {}, context);
823
- const bodies = Array.isArray(loaded) ? loaded : [loaded];
824
- return {
825
- contents: bodies.map((body) => ({
826
- ...body,
827
- mimeType: body.mimeType ?? template.mimeType,
828
- uri: body.uri ?? uri.toString()
829
- }))
830
- };
843
+ const { context, release } = this.#makeContext(auth, ctx);
844
+ try {
845
+ const loaded = await template.load(args ?? {}, context);
846
+ const bodies = Array.isArray(loaded) ? loaded : [loaded];
847
+ return {
848
+ contents: bodies.map((body) => ({
849
+ ...body,
850
+ mimeType: body.mimeType ?? template.mimeType,
851
+ uri: body.uri ?? uri.toString()
852
+ }))
853
+ };
854
+ } finally {
855
+ release();
856
+ }
831
857
  })
832
858
  );
833
859
  }
@@ -842,19 +868,23 @@ var ViteMCP = class {
842
868
  description: prompt.description
843
869
  },
844
870
  (async (args, ctx) => {
845
- const context = this.#makeContext(auth, ctx);
846
- const loaded = await prompt.load(args ?? {}, context);
847
- if (typeof loaded !== "string") {
848
- return loaded;
871
+ const { context, release } = this.#makeContext(auth, ctx);
872
+ try {
873
+ const loaded = await prompt.load(args ?? {}, context);
874
+ if (typeof loaded !== "string") {
875
+ return loaded;
876
+ }
877
+ return {
878
+ messages: [
879
+ {
880
+ content: { text: loaded, type: "text" },
881
+ role: "user"
882
+ }
883
+ ]
884
+ };
885
+ } finally {
886
+ release();
849
887
  }
850
- return {
851
- messages: [
852
- {
853
- content: { text: loaded, type: "text" },
854
- role: "user"
855
- }
856
- ]
857
- };
858
888
  })
859
889
  );
860
890
  }
@@ -869,8 +899,14 @@ var ViteMCP = class {
869
899
  );
870
900
  return app;
871
901
  }
872
- /** Bridges the v2 per-request context onto ViteMCP's `Context`. */
873
- #makeContext(auth, rawCtx) {
902
+ /**
903
+ * Bridges the v2 per-request context onto ViteMCP's `Context`.
904
+ *
905
+ * `timeoutSignal` is folded into `context.signal` for a tool that declares
906
+ * `timeoutMs`; everything else mirrors the SDK's request signal alone. Call
907
+ * `release()` once the handler has settled — see {@link requestScope}.
908
+ */
909
+ #makeContext(auth, rawCtx, timeoutSignal) {
874
910
  const ctx = rawCtx;
875
911
  const mcpReq = ctx?.mcpReq;
876
912
  const requestedLevel = mcpReq?._meta?.["io.modelcontextprotocol/logLevel"];
@@ -884,39 +920,49 @@ var ViteMCP = class {
884
920
  })?.catch(() => {
885
921
  });
886
922
  };
923
+ const scope = requestScope(mcpReq?.signal, timeoutSignal);
887
924
  return {
888
- auth,
889
- elicit: (params) => inputRequired.elicit({
890
- message: params.message,
891
- requestedSchema: params.requestedSchema
892
- }),
893
- input: (key, schema) => acceptedContent(mcpReq?.inputResponses, key, schema),
894
- inputRequired: (inputRequests, requestState) => inputRequired({ inputRequests, requestState }),
895
- inputResponses: mcpReq?.inputResponses,
896
- log: {
897
- debug: (m, d) => emit("debug", m, d),
898
- error: (m, d) => emit("error", m, d),
899
- info: (m, d) => emit("info", m, d),
900
- warn: (m, d) => emit("warning", m, d)
901
- },
902
- reportProgress: async (progress) => {
903
- const progressToken = mcpReq?._meta?.progressToken;
904
- if (progressToken === void 0) {
905
- return;
906
- }
907
- await mcpReq?.notify?.({
908
- method: "notifications/progress",
909
- params: {
910
- message: progress.message,
911
- progress: progress.progress,
912
- progressToken,
913
- total: progress.total
925
+ context: {
926
+ auth,
927
+ elicit: (params) => inputRequired.elicit({
928
+ message: params.message,
929
+ requestedSchema: params.requestedSchema
930
+ }),
931
+ input: (key, schema) => acceptedContent(
932
+ mcpReq?.inputResponses,
933
+ key,
934
+ schema
935
+ ),
936
+ inputRequired: (inputRequests, requestState) => inputRequired({ inputRequests, requestState }),
937
+ inputResponses: mcpReq?.inputResponses,
938
+ log: {
939
+ debug: (m, d) => emit("debug", m, d),
940
+ error: (m, d) => emit("error", m, d),
941
+ info: (m, d) => emit("info", m, d),
942
+ warn: (m, d) => emit("warning", m, d)
943
+ },
944
+ reportProgress: async (progress) => {
945
+ const progressToken = mcpReq?._meta?.progressToken;
946
+ if (progressToken === void 0) {
947
+ return;
914
948
  }
915
- });
949
+ await mcpReq?.notify?.({
950
+ method: "notifications/progress",
951
+ params: {
952
+ message: progress.message,
953
+ progress: progress.progress,
954
+ progressToken,
955
+ total: progress.total
956
+ }
957
+ });
958
+ },
959
+ requestId: mcpReq?.id,
960
+ // The SDK exposes this as an accessor; call it so callers get the
961
+ // value.
962
+ requestState: mcpReq?.requestState?.(),
963
+ signal: scope.signal
916
964
  },
917
- requestId: mcpReq?.id,
918
- // The SDK exposes this as an accessor; call it so callers get the value.
919
- requestState: mcpReq?.requestState?.()
965
+ release: scope.release
920
966
  };
921
967
  }
922
968
  /**
@@ -1013,7 +1059,7 @@ var ViteMCP = class {
1013
1059
  return;
1014
1060
  }
1015
1061
  const response = await app.fetch(
1016
- nodeToWebRequest(req, body, useTls),
1062
+ nodeToWebRequest(req, body, useTls, clientDisconnectSignal(res)),
1017
1063
  {
1018
1064
  incoming: req,
1019
1065
  outgoing: res
@@ -1100,7 +1146,7 @@ var ViteMCP = class {
1100
1146
  );
1101
1147
  }
1102
1148
  };
1103
- var nodeToWebRequest = (req, body, secure) => {
1149
+ var nodeToWebRequest = (req, body, secure, signal) => {
1104
1150
  const host = req.headers.host ?? "localhost";
1105
1151
  const url = `${secure ? "https" : "http"}://${host}${req.url ?? "/"}`;
1106
1152
  const headers = new Headers();
@@ -1121,20 +1167,53 @@ var nodeToWebRequest = (req, body, secure) => {
1121
1167
  return new Request(url, {
1122
1168
  headers,
1123
1169
  method,
1170
+ signal,
1124
1171
  ...hasBody ? { body } : {}
1125
1172
  });
1126
1173
  };
1127
- var withTimeout = (work, timeoutMs, toolName) => new Promise((resolve, reject) => {
1174
+ var clientDisconnectSignal = (res) => {
1175
+ const controller = new AbortController();
1176
+ const abortIfPremature = () => {
1177
+ if (!res.writableEnded) {
1178
+ controller.abort(new Error("Client disconnected"));
1179
+ }
1180
+ };
1181
+ if (res.closed) {
1182
+ abortIfPremature();
1183
+ } else {
1184
+ res.once("close", abortIfPremature);
1185
+ }
1186
+ return controller.signal;
1187
+ };
1188
+ var withTimeout = (work, timeout, toolName) => new Promise((resolve, reject) => {
1128
1189
  const timer = setTimeout(() => {
1129
- reject(
1130
- new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {
1131
- timeoutMs,
1132
- toolName
1133
- })
1190
+ const error = new UserError(
1191
+ `Tool '${toolName}' timed out after ${timeout.ms}ms`,
1192
+ { timeoutMs: timeout.ms, toolName }
1134
1193
  );
1135
- }, timeoutMs);
1194
+ timeout.controller.abort(error);
1195
+ reject(error);
1196
+ }, timeout.ms);
1136
1197
  work.then(resolve, reject).finally(() => clearTimeout(timer));
1137
1198
  });
1199
+ var requestScope = (...sources) => {
1200
+ const controller = new AbortController();
1201
+ const detach = new AbortController();
1202
+ for (const source of sources) {
1203
+ if (source === void 0) {
1204
+ continue;
1205
+ }
1206
+ if (source.aborted) {
1207
+ controller.abort(source.reason);
1208
+ break;
1209
+ }
1210
+ source.addEventListener("abort", () => controller.abort(source.reason), {
1211
+ once: true,
1212
+ signal: detach.signal
1213
+ });
1214
+ }
1215
+ return { release: () => detach.abort(), signal: controller.signal };
1216
+ };
1138
1217
  var formatBytes = (bytes) => {
1139
1218
  if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {
1140
1219
  return `${bytes / (1024 * 1024)} MiB`;