@vitemcp/server 1.5.0 → 1.6.0

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.cjs CHANGED
@@ -573,7 +573,9 @@ var ViteMCP = class {
573
573
  async embedded(uri) {
574
574
  const direct = this.#resources.find((resource) => resource.uri === uri);
575
575
  if (direct) {
576
- const loaded = await direct.load(this.#makeContext(void 0, void 0));
576
+ const loaded = await direct.load(
577
+ this.#makeContext(void 0, void 0).context
578
+ );
577
579
  const first = Array.isArray(loaded) ? loaded[0] : loaded;
578
580
  if (!first) {
579
581
  throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {
@@ -589,7 +591,7 @@ var ViteMCP = class {
589
591
  }
590
592
  const loaded = await template.load(
591
593
  params,
592
- this.#makeContext(void 0, void 0)
594
+ this.#makeContext(void 0, void 0).context
593
595
  );
594
596
  const first = Array.isArray(loaded) ? loaded[0] : loaded;
595
597
  if (!first) {
@@ -748,13 +750,14 @@ var ViteMCP = class {
748
750
  )
749
751
  },
750
752
  (async (args, ctx) => {
751
- const context = this.#makeContext(auth, ctx);
753
+ const timeout = tool.timeoutMs ? { controller: new AbortController(), ms: tool.timeoutMs } : void 0;
754
+ const { context, release } = this.#makeContext(
755
+ auth,
756
+ ctx,
757
+ _optionalChain([timeout, 'optionalAccess', _23 => _23.controller, 'access', _24 => _24.signal])
758
+ );
752
759
  try {
753
- const result = await (tool.timeoutMs ? withTimeout(
754
- tool.execute(args, context),
755
- tool.timeoutMs,
756
- tool.name
757
- ) : tool.execute(args, context));
760
+ const result = await (timeout ? withTimeout(tool.execute(args, context), timeout, tool.name) : tool.execute(args, context));
758
761
  return normalizeToolResult(result, tool.outputSchema !== void 0);
759
762
  } catch (error) {
760
763
  if (error instanceof UserError) {
@@ -765,6 +768,8 @@ var ViteMCP = class {
765
768
  };
766
769
  }
767
770
  throw error;
771
+ } finally {
772
+ release();
768
773
  }
769
774
  })
770
775
  );
@@ -782,16 +787,20 @@ var ViteMCP = class {
782
787
  mimeType: resource.mimeType
783
788
  },
784
789
  (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: _nullishCoalesce(body.mimeType, () => ( resource.mimeType)),
792
- uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
793
- }))
794
- };
790
+ const { context, release } = this.#makeContext(auth, ctx);
791
+ try {
792
+ const loaded = await resource.load(context);
793
+ const bodies = Array.isArray(loaded) ? loaded : [loaded];
794
+ return {
795
+ contents: bodies.map((body) => ({
796
+ ...body,
797
+ mimeType: _nullishCoalesce(body.mimeType, () => ( resource.mimeType)),
798
+ uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
799
+ }))
800
+ };
801
+ } finally {
802
+ release();
803
+ }
795
804
  })
796
805
  );
797
806
  }
@@ -818,16 +827,20 @@ var ViteMCP = class {
818
827
  mimeType: template.mimeType
819
828
  },
820
829
  (async (uri, args, ctx) => {
821
- const context = this.#makeContext(auth, ctx);
822
- const loaded = await template.load(_nullishCoalesce(args, () => ( {})), context);
823
- const bodies = Array.isArray(loaded) ? loaded : [loaded];
824
- return {
825
- contents: bodies.map((body) => ({
826
- ...body,
827
- mimeType: _nullishCoalesce(body.mimeType, () => ( template.mimeType)),
828
- uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
829
- }))
830
- };
830
+ const { context, release } = this.#makeContext(auth, ctx);
831
+ try {
832
+ const loaded = await template.load(_nullishCoalesce(args, () => ( {})), context);
833
+ const bodies = Array.isArray(loaded) ? loaded : [loaded];
834
+ return {
835
+ contents: bodies.map((body) => ({
836
+ ...body,
837
+ mimeType: _nullishCoalesce(body.mimeType, () => ( template.mimeType)),
838
+ uri: _nullishCoalesce(body.uri, () => ( uri.toString()))
839
+ }))
840
+ };
841
+ } finally {
842
+ release();
843
+ }
831
844
  })
832
845
  );
833
846
  }
@@ -842,19 +855,23 @@ var ViteMCP = class {
842
855
  description: prompt.description
843
856
  },
844
857
  (async (args, ctx) => {
845
- const context = this.#makeContext(auth, ctx);
846
- const loaded = await prompt.load(_nullishCoalesce(args, () => ( {})), context);
847
- if (typeof loaded !== "string") {
848
- return loaded;
858
+ const { context, release } = this.#makeContext(auth, ctx);
859
+ try {
860
+ const loaded = await prompt.load(_nullishCoalesce(args, () => ( {})), context);
861
+ if (typeof loaded !== "string") {
862
+ return loaded;
863
+ }
864
+ return {
865
+ messages: [
866
+ {
867
+ content: { text: loaded, type: "text" },
868
+ role: "user"
869
+ }
870
+ ]
871
+ };
872
+ } finally {
873
+ release();
849
874
  }
850
- return {
851
- messages: [
852
- {
853
- content: { text: loaded, type: "text" },
854
- role: "user"
855
- }
856
- ]
857
- };
858
875
  })
859
876
  );
860
877
  }
@@ -869,54 +886,70 @@ var ViteMCP = class {
869
886
  );
870
887
  return app;
871
888
  }
872
- /** Bridges the v2 per-request context onto ViteMCP's `Context`. */
873
- #makeContext(auth, rawCtx) {
889
+ /**
890
+ * Bridges the v2 per-request context onto ViteMCP's `Context`.
891
+ *
892
+ * `timeoutSignal` is folded into `context.signal` for a tool that declares
893
+ * `timeoutMs`; everything else mirrors the SDK's request signal alone. Call
894
+ * `release()` once the handler has settled — see {@link requestScope}.
895
+ */
896
+ #makeContext(auth, rawCtx, timeoutSignal) {
874
897
  const ctx = rawCtx;
875
- const mcpReq = _optionalChain([ctx, 'optionalAccess', _23 => _23.mcpReq]);
876
- const requestedLevel = _optionalChain([mcpReq, 'optionalAccess', _24 => _24._meta, 'optionalAccess', _25 => _25["io.modelcontextprotocol/logLevel"]]);
898
+ const mcpReq = _optionalChain([ctx, 'optionalAccess', _25 => _25.mcpReq]);
899
+ const requestedLevel = _optionalChain([mcpReq, 'optionalAccess', _26 => _26._meta, 'optionalAccess', _27 => _27["io.modelcontextprotocol/logLevel"]]);
877
900
  const emit = (level, message, data) => {
878
901
  if (!requestedLevel) {
879
902
  return;
880
903
  }
881
- void _optionalChain([mcpReq, 'optionalAccess', _26 => _26.notify, 'optionalCall', _27 => _27({
904
+ void _optionalChain([mcpReq, 'optionalAccess', _28 => _28.notify, 'optionalCall', _29 => _29({
882
905
  method: "notifications/message",
883
906
  params: { data: { context: data, message }, level }
884
- }), 'optionalAccess', _28 => _28.catch, 'call', _29 => _29(() => {
907
+ }), 'optionalAccess', _30 => _30.catch, 'call', _31 => _31(() => {
885
908
  })]);
886
909
  };
910
+ const scope = requestScope(_optionalChain([mcpReq, 'optionalAccess', _32 => _32.signal]), timeoutSignal);
887
911
  return {
888
- auth,
889
- elicit: (params) => _server.inputRequired.elicit({
890
- message: params.message,
891
- requestedSchema: params.requestedSchema
892
- }),
893
- input: (key, schema) => _server.acceptedContent.call(void 0, _optionalChain([mcpReq, 'optionalAccess', _30 => _30.inputResponses]), key, schema),
894
- inputRequired: (inputRequests, requestState) => _server.inputRequired.call(void 0, { inputRequests, requestState }),
895
- inputResponses: _optionalChain([mcpReq, 'optionalAccess', _31 => _31.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 = _optionalChain([mcpReq, 'optionalAccess', _32 => _32._meta, 'optionalAccess', _33 => _33.progressToken]);
904
- if (progressToken === void 0) {
905
- return;
906
- }
907
- await _optionalChain([mcpReq, 'optionalAccess', _34 => _34.notify, 'optionalCall', _35 => _35({
908
- method: "notifications/progress",
909
- params: {
910
- message: progress.message,
911
- progress: progress.progress,
912
- progressToken,
913
- total: progress.total
912
+ context: {
913
+ auth,
914
+ elicit: (params) => _server.inputRequired.elicit({
915
+ message: params.message,
916
+ requestedSchema: params.requestedSchema
917
+ }),
918
+ input: (key, schema) => _server.acceptedContent.call(void 0,
919
+ _optionalChain([mcpReq, 'optionalAccess', _33 => _33.inputResponses]),
920
+ key,
921
+ schema
922
+ ),
923
+ inputRequired: (inputRequests, requestState) => _server.inputRequired.call(void 0, { inputRequests, requestState }),
924
+ inputResponses: _optionalChain([mcpReq, 'optionalAccess', _34 => _34.inputResponses]),
925
+ log: {
926
+ debug: (m, d) => emit("debug", m, d),
927
+ error: (m, d) => emit("error", m, d),
928
+ info: (m, d) => emit("info", m, d),
929
+ warn: (m, d) => emit("warning", m, d)
930
+ },
931
+ reportProgress: async (progress) => {
932
+ const progressToken = _optionalChain([mcpReq, 'optionalAccess', _35 => _35._meta, 'optionalAccess', _36 => _36.progressToken]);
933
+ if (progressToken === void 0) {
934
+ return;
914
935
  }
915
- })]);
936
+ await _optionalChain([mcpReq, 'optionalAccess', _37 => _37.notify, 'optionalCall', _38 => _38({
937
+ method: "notifications/progress",
938
+ params: {
939
+ message: progress.message,
940
+ progress: progress.progress,
941
+ progressToken,
942
+ total: progress.total
943
+ }
944
+ })]);
945
+ },
946
+ requestId: _optionalChain([mcpReq, 'optionalAccess', _39 => _39.id]),
947
+ // The SDK exposes this as an accessor; call it so callers get the
948
+ // value.
949
+ requestState: _optionalChain([mcpReq, 'optionalAccess', _40 => _40.requestState, 'optionalCall', _41 => _41()]),
950
+ signal: scope.signal
916
951
  },
917
- requestId: _optionalChain([mcpReq, 'optionalAccess', _36 => _36.id]),
918
- // The SDK exposes this as an accessor; call it so callers get the value.
919
- requestState: _optionalChain([mcpReq, 'optionalAccess', _37 => _37.requestState, 'optionalCall', _38 => _38()])
952
+ release: scope.release
920
953
  };
921
954
  }
922
955
  /**
@@ -925,7 +958,7 @@ var ViteMCP = class {
925
958
  * no addressee on a stateless transport.
926
959
  */
927
960
  #notifyListChanged(kind) {
928
- const notifier = _optionalChain([this, 'access', _39 => _39.#handler, 'optionalAccess', _40 => _40.notify]);
961
+ const notifier = _optionalChain([this, 'access', _42 => _42.#handler, 'optionalAccess', _43 => _43.notify]);
929
962
  if (!notifier) {
930
963
  return;
931
964
  }
@@ -938,7 +971,7 @@ var ViteMCP = class {
938
971
  // Authentication has already run in the route below, which is the only
939
972
  // place that can turn a refusal into an HTTP status. What reaches here
940
973
  // is either an authenticated session or a deliberately anonymous one.
941
- async () => this.#buildServer(_optionalChain([this, 'access', _41 => _41.#authStore, 'access', _42 => _42.getStore, 'call', _43 => _43(), 'optionalAccess', _44 => _44.auth])),
974
+ async () => this.#buildServer(_optionalChain([this, 'access', _44 => _44.#authStore, 'access', _45 => _45.getStore, 'call', _46 => _46(), 'optionalAccess', _47 => _47.auth])),
942
975
  {
943
976
  // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy
944
977
  // requests are answered unadvertised and skip Mcp-* validation.
@@ -948,8 +981,8 @@ var ViteMCP = class {
948
981
  }
949
982
  );
950
983
  this.#corsMiddleware = config.cors === false ? null : _cors.cors.call(void 0, config.cors);
951
- const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _45 => _45.#options, 'access', _46 => _46.auth, 'optionalAccess', _47 => _47.getOAuthConfig, 'call', _48 => _48()])));
952
- if (_optionalChain([oauth, 'optionalAccess', _49 => _49.enabled]) !== false && (_nullishCoalesce(_nullishCoalesce(_optionalChain([oauth, 'optionalAccess', _50 => _50.proxy]), () => ( _optionalChain([oauth, 'optionalAccess', _51 => _51.authorizationServer]))), () => ( _optionalChain([oauth, 'optionalAccess', _52 => _52.protectedResource]))))) {
984
+ const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _48 => _48.#options, 'access', _49 => _49.auth, 'optionalAccess', _50 => _50.getOAuthConfig, 'call', _51 => _51()])));
985
+ if (_optionalChain([oauth, 'optionalAccess', _52 => _52.enabled]) !== false && (_nullishCoalesce(_nullishCoalesce(_optionalChain([oauth, 'optionalAccess', _53 => _53.proxy]), () => ( _optionalChain([oauth, 'optionalAccess', _54 => _54.authorizationServer]))), () => ( _optionalChain([oauth, 'optionalAccess', _55 => _55.protectedResource]))))) {
953
986
  this.#honoApp.route(
954
987
  "/",
955
988
  createOAuthRouter({
@@ -963,10 +996,10 @@ var ViteMCP = class {
963
996
  this.#servesProtectedResourceMetadata = Boolean(oauth.protectedResource);
964
997
  }
965
998
  const health = this.#options.health;
966
- if (_optionalChain([health, 'optionalAccess', _53 => _53.enabled]) !== false) {
999
+ if (_optionalChain([health, 'optionalAccess', _56 => _56.enabled]) !== false) {
967
1000
  this.#honoApp.get(
968
- _nullishCoalesce(_optionalChain([health, 'optionalAccess', _54 => _54.path]), () => ( "/health")),
969
- (c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _55 => _55.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _56 => _56.status]), () => ( 200)))
1001
+ _nullishCoalesce(_optionalChain([health, 'optionalAccess', _57 => _57.path]), () => ( "/health")),
1002
+ (c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _58 => _58.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _59 => _59.status]), () => ( 200)))
970
1003
  );
971
1004
  }
972
1005
  const endpoint = `${_nullishCoalesce(config.basePath, () => ( ""))}${_nullishCoalesce(config.endpoint, () => ( "/mcp"))}`;
@@ -1003,7 +1036,7 @@ var ViteMCP = class {
1003
1036
  "Content-Type": "application/json"
1004
1037
  });
1005
1038
  req.resume();
1006
- res.once("finish", () => _optionalChain([res, 'access', _57 => _57.socket, 'optionalAccess', _58 => _58.end, 'call', _59 => _59()]));
1039
+ res.once("finish", () => _optionalChain([res, 'access', _60 => _60.socket, 'optionalAccess', _61 => _61.end, 'call', _62 => _62()]));
1007
1040
  res.end(
1008
1041
  JSON.stringify({
1009
1042
  error: "invalid_request",
@@ -1013,7 +1046,7 @@ var ViteMCP = class {
1013
1046
  return;
1014
1047
  }
1015
1048
  const response = await app.fetch(
1016
- nodeToWebRequest(req, body, useTls),
1049
+ nodeToWebRequest(req, body, useTls, clientDisconnectSignal(res)),
1017
1050
  {
1018
1051
  incoming: req,
1019
1052
  outgoing: res
@@ -1066,7 +1099,7 @@ var ViteMCP = class {
1066
1099
  return void 0;
1067
1100
  }
1068
1101
  const standard = schema["~standard"];
1069
- if (_optionalChain([standard, 'optionalAccess', _60 => _60.jsonSchema])) {
1102
+ if (_optionalChain([standard, 'optionalAccess', _63 => _63.jsonSchema])) {
1070
1103
  return schema;
1071
1104
  }
1072
1105
  try {
@@ -1100,7 +1133,7 @@ var ViteMCP = class {
1100
1133
  );
1101
1134
  }
1102
1135
  };
1103
- var nodeToWebRequest = (req, body, secure) => {
1136
+ var nodeToWebRequest = (req, body, secure, signal) => {
1104
1137
  const host = _nullishCoalesce(req.headers.host, () => ( "localhost"));
1105
1138
  const url = `${secure ? "https" : "http"}://${host}${_nullishCoalesce(req.url, () => ( "/"))}`;
1106
1139
  const headers = new Headers();
@@ -1121,20 +1154,53 @@ var nodeToWebRequest = (req, body, secure) => {
1121
1154
  return new Request(url, {
1122
1155
  headers,
1123
1156
  method,
1157
+ signal,
1124
1158
  ...hasBody ? { body } : {}
1125
1159
  });
1126
1160
  };
1127
- var withTimeout = (work, timeoutMs, toolName) => new Promise((resolve, reject) => {
1161
+ var clientDisconnectSignal = (res) => {
1162
+ const controller = new AbortController();
1163
+ const abortIfPremature = () => {
1164
+ if (!res.writableEnded) {
1165
+ controller.abort(new Error("Client disconnected"));
1166
+ }
1167
+ };
1168
+ if (res.closed) {
1169
+ abortIfPremature();
1170
+ } else {
1171
+ res.once("close", abortIfPremature);
1172
+ }
1173
+ return controller.signal;
1174
+ };
1175
+ var withTimeout = (work, timeout, toolName) => new Promise((resolve, reject) => {
1128
1176
  const timer = setTimeout(() => {
1129
- reject(
1130
- new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {
1131
- timeoutMs,
1132
- toolName
1133
- })
1177
+ const error = new UserError(
1178
+ `Tool '${toolName}' timed out after ${timeout.ms}ms`,
1179
+ { timeoutMs: timeout.ms, toolName }
1134
1180
  );
1135
- }, timeoutMs);
1181
+ timeout.controller.abort(error);
1182
+ reject(error);
1183
+ }, timeout.ms);
1136
1184
  work.then(resolve, reject).finally(() => clearTimeout(timer));
1137
1185
  });
1186
+ var requestScope = (...sources) => {
1187
+ const controller = new AbortController();
1188
+ const detach = new AbortController();
1189
+ for (const source of sources) {
1190
+ if (source === void 0) {
1191
+ continue;
1192
+ }
1193
+ if (source.aborted) {
1194
+ controller.abort(source.reason);
1195
+ break;
1196
+ }
1197
+ source.addEventListener("abort", () => controller.abort(source.reason), {
1198
+ once: true,
1199
+ signal: detach.signal
1200
+ });
1201
+ }
1202
+ return { release: () => detach.abort(), signal: controller.signal };
1203
+ };
1138
1204
  var formatBytes = (bytes) => {
1139
1205
  if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {
1140
1206
  return `${bytes / (1024 * 1024)} MiB`;
@@ -1166,8 +1232,8 @@ var assertStandardSchema = (schema, toolName, field) => {
1166
1232
  if (schema === void 0) {
1167
1233
  return;
1168
1234
  }
1169
- const standard = _optionalChain([schema, 'optionalAccess', _61 => _61["~standard"]]);
1170
- if (typeof _optionalChain([standard, 'optionalAccess', _62 => _62.validate]) !== "function") {
1235
+ const standard = _optionalChain([schema, 'optionalAccess', _64 => _64["~standard"]]);
1236
+ if (typeof _optionalChain([standard, 'optionalAccess', _65 => _65.validate]) !== "function") {
1171
1237
  throw new UnexpectedStateError(
1172
1238
  `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,
1173
1239
  { toolName }
@@ -1176,13 +1242,13 @@ var assertStandardSchema = (schema, toolName, field) => {
1176
1242
  };
1177
1243
  var promptArgsSchema = (prompt) => {
1178
1244
  const args = prompt.arguments;
1179
- if (!_optionalChain([args, 'optionalAccess', _63 => _63.length])) {
1245
+ if (!_optionalChain([args, 'optionalAccess', _66 => _66.length])) {
1180
1246
  return void 0;
1181
1247
  }
1182
1248
  const shape = {};
1183
1249
  for (const arg of args) {
1184
1250
  const completer = _nullishCoalesce(arg.complete, () => ( (prompt.complete ? (value) => prompt.complete(arg.name, value) : void 0)));
1185
- const valueSchema = _optionalChain([arg, 'access', _64 => _64.enum, 'optionalAccess', _65 => _65.length]) ? _zod.z.enum(arg.enum) : _zod.z.string();
1251
+ const valueSchema = _optionalChain([arg, 'access', _67 => _67.enum, 'optionalAccess', _68 => _68.length]) ? _zod.z.enum(arg.enum) : _zod.z.string();
1186
1252
  const described = arg.description ? valueSchema.describe(arg.description) : valueSchema;
1187
1253
  const base = completer ? _server.completable.call(void 0,
1188
1254
  described,