@vitemcp/server 1.3.0 → 1.4.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/README.md CHANGED
@@ -358,6 +358,30 @@ server.addTool({
358
358
 
359
359
  When `outputSchema` is provided, ViteMCP validates `structuredContent` before sending the tool result. Invalid structured output is returned to the client as a tool error instead of silently violating the advertised schema.
360
360
 
361
+ ViteMCP tells a structured payload apart from MCP content blocks by shape, so a payload that looks like one of the other shapes needs saying outright. Return it under `structuredContent` and there is nothing left to infer — the JSON text fallback is still written for you:
362
+
363
+ ```typescript
364
+ server.addTool({
365
+ name: "get-document",
366
+ parameters: z.object({ id: z.string() }),
367
+ outputSchema: z.object({
368
+ title: z.string(),
369
+ content: z.array(z.string()),
370
+ }),
371
+ execute: async ({ id }) => {
372
+ const doc = await getDocument(id);
373
+
374
+ return {
375
+ structuredContent: { title: doc.title, content: doc.paragraphs },
376
+ };
377
+ },
378
+ });
379
+ ```
380
+
381
+ Three payload shapes need it: an array-valued `content` field (as above), a `resultType` of `"input_required"`, and a lone `structuredContent` field of your own. Everything else is inferred correctly — including a payload that has a `structuredContent` field among others. In particular a top-level `type` field is safe — including `type: "text"` and the other content-block kinds — because a declared `outputSchema` turns off the single-content-block shorthand.
382
+
383
+ The wrapper must stand alone: `{ structuredContent }`, optionally with `isError` or `_meta`. An object carrying anything else is read as a payload in its own right, so keys `execute` meant to keep never reach the client.
384
+
361
385
  #### Restricting who can call a tool
362
386
 
363
387
  A tool's optional `canAccess` receives the request's auth context and returns whether the caller may use it. Tools it rejects are filtered out of `tools/list` entirely.
@@ -857,8 +881,13 @@ registration steps, redirect URIs and scopes for each.
857
881
 
858
882
  #### Tool Authorization
859
883
 
860
- `canAccess` decides whether a caller may use a tool; tools it rejects are
861
- filtered out of `tools/list` entirely. Built-in helpers cover the common cases:
884
+ Configuring `auth` (or `authenticate`) closes the endpoint on its own: a request
885
+ that does not authenticate is refused with `401` and an RFC 6750
886
+ `WWW-Authenticate` challenge before any handler runs, so nothing is reachable
887
+ anonymously. `canAccess` then decides what an _authenticated_ caller may use.
888
+
889
+ `canAccess` filters rejected tools out of `tools/list` entirely. Built-in helpers
890
+ cover the common cases:
862
891
 
863
892
  ```ts
864
893
  import {
@@ -945,6 +974,34 @@ server.addTool({
945
974
  });
946
975
  ```
947
976
 
977
+ The hook has two ways to refuse:
978
+
979
+ - **Return `null` or `undefined`.** ViteMCP answers `401` with a
980
+ `WWW-Authenticate` challenge, pointing at the protected-resource document when
981
+ the server publishes one. `execute` never runs.
982
+ - **Throw a `Response`.** It is sent to the client verbatim, for when you want an
983
+ exact status, body or header — as in the example above.
984
+
985
+ Anything else the hook throws is a fault in your code: it is logged and answered
986
+ with `500`, never served.
987
+
988
+ Because a hook that cannot identify the caller has not authenticated them,
989
+ returning nothing is a refusal and not an anonymous session. If your server is
990
+ public in part, opt in explicitly and guard the rest with `canAccess`:
991
+
992
+ ```ts
993
+ const server = new ViteMCP({
994
+ name: "My Server",
995
+ version: "1.0.0",
996
+ // Callers the hook could not identify are served with `auth: undefined`.
997
+ allowAnonymous: true,
998
+ authenticate: async (request) => lookUpApiKey(request) ?? undefined,
999
+ });
1000
+
1001
+ server.addTool({ name: "public-tool" /* ... */ });
1002
+ server.addTool({ canAccess: requireAuth, name: "private-tool" /* ... */ });
1003
+ ```
1004
+
948
1005
  #### OAuth Proxy
949
1006
 
950
1007
  The `auth` option is backed by ViteMCP's OAuth Proxy, which sits between MCP
package/dist/ViteMCP.cjs CHANGED
@@ -25,10 +25,15 @@ var _chunkXC4BVJQZcjs = require('./chunk-XC4BVJQZ.cjs');
25
25
 
26
26
 
27
27
 
28
+
29
+
30
+
31
+
28
32
  var _server = require('@modelcontextprotocol/server');
29
33
 
30
34
 
31
35
  var _stdio = require('@modelcontextprotocol/server/stdio');
36
+ var _async_hooks = require('async_hooks');
32
37
  var _promises = require('fs/promises');
33
38
  var _hono = require('hono');
34
39
  var _cors = require('hono/cors');
@@ -472,6 +477,13 @@ var ViteMCP = class {
472
477
  return this.#serverState;
473
478
  }
474
479
  #authenticate;
480
+ /**
481
+ * Carries the `authenticate` result from the HTTP route into the per-request
482
+ * server factory. The SDK invokes that factory from within `handler.fetch`,
483
+ * so the running store is always the one this request established — whereas
484
+ * a field on `this` would be shared by every concurrent request.
485
+ */
486
+ #authStore = new (0, _async_hooks.AsyncLocalStorage)();
475
487
  #connectedServers = [];
476
488
  #corsMiddleware = null;
477
489
  #handler = null;
@@ -483,6 +495,13 @@ var ViteMCP = class {
483
495
  #resources = [];
484
496
  #resourceTemplates = [];
485
497
  #serverState = "stopped" /* Stopped */;
498
+ /**
499
+ * Whether this server publishes an RFC 9728 protected-resource document, and
500
+ * so whether a 401 can point a client at it. Latched when the routes are
501
+ * mounted rather than read back from `auth` per rejection: the provider's
502
+ * config getter builds its proxy on demand and refuses once destroyed.
503
+ */
504
+ #servesProtectedResourceMetadata = false;
486
505
  #stdioHandle = null;
487
506
  #tools = [];
488
507
  constructor(options) {
@@ -665,6 +684,38 @@ var ViteMCP = class {
665
684
  }
666
685
  this.#serverState = "stopped" /* Stopped */;
667
686
  }
687
+ /**
688
+ * Runs the `authenticate` hook and decides whether the exchange may proceed,
689
+ * returning either the store to run it under or the `Response` refusing it.
690
+ *
691
+ * Deliberately *not* done inside the per-request server factory: that
692
+ * factory's only return channel is an `McpServer`, so a refusal raised there
693
+ * is indistinguishable from a crash and reaches the client as a 500 with no
694
+ * `WWW-Authenticate` — the one header that tells an MCP client where to log
695
+ * in. Doing it here also covers the legacy fallback, which shares the same
696
+ * route, so no transport can be reached without passing this.
697
+ */
698
+ async #authenticateRequest(request) {
699
+ if (!this.#authenticate) {
700
+ return { auth: void 0 };
701
+ }
702
+ let auth;
703
+ try {
704
+ auth = await this.#authenticate(request);
705
+ } catch (error) {
706
+ if (error instanceof Response) {
707
+ return error;
708
+ }
709
+ this.#logger.error("[ViteMCP error]", error);
710
+ return _server.bearerAuthChallengeResponse.call(void 0,
711
+ new (0, _server.OAuthError)(_server.OAuthErrorCode.ServerError, "Internal Server Error")
712
+ );
713
+ }
714
+ if (!auth) {
715
+ return this.#options.allowAnonymous ? { auth: void 0 } : this.#unauthorized(request);
716
+ }
717
+ return { auth };
718
+ }
668
719
  async #buildServer(auth) {
669
720
  const server = new (0, _server.McpServer)(
670
721
  { name: this.#options.name, version: this.#options.version },
@@ -697,7 +748,7 @@ var ViteMCP = class {
697
748
  tool.timeoutMs,
698
749
  tool.name
699
750
  ) : tool.execute(args, context));
700
- return normalizeToolResult(result);
751
+ return normalizeToolResult(result, tool.outputSchema !== void 0);
701
752
  } catch (error) {
702
753
  if (error instanceof UserError) {
703
754
  return {
@@ -877,11 +928,10 @@ var ViteMCP = class {
877
928
  }
878
929
  async #startHttp(config) {
879
930
  this.#handler = _server.createMcpHandler.call(void 0,
880
- async (ctx) => {
881
- const request = ctx.requestInfo;
882
- const auth = this.#authenticate && request ? await this.#authenticate(request) : void 0;
883
- return this.#buildServer(auth);
884
- },
931
+ // Authentication has already run in the route below, which is the only
932
+ // place that can turn a refusal into an HTTP status. What reaches here
933
+ // is either an authenticated session or a deliberately anonymous one.
934
+ async () => this.#buildServer(_optionalChain([this, 'access', _41 => _41.#authStore, 'access', _42 => _42.getStore, 'call', _43 => _43(), 'optionalAccess', _44 => _44.auth])),
885
935
  {
886
936
  // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy
887
937
  // requests are answered unadvertised and skip Mcp-* validation.
@@ -891,8 +941,8 @@ var ViteMCP = class {
891
941
  }
892
942
  );
893
943
  this.#corsMiddleware = config.cors === false ? null : _cors.cors.call(void 0, config.cors);
894
- const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _41 => _41.#options, 'access', _42 => _42.auth, 'optionalAccess', _43 => _43.getOAuthConfig, 'call', _44 => _44()])));
895
- if (_optionalChain([oauth, 'optionalAccess', _45 => _45.enabled]) !== false && (_nullishCoalesce(_nullishCoalesce(_optionalChain([oauth, 'optionalAccess', _46 => _46.proxy]), () => ( _optionalChain([oauth, 'optionalAccess', _47 => _47.authorizationServer]))), () => ( _optionalChain([oauth, 'optionalAccess', _48 => _48.protectedResource]))))) {
944
+ const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _45 => _45.#options, 'access', _46 => _46.auth, 'optionalAccess', _47 => _47.getOAuthConfig, 'call', _48 => _48()])));
945
+ 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]))))) {
896
946
  this.#honoApp.route(
897
947
  "/",
898
948
  createOAuthRouter({
@@ -903,12 +953,13 @@ var ViteMCP = class {
903
953
  proxy: oauth.proxy
904
954
  })
905
955
  );
956
+ this.#servesProtectedResourceMetadata = Boolean(oauth.protectedResource);
906
957
  }
907
958
  const health = this.#options.health;
908
- if (_optionalChain([health, 'optionalAccess', _49 => _49.enabled]) !== false) {
959
+ if (_optionalChain([health, 'optionalAccess', _53 => _53.enabled]) !== false) {
909
960
  this.#honoApp.get(
910
- _nullishCoalesce(_optionalChain([health, 'optionalAccess', _50 => _50.path]), () => ( "/health")),
911
- (c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _51 => _51.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _52 => _52.status]), () => ( 200)))
961
+ _nullishCoalesce(_optionalChain([health, 'optionalAccess', _54 => _54.path]), () => ( "/health")),
962
+ (c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _55 => _55.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _56 => _56.status]), () => ( 200)))
912
963
  );
913
964
  }
914
965
  const endpoint = `${_nullishCoalesce(config.basePath, () => ( ""))}${_nullishCoalesce(config.endpoint, () => ( "/mcp"))}`;
@@ -926,7 +977,11 @@ var ViteMCP = class {
926
977
  if (rejected) {
927
978
  return rejected;
928
979
  }
929
- return handler.fetch(c.req.raw);
980
+ const authenticated = await this.#authenticateRequest(c.req.raw);
981
+ if (authenticated instanceof Response) {
982
+ return authenticated;
983
+ }
984
+ return this.#authStore.run(authenticated, () => handler.fetch(c.req.raw));
930
985
  });
931
986
  const app = this.#honoApp;
932
987
  const maxBodySize = _nullishCoalesce(config.maxBodySize, () => ( OAUTH_PROXY_MAX_BODY_SIZE));
@@ -941,7 +996,7 @@ var ViteMCP = class {
941
996
  "Content-Type": "application/json"
942
997
  });
943
998
  req.resume();
944
- res.once("finish", () => _optionalChain([res, 'access', _53 => _53.socket, 'optionalAccess', _54 => _54.end, 'call', _55 => _55()]));
999
+ res.once("finish", () => _optionalChain([res, 'access', _57 => _57.socket, 'optionalAccess', _58 => _58.end, 'call', _59 => _59()]));
945
1000
  res.end(
946
1001
  JSON.stringify({
947
1002
  error: "invalid_request",
@@ -1004,7 +1059,7 @@ var ViteMCP = class {
1004
1059
  return void 0;
1005
1060
  }
1006
1061
  const standard = schema["~standard"];
1007
- if (_optionalChain([standard, 'optionalAccess', _56 => _56.jsonSchema])) {
1062
+ if (_optionalChain([standard, 'optionalAccess', _60 => _60.jsonSchema])) {
1008
1063
  return schema;
1009
1064
  }
1010
1065
  try {
@@ -1017,6 +1072,26 @@ var ViteMCP = class {
1017
1072
  );
1018
1073
  }
1019
1074
  }
1075
+ /**
1076
+ * The RFC 6750 §3 challenge sent when `authenticate` refuses a request.
1077
+ *
1078
+ * `resource_metadata` (RFC 9728 §5.1) is the parameter that turns a bare
1079
+ * rejection into a login: it points the client at this server's
1080
+ * protected-resource document, from which it discovers the authorization
1081
+ * server and starts the flow. It is derived from the URL the request
1082
+ * arrived on, which is exactly where `createOAuthRouter` mounts that
1083
+ * document, and is omitted when this server publishes no such document.
1084
+ */
1085
+ #unauthorized(request) {
1086
+ return _server.bearerAuthChallengeResponse.call(void 0,
1087
+ new (0, _server.OAuthError)(_server.OAuthErrorCode.InvalidToken, "Authentication required"),
1088
+ this.#servesProtectedResourceMetadata ? {
1089
+ resourceMetadataUrl: _server.getOAuthProtectedResourceMetadataUrl.call(void 0,
1090
+ new URL(request.url)
1091
+ )
1092
+ } : {}
1093
+ );
1094
+ }
1020
1095
  };
1021
1096
  var nodeToWebRequest = (req, body, secure) => {
1022
1097
  const host = _nullishCoalesce(req.headers.host, () => ( "localhost"));
@@ -1084,8 +1159,8 @@ var assertStandardSchema = (schema, toolName, field) => {
1084
1159
  if (schema === void 0) {
1085
1160
  return;
1086
1161
  }
1087
- const standard = _optionalChain([schema, 'optionalAccess', _57 => _57["~standard"]]);
1088
- if (typeof _optionalChain([standard, 'optionalAccess', _58 => _58.validate]) !== "function") {
1162
+ const standard = _optionalChain([schema, 'optionalAccess', _61 => _61["~standard"]]);
1163
+ if (typeof _optionalChain([standard, 'optionalAccess', _62 => _62.validate]) !== "function") {
1089
1164
  throw new UnexpectedStateError(
1090
1165
  `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,
1091
1166
  { toolName }
@@ -1094,13 +1169,13 @@ var assertStandardSchema = (schema, toolName, field) => {
1094
1169
  };
1095
1170
  var promptArgsSchema = (prompt) => {
1096
1171
  const args = prompt.arguments;
1097
- if (!_optionalChain([args, 'optionalAccess', _59 => _59.length])) {
1172
+ if (!_optionalChain([args, 'optionalAccess', _63 => _63.length])) {
1098
1173
  return void 0;
1099
1174
  }
1100
1175
  const shape = {};
1101
1176
  for (const arg of args) {
1102
1177
  const completer = _nullishCoalesce(arg.complete, () => ( (prompt.complete ? (value) => prompt.complete(arg.name, value) : void 0)));
1103
- const valueSchema = _optionalChain([arg, 'access', _60 => _60.enum, 'optionalAccess', _61 => _61.length]) ? _zod.z.enum(arg.enum) : _zod.z.string();
1178
+ const valueSchema = _optionalChain([arg, 'access', _64 => _64.enum, 'optionalAccess', _65 => _65.length]) ? _zod.z.enum(arg.enum) : _zod.z.string();
1104
1179
  const described = arg.description ? valueSchema.describe(arg.description) : valueSchema;
1105
1180
  const base = completer ? _server.completable.call(void 0,
1106
1181
  described,
@@ -1110,7 +1185,21 @@ var promptArgsSchema = (prompt) => {
1110
1185
  }
1111
1186
  return _zod.z.object(shape);
1112
1187
  };
1113
- var normalizeToolResult = (result) => {
1188
+ var isStructuredResult = (value) => {
1189
+ if (!Object.hasOwn(value, "structuredContent") || value.structuredContent === void 0) {
1190
+ return false;
1191
+ }
1192
+ if (value.isError !== void 0 && typeof value.isError !== "boolean") {
1193
+ return false;
1194
+ }
1195
+ if (value._meta !== void 0 && (typeof value._meta !== "object" || value._meta === null || Array.isArray(value._meta))) {
1196
+ return false;
1197
+ }
1198
+ return Object.keys(value).every(
1199
+ (key) => key === "structuredContent" || key === "isError" || key === "_meta" || value[key] === void 0
1200
+ );
1201
+ };
1202
+ var normalizeToolResult = (result, hasOutputSchema) => {
1114
1203
  if (result === void 0 || result === null) {
1115
1204
  return { content: [] };
1116
1205
  }
@@ -1122,7 +1211,23 @@ var normalizeToolResult = (result) => {
1122
1211
  if (value.resultType === "input_required" || Array.isArray(value.content)) {
1123
1212
  return value;
1124
1213
  }
1125
- if (value.type === "text" || value.type === "image" || value.type === "audio" || value.type === "resource" || value.type === "resource_link") {
1214
+ if (isStructuredResult(value)) {
1215
+ return {
1216
+ content: [
1217
+ {
1218
+ // `undefined` is excluded already; this covers what else JSON
1219
+ // declines to represent, so a broken payload stays a tool error
1220
+ // rather than an unserializable content block.
1221
+ text: _nullishCoalesce(JSON.stringify(value.structuredContent), () => ( "null")),
1222
+ type: "text"
1223
+ }
1224
+ ],
1225
+ structuredContent: value.structuredContent,
1226
+ ...value.isError === void 0 ? {} : { isError: value.isError },
1227
+ ...value._meta === void 0 ? {} : { _meta: value._meta }
1228
+ };
1229
+ }
1230
+ if (!hasOutputSchema && (value.type === "text" || value.type === "image" || value.type === "audio" || value.type === "resource" || value.type === "resource_link")) {
1126
1231
  return { content: [value] };
1127
1232
  }
1128
1233
  return {