@vitemcp/server 1.0.2 → 1.0.4
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 +36 -26
- package/dist/ViteMCP.cjs.map +1 -1
- package/dist/ViteMCP.d.cts +7 -0
- package/dist/ViteMCP.d.ts +7 -0
- package/dist/ViteMCP.js +11 -1
- package/dist/ViteMCP.js.map +1 -1
- package/package.json +3 -8
package/dist/ViteMCP.cjs
CHANGED
|
@@ -435,6 +435,16 @@ var ServerState = /* @__PURE__ */ ((ServerState2) => {
|
|
|
435
435
|
return ServerState2;
|
|
436
436
|
})(ServerState || {});
|
|
437
437
|
var ViteMCP = class {
|
|
438
|
+
/**
|
|
439
|
+
* The port the HTTP server is actually listening on, or `null` when it is
|
|
440
|
+
* not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a
|
|
441
|
+
* free port and read it back here — this avoids the race inherent in
|
|
442
|
+
* picking a port first and binding it afterwards.
|
|
443
|
+
*/
|
|
444
|
+
get port() {
|
|
445
|
+
const address = _optionalChain([this, 'access', _10 => _10.#httpServer, 'optionalAccess', _11 => _11.address, 'call', _12 => _12()]);
|
|
446
|
+
return address && typeof address === "object" ? address.port : null;
|
|
447
|
+
}
|
|
438
448
|
get serverState() {
|
|
439
449
|
return this.#serverState;
|
|
440
450
|
}
|
|
@@ -559,7 +569,7 @@ var ViteMCP = class {
|
|
|
559
569
|
* that opted in to it.
|
|
560
570
|
*/
|
|
561
571
|
notifyResourceUpdated(uri) {
|
|
562
|
-
_optionalChain([this, 'access',
|
|
572
|
+
_optionalChain([this, 'access', _13 => _13.#handler, 'optionalAccess', _14 => _14.notify, 'access', _15 => _15.resourceUpdated, 'call', _16 => _16(uri)]);
|
|
563
573
|
}
|
|
564
574
|
removePrompt(name) {
|
|
565
575
|
this.#prompts = this.#prompts.filter((p) => p.name !== name);
|
|
@@ -620,9 +630,9 @@ var ViteMCP = class {
|
|
|
620
630
|
});
|
|
621
631
|
}
|
|
622
632
|
this.#connectedServers = [];
|
|
623
|
-
await _optionalChain([this, 'access',
|
|
633
|
+
await _optionalChain([this, 'access', _17 => _17.#stdioHandle, 'optionalAccess', _18 => _18.close, 'optionalCall', _19 => _19()]);
|
|
624
634
|
this.#stdioHandle = null;
|
|
625
|
-
await _optionalChain([this, 'access',
|
|
635
|
+
await _optionalChain([this, 'access', _20 => _20.#handler, 'optionalAccess', _21 => _21.close, 'call', _22 => _22()]);
|
|
626
636
|
this.#handler = null;
|
|
627
637
|
if (this.#httpServer) {
|
|
628
638
|
await new Promise(
|
|
@@ -781,16 +791,16 @@ var ViteMCP = class {
|
|
|
781
791
|
/** Bridges the v2 per-request context onto ViteMCP's `Context`. */
|
|
782
792
|
#makeContext(auth, rawCtx) {
|
|
783
793
|
const ctx = rawCtx;
|
|
784
|
-
const mcpReq = _optionalChain([ctx, 'optionalAccess',
|
|
785
|
-
const requestedLevel = _optionalChain([mcpReq, 'optionalAccess',
|
|
794
|
+
const mcpReq = _optionalChain([ctx, 'optionalAccess', _23 => _23.mcpReq]);
|
|
795
|
+
const requestedLevel = _optionalChain([mcpReq, 'optionalAccess', _24 => _24._meta, 'optionalAccess', _25 => _25["io.modelcontextprotocol/logLevel"]]);
|
|
786
796
|
const emit = (level, message, data) => {
|
|
787
797
|
if (!requestedLevel) {
|
|
788
798
|
return;
|
|
789
799
|
}
|
|
790
|
-
void _optionalChain([mcpReq, 'optionalAccess',
|
|
800
|
+
void _optionalChain([mcpReq, 'optionalAccess', _26 => _26.notify, 'optionalCall', _27 => _27({
|
|
791
801
|
method: "notifications/message",
|
|
792
802
|
params: { data: { context: data, message }, level }
|
|
793
|
-
}), 'optionalAccess',
|
|
803
|
+
}), 'optionalAccess', _28 => _28.catch, 'call', _29 => _29(() => {
|
|
794
804
|
})]);
|
|
795
805
|
};
|
|
796
806
|
return {
|
|
@@ -799,9 +809,9 @@ var ViteMCP = class {
|
|
|
799
809
|
message: params.message,
|
|
800
810
|
requestedSchema: params.requestedSchema
|
|
801
811
|
}),
|
|
802
|
-
input: (key, schema) => _server.acceptedContent.call(void 0, _optionalChain([mcpReq, 'optionalAccess',
|
|
812
|
+
input: (key, schema) => _server.acceptedContent.call(void 0, _optionalChain([mcpReq, 'optionalAccess', _30 => _30.inputResponses]), key, schema),
|
|
803
813
|
inputRequired: (inputRequests, requestState) => _server.inputRequired.call(void 0, { inputRequests, requestState }),
|
|
804
|
-
inputResponses: _optionalChain([mcpReq, 'optionalAccess',
|
|
814
|
+
inputResponses: _optionalChain([mcpReq, 'optionalAccess', _31 => _31.inputResponses]),
|
|
805
815
|
log: {
|
|
806
816
|
debug: (m, d) => emit("debug", m, d),
|
|
807
817
|
error: (m, d) => emit("error", m, d),
|
|
@@ -809,11 +819,11 @@ var ViteMCP = class {
|
|
|
809
819
|
warn: (m, d) => emit("warning", m, d)
|
|
810
820
|
},
|
|
811
821
|
reportProgress: async (progress) => {
|
|
812
|
-
const progressToken = _optionalChain([mcpReq, 'optionalAccess',
|
|
822
|
+
const progressToken = _optionalChain([mcpReq, 'optionalAccess', _32 => _32._meta, 'optionalAccess', _33 => _33.progressToken]);
|
|
813
823
|
if (progressToken === void 0) {
|
|
814
824
|
return;
|
|
815
825
|
}
|
|
816
|
-
await _optionalChain([mcpReq, 'optionalAccess',
|
|
826
|
+
await _optionalChain([mcpReq, 'optionalAccess', _34 => _34.notify, 'optionalCall', _35 => _35({
|
|
817
827
|
method: "notifications/progress",
|
|
818
828
|
params: {
|
|
819
829
|
message: progress.message,
|
|
@@ -823,9 +833,9 @@ var ViteMCP = class {
|
|
|
823
833
|
}
|
|
824
834
|
})]);
|
|
825
835
|
},
|
|
826
|
-
requestId: _optionalChain([mcpReq, 'optionalAccess',
|
|
836
|
+
requestId: _optionalChain([mcpReq, 'optionalAccess', _36 => _36.id]),
|
|
827
837
|
// The SDK exposes this as an accessor; call it so callers get the value.
|
|
828
|
-
requestState: _optionalChain([mcpReq, 'optionalAccess',
|
|
838
|
+
requestState: _optionalChain([mcpReq, 'optionalAccess', _37 => _37.requestState, 'optionalCall', _38 => _38()])
|
|
829
839
|
};
|
|
830
840
|
}
|
|
831
841
|
/**
|
|
@@ -834,7 +844,7 @@ var ViteMCP = class {
|
|
|
834
844
|
* no addressee on a stateless transport.
|
|
835
845
|
*/
|
|
836
846
|
#notifyListChanged(kind) {
|
|
837
|
-
const notifier = _optionalChain([this, 'access',
|
|
847
|
+
const notifier = _optionalChain([this, 'access', _39 => _39.#handler, 'optionalAccess', _40 => _40.notify]);
|
|
838
848
|
if (!notifier) {
|
|
839
849
|
return;
|
|
840
850
|
}
|
|
@@ -858,8 +868,8 @@ var ViteMCP = class {
|
|
|
858
868
|
}
|
|
859
869
|
);
|
|
860
870
|
this.#corsMiddleware = config.cors === false ? null : _cors.cors.call(void 0, config.cors);
|
|
861
|
-
const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access',
|
|
862
|
-
if (_optionalChain([oauth, 'optionalAccess',
|
|
871
|
+
const oauth = _nullishCoalesce(this.#options.oauth, () => ( _optionalChain([this, 'access', _41 => _41.#options, 'access', _42 => _42.auth, 'optionalAccess', _43 => _43.getOAuthConfig, 'call', _44 => _44()])));
|
|
872
|
+
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]))))) {
|
|
863
873
|
this.#honoApp.route(
|
|
864
874
|
"/",
|
|
865
875
|
createOAuthRouter({
|
|
@@ -872,10 +882,10 @@ var ViteMCP = class {
|
|
|
872
882
|
);
|
|
873
883
|
}
|
|
874
884
|
const health = this.#options.health;
|
|
875
|
-
if (_optionalChain([health, 'optionalAccess',
|
|
885
|
+
if (_optionalChain([health, 'optionalAccess', _49 => _49.enabled]) !== false) {
|
|
876
886
|
this.#honoApp.get(
|
|
877
|
-
_nullishCoalesce(_optionalChain([health, 'optionalAccess',
|
|
878
|
-
(c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess',
|
|
887
|
+
_nullishCoalesce(_optionalChain([health, 'optionalAccess', _50 => _50.path]), () => ( "/health")),
|
|
888
|
+
(c) => c.text(_nullishCoalesce(_optionalChain([health, 'optionalAccess', _51 => _51.message]), () => ( "ok")), _nullishCoalesce(_optionalChain([health, 'optionalAccess', _52 => _52.status]), () => ( 200)))
|
|
879
889
|
);
|
|
880
890
|
}
|
|
881
891
|
const endpoint = `${_nullishCoalesce(config.basePath, () => ( ""))}${_nullishCoalesce(config.endpoint, () => ( "/mcp"))}`;
|
|
@@ -908,7 +918,7 @@ var ViteMCP = class {
|
|
|
908
918
|
"Content-Type": "application/json"
|
|
909
919
|
});
|
|
910
920
|
req.resume();
|
|
911
|
-
res.once("finish", () => _optionalChain([res, 'access',
|
|
921
|
+
res.once("finish", () => _optionalChain([res, 'access', _53 => _53.socket, 'optionalAccess', _54 => _54.end, 'call', _55 => _55()]));
|
|
912
922
|
res.end(
|
|
913
923
|
JSON.stringify({
|
|
914
924
|
error: "invalid_request",
|
|
@@ -959,7 +969,7 @@ var ViteMCP = class {
|
|
|
959
969
|
)
|
|
960
970
|
);
|
|
961
971
|
this.#logger.info(
|
|
962
|
-
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${_nullishCoalesce(config.host, () => ( "127.0.0.1"))}:${config.port}${endpoint}`
|
|
972
|
+
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${_nullishCoalesce(config.host, () => ( "127.0.0.1"))}:${_nullishCoalesce(this.port, () => ( config.port))}${endpoint}`
|
|
963
973
|
);
|
|
964
974
|
}
|
|
965
975
|
/**
|
|
@@ -971,7 +981,7 @@ var ViteMCP = class {
|
|
|
971
981
|
return void 0;
|
|
972
982
|
}
|
|
973
983
|
const standard = schema["~standard"];
|
|
974
|
-
if (_optionalChain([standard, 'optionalAccess',
|
|
984
|
+
if (_optionalChain([standard, 'optionalAccess', _56 => _56.jsonSchema])) {
|
|
975
985
|
return schema;
|
|
976
986
|
}
|
|
977
987
|
try {
|
|
@@ -1051,8 +1061,8 @@ var assertStandardSchema = (schema, toolName, field) => {
|
|
|
1051
1061
|
if (schema === void 0) {
|
|
1052
1062
|
return;
|
|
1053
1063
|
}
|
|
1054
|
-
const standard = _optionalChain([schema, 'optionalAccess',
|
|
1055
|
-
if (typeof _optionalChain([standard, 'optionalAccess',
|
|
1064
|
+
const standard = _optionalChain([schema, 'optionalAccess', _57 => _57["~standard"]]);
|
|
1065
|
+
if (typeof _optionalChain([standard, 'optionalAccess', _58 => _58.validate]) !== "function") {
|
|
1056
1066
|
throw new UnexpectedStateError(
|
|
1057
1067
|
`Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,
|
|
1058
1068
|
{ toolName }
|
|
@@ -1061,13 +1071,13 @@ var assertStandardSchema = (schema, toolName, field) => {
|
|
|
1061
1071
|
};
|
|
1062
1072
|
var promptArgsSchema = (prompt) => {
|
|
1063
1073
|
const args = prompt.arguments;
|
|
1064
|
-
if (!_optionalChain([args, 'optionalAccess',
|
|
1074
|
+
if (!_optionalChain([args, 'optionalAccess', _59 => _59.length])) {
|
|
1065
1075
|
return void 0;
|
|
1066
1076
|
}
|
|
1067
1077
|
const shape = {};
|
|
1068
1078
|
for (const arg of args) {
|
|
1069
1079
|
const completer = _nullishCoalesce(arg.complete, () => ( (prompt.complete ? (value) => prompt.complete(arg.name, value) : void 0)));
|
|
1070
|
-
const valueSchema = _optionalChain([arg, 'access',
|
|
1080
|
+
const valueSchema = _optionalChain([arg, 'access', _60 => _60.enum, 'optionalAccess', _61 => _61.length]) ? _zod.z.enum(arg.enum) : _zod.z.string();
|
|
1071
1081
|
const described = arg.description ? valueSchema.describe(arg.description) : valueSchema;
|
|
1072
1082
|
const base = completer ? _server.completable.call(void 0,
|
|
1073
1083
|
described,
|
package/dist/ViteMCP.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/server/server/dist/ViteMCP.cjs","../src/ViteMCP.ts","../src/auth/router.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"names":["ServerState"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACdA;AACE;AAEA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AAAoB,sDAEf;AACP;AACE;AAAA,2DAEK;AAEP,uCAAyB;AACzB,4BAAqB;AACrB,iCAAqB;AACrB,wEAAiB;AACjB,4EAAkB;AAClB,4CAAoC;AACpC,gCAAsB;AACtB,yGAA6B;AAC7B,oCAA+C;AAC/C,0BAAkB;ADSlB;AACA;AEvCA;AAKO,IAAM,0BAAA,EAA4B,KAAA,EAAO,IAAA;AAOhD,IAAM,cAAA,EAAgB,CAAC,KAAA,EAAA,GAAmB;AACxC,EAAA,MAAM,IAAA,EAAM,KAAA;AACZ,EAAA,OAAO;AAAA,IACL,IAAA,mCAAM,GAAA,mBAAI,MAAA,0BAAA,CAAS,GAAA,UAAK,EAAE,KAAA,EAAO,kBAAkB,GAAA;AAAA,IACnD,MAAA,mBAAS,GAAA,CAAI,UAAA,UAAc;AAAA,EAC7B,CAAA;AACF,CAAA;AAQO,IAAM,eAAA,EAAiB,MAAA,CAC5B,OAAA,EAAA,GAC2B;AAC3B,EAAA,MAAM,SAAA,EAAW,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA;AAErD,EAAA,GAAA,CAAI,SAAA,GAAY,MAAA,CAAO,QAAQ,EAAA,EAAI,yBAAA,EAA2B;AAC5D,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,IAAA,EA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AEgC,EAAA;AACqB,IAAA;AACrD,EAAA;AAEgC,EAAA;AAChB,IAAA;AAGqC,IAAA;AAC1C,MAAA;AACT,IAAA;AAIiB,IAAA;AAKW,MAAA;AAC5B,IAAA;AAIO,IAAA;AAC0C,MAAA;AAC5B,MAAA;AACrB,IAAA;AACF,EAAA;AAEiD,EAAA;AACnD;AD5SyD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/server/server/dist/ViteMCP.cjs","sourcesContent":[null,"import {\n acceptedContent,\n type CacheScope,\n completable,\n createMcpHandler,\n fromJsonSchema,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n type McpHttpHandler,\n McpServer,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport parseURITemplate from \"uri-templates\";\nimport { strictJsonSchema, toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\ntype MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const mimeType = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mimeType?.mime ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\"),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n version: `${number}.${number}.${number}`;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Authenticate<T> = (request: Request) => Promise<T>;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype LoadContext<T extends ViteMCPAuth> = Omit<Context<T>, \"reportProgress\">;\n\ntype Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\ntype ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\ntype ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\ntype SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\ntype ToolParameters = StandardSchemaV1;\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n const loaded = await direct.load(this.#makeContext(undefined, undefined));\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return { ...first, mimeType: first.mimeType ?? direct.mimeType, uri };\n }\n\n for (const template of this.#resourceTemplates) {\n const params = parseURITemplate(template.uriTemplate).fromUri(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined),\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return { ...first, mimeType: first.mimeType ?? template.mimeType, uri };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n this.#stdioHandle = serveStdio(() => this.#buildServer(undefined));\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n async #buildServer(auth: T | undefined): Promise<McpServer> {\n const server = new McpServer(\n { name: this.#options.name, version: this.#options.version },\n { instructions: this.#options.instructions },\n );\n\n for (const tool of this.#tools) {\n if (tool.canAccess && !tool.canAccess(auth)) {\n continue;\n }\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: (await this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n )) as never,\n outputSchema: (await this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n )) as never,\n },\n (async (args: unknown, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n\n try {\n const result = await (tool.timeoutMs\n ? withTimeout(\n tool.execute(args, context),\n tool.timeoutMs,\n tool.name,\n )\n : tool.execute(args, context));\n return normalizeToolResult(result);\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(error.extras ? { structuredContent: error.extras } : {}),\n };\n }\n throw error;\n }\n }) as never,\n );\n }\n\n for (const resource of this.#resources) {\n if (resource.canAccess && !resource.canAccess(auth)) {\n continue;\n }\n\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const template of this.#resourceTemplates) {\n if (template.canAccess && !template.canAccess(auth)) {\n continue;\n }\n\n const complete: Record<string, (value: string) => Promise<string[]>> = {};\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n if (prompt.canAccess && !prompt.canAccess(auth)) {\n continue;\n }\n\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: promptArgsSchema(prompt),\n description: prompt.description,\n } as never,\n (async (args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n }) as never,\n );\n }\n\n return server;\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /** Bridges the v2 per-request context onto ViteMCP's `Context`. */\n #makeContext(auth: T | undefined, rawCtx: unknown): Context<T> {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n \"io.modelcontextprotocol/logLevel\"?: string;\n progressToken?: number | string;\n };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n };\n };\n const mcpReq = ctx?.mcpReq;\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`. Failures are swallowed: a log line must never take down\n // the request.\n const requestedLevel = mcpReq?._meta?.[\"io.modelcontextprotocol/logLevel\"];\n\n const emit = (level: string, message: string, data?: SerializableValue) => {\n if (!requestedLevel) {\n return;\n }\n\n void mcpReq\n ?.notify?.({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n })\n ?.catch(() => {});\n };\n\n return {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(mcpReq?.inputResponses, key, schema as never) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await mcpReq?.notify?.({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the value.\n requestState: mcpReq?.requestState?.<string>(),\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n async (ctx) => {\n // `ctx.requestInfo` is the real field; a previous cast invented `req`\n // and silently handed every hook `undefined`.\n const request = ctx.requestInfo;\n\n const auth =\n this.#authenticate && request\n ? await this.#authenticate(request)\n : undefined;\n\n return this.#buildServer(auth);\n },\n {\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n const oauth = this.#options.oauth ?? this.#options.auth?.getOAuthConfig();\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n return handler.fetch(c.req.raw);\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, Object.fromEntries(response.headers));\n res.end(Buffer.from(await response.arrayBuffer()));\n } catch (error) {\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n if (!res.headersSent) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n }\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${config.port}${endpoint}`,\n );\n }\n\n /**\n * Converts a schema the SDK cannot consume directly. Zod v4 emits JSON\n * Schema natively; valibot/arktype go via xsschema.\n */\n async #toSdkSchema(schema: unknown, label: string): Promise<unknown> {\n if (!schema) {\n return undefined;\n }\n\n const standard = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n\n if (standard?.jsonSchema) {\n return schema;\n }\n\n try {\n const json = strictJsonSchema(await toJsonSchema(schema as never));\n return fromJsonSchema(json as never);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n}\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`. The work itself is not cancelled\n * — `execute` owns whatever it started — but the caller stops waiting.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeoutMs: number,\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {\n timeoutMs,\n toolName,\n }),\n );\n }, timeoutMs);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/** Renders a byte cap the way the error message should read (e.g. \"1 MiB\"). */\nconst formatBytes = (bytes: number): string => {\n if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {\n return `${bytes / (1024 * 1024)} MiB`;\n }\n\n if (bytes >= 1024 && bytes % 1024 === 0) {\n return `${bytes / 1024} KiB`;\n }\n\n return `${bytes} bytes`;\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const completer =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n // On the schema, not here: the SDK derives `prompts/list` arguments from\n // the schema's JSON Schema.\n const valueSchema = arg.enum?.length\n ? z.enum(arg.enum as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return z.object(shape);\n};\n\n/** Normalizes the several shapes `execute` may return into a CallToolResult. */\nconst normalizeToolResult = (result: unknown): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n if (\n value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\"\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nexport const readCappedBody = async (\n request: Request,\n): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via Basic auth. Body wins.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator !== -1) {\n params.client_id ||= decodeURIComponent(decoded.slice(0, separator));\n params.client_secret ||= decodeURIComponent(\n decoded.slice(separator + 1),\n );\n }\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","export class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n } else {\n this.#cache.clear();\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(url);\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n this.#inFlight.delete(url);\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(url: string): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // store in cache with expiration\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n let ajvModule;\n\n try {\n ajvModule = await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n const ajv = new Ajv({ allErrors: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(schema);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n const path = error.instancePath\n .split(\"/\")\n .filter(Boolean)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return Number.isInteger(index) && segment !== \"\" ? index : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/server/server/dist/ViteMCP.cjs","../src/ViteMCP.ts","../src/auth/router.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"names":["ServerState"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACdA;AACE;AAEA;AACA;AACA;AAEA;AAEA;AAEA;AACA;AACA;AAAoB,sDAEf;AACP;AACE;AAAA,2DAEK;AAEP,uCAAyB;AACzB,4BAAqB;AACrB,iCAAqB;AACrB,wEAAiB;AACjB,4EAAkB;AAClB,4CAAoC;AACpC,gCAAsB;AACtB,yGAA6B;AAC7B,oCAA+C;AAC/C,0BAAkB;ADSlB;AACA;AEvCA;AAKO,IAAM,0BAAA,EAA4B,KAAA,EAAO,IAAA;AAOhD,IAAM,cAAA,EAAgB,CAAC,KAAA,EAAA,GAAmB;AACxC,EAAA,MAAM,IAAA,EAAM,KAAA;AACZ,EAAA,OAAO;AAAA,IACL,IAAA,mCAAM,GAAA,mBAAI,MAAA,0BAAA,CAAS,GAAA,UAAK,EAAE,KAAA,EAAO,kBAAkB,GAAA;AAAA,IAC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,IAAA;AAES,IAAA;AACZ,MAAA;AACT,IAAA;AAEe,IAAA;AACjB,EAAA;AAE2B,EAAA;AAC7B;AAOK;AACuB,EAAA;AACxB,IAAA;AACF,EAAA;AAIA,EAAA;AAE8C,EAAA;AAClC,IAAA;AACmB,MAAA;AAChB,MAAA;AACb,IAAA;AACF,EAAA;AACF;AAEuE;AACjD,EAAA;AAED,EAAA;AACV,IAAA;AACT,EAAA;AAE0C,EAAA;AAClB,EAAA;AAIhB,IAAA;AAKS,IAAA;AAGC,IAAA;AAGZ,IAAA;AACE,MAAA;AACmD,MAAA;AAErD,IAAA;AAC0C,IAAA;AAChD,EAAA;AAEqB,EAAA;AACvB;AAG0D;AACX,EAAA;AACtB,IAAA;AACvB,EAAA;AAEgC,EAAA;AACqB,IAAA;AACrD,EAAA;AAEgC,EAAA;AAChB,IAAA;AAGqC,IAAA;AAC1C,MAAA;AACT,IAAA;AAIiB,IAAA;AAKW,MAAA;AAC5B,IAAA;AAIO,IAAA;AAC0C,MAAA;AAC5B,MAAA;AACrB,IAAA;AACF,EAAA;AAEiD,EAAA;AACnD;AD7SyD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/server/server/dist/ViteMCP.cjs","sourcesContent":[null,"import {\n acceptedContent,\n type CacheScope,\n completable,\n createMcpHandler,\n fromJsonSchema,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n type McpHttpHandler,\n McpServer,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport parseURITemplate from \"uri-templates\";\nimport { strictJsonSchema, toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\ntype MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const mimeType = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mimeType?.mime ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\"),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n version: `${number}.${number}.${number}`;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Authenticate<T> = (request: Request) => Promise<T>;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype LoadContext<T extends ViteMCPAuth> = Omit<Context<T>, \"reportProgress\">;\n\ntype Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\ntype ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\ntype ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\ntype SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\ntype ToolParameters = StandardSchemaV1;\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n /**\n * The port the HTTP server is actually listening on, or `null` when it is\n * not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a\n * free port and read it back here — this avoids the race inherent in\n * picking a port first and binding it afterwards.\n */\n public get port(): null | number {\n const address = this.#httpServer?.address();\n return address && typeof address === \"object\" ? address.port : null;\n }\n\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n const loaded = await direct.load(this.#makeContext(undefined, undefined));\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return { ...first, mimeType: first.mimeType ?? direct.mimeType, uri };\n }\n\n for (const template of this.#resourceTemplates) {\n const params = parseURITemplate(template.uriTemplate).fromUri(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined),\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return { ...first, mimeType: first.mimeType ?? template.mimeType, uri };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n this.#stdioHandle = serveStdio(() => this.#buildServer(undefined));\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n async #buildServer(auth: T | undefined): Promise<McpServer> {\n const server = new McpServer(\n { name: this.#options.name, version: this.#options.version },\n { instructions: this.#options.instructions },\n );\n\n for (const tool of this.#tools) {\n if (tool.canAccess && !tool.canAccess(auth)) {\n continue;\n }\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: (await this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n )) as never,\n outputSchema: (await this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n )) as never,\n },\n (async (args: unknown, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n\n try {\n const result = await (tool.timeoutMs\n ? withTimeout(\n tool.execute(args, context),\n tool.timeoutMs,\n tool.name,\n )\n : tool.execute(args, context));\n return normalizeToolResult(result);\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(error.extras ? { structuredContent: error.extras } : {}),\n };\n }\n throw error;\n }\n }) as never,\n );\n }\n\n for (const resource of this.#resources) {\n if (resource.canAccess && !resource.canAccess(auth)) {\n continue;\n }\n\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const template of this.#resourceTemplates) {\n if (template.canAccess && !template.canAccess(auth)) {\n continue;\n }\n\n const complete: Record<string, (value: string) => Promise<string[]>> = {};\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n if (prompt.canAccess && !prompt.canAccess(auth)) {\n continue;\n }\n\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: promptArgsSchema(prompt),\n description: prompt.description,\n } as never,\n (async (args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n }) as never,\n );\n }\n\n return server;\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /** Bridges the v2 per-request context onto ViteMCP's `Context`. */\n #makeContext(auth: T | undefined, rawCtx: unknown): Context<T> {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n \"io.modelcontextprotocol/logLevel\"?: string;\n progressToken?: number | string;\n };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n };\n };\n const mcpReq = ctx?.mcpReq;\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`. Failures are swallowed: a log line must never take down\n // the request.\n const requestedLevel = mcpReq?._meta?.[\"io.modelcontextprotocol/logLevel\"];\n\n const emit = (level: string, message: string, data?: SerializableValue) => {\n if (!requestedLevel) {\n return;\n }\n\n void mcpReq\n ?.notify?.({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n })\n ?.catch(() => {});\n };\n\n return {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(mcpReq?.inputResponses, key, schema as never) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await mcpReq?.notify?.({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the value.\n requestState: mcpReq?.requestState?.<string>(),\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n async (ctx) => {\n // `ctx.requestInfo` is the real field; a previous cast invented `req`\n // and silently handed every hook `undefined`.\n const request = ctx.requestInfo;\n\n const auth =\n this.#authenticate && request\n ? await this.#authenticate(request)\n : undefined;\n\n return this.#buildServer(auth);\n },\n {\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n const oauth = this.#options.oauth ?? this.#options.auth?.getOAuthConfig();\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n return handler.fetch(c.req.raw);\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, Object.fromEntries(response.headers));\n res.end(Buffer.from(await response.arrayBuffer()));\n } catch (error) {\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n if (!res.headersSent) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n }\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${this.port ?? config.port}${endpoint}`,\n );\n }\n\n /**\n * Converts a schema the SDK cannot consume directly. Zod v4 emits JSON\n * Schema natively; valibot/arktype go via xsschema.\n */\n async #toSdkSchema(schema: unknown, label: string): Promise<unknown> {\n if (!schema) {\n return undefined;\n }\n\n const standard = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n\n if (standard?.jsonSchema) {\n return schema;\n }\n\n try {\n const json = strictJsonSchema(await toJsonSchema(schema as never));\n return fromJsonSchema(json as never);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n}\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`. The work itself is not cancelled\n * — `execute` owns whatever it started — but the caller stops waiting.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeoutMs: number,\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {\n timeoutMs,\n toolName,\n }),\n );\n }, timeoutMs);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/** Renders a byte cap the way the error message should read (e.g. \"1 MiB\"). */\nconst formatBytes = (bytes: number): string => {\n if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {\n return `${bytes / (1024 * 1024)} MiB`;\n }\n\n if (bytes >= 1024 && bytes % 1024 === 0) {\n return `${bytes / 1024} KiB`;\n }\n\n return `${bytes} bytes`;\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const completer =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n // On the schema, not here: the SDK derives `prompts/list` arguments from\n // the schema's JSON Schema.\n const valueSchema = arg.enum?.length\n ? z.enum(arg.enum as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return z.object(shape);\n};\n\n/** Normalizes the several shapes `execute` may return into a CallToolResult. */\nconst normalizeToolResult = (result: unknown): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n if (\n value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\"\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nconst readCappedBody = async (request: Request): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via Basic auth. Body wins.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator !== -1) {\n params.client_id ||= decodeURIComponent(decoded.slice(0, separator));\n params.client_secret ||= decodeURIComponent(\n decoded.slice(separator + 1),\n );\n }\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","export class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n } else {\n this.#cache.clear();\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(url);\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n this.#inFlight.delete(url);\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(url: string): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // store in cache with expiration\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n let ajvModule;\n\n try {\n ajvModule = await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n const ajv = new Ajv({ allErrors: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(schema);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n const path = error.instancePath\n .split(\"/\")\n .filter(Boolean)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return Number.isInteger(index) && segment !== \"\" ? index : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"]}
|
package/dist/ViteMCP.d.cts
CHANGED
|
@@ -333,6 +333,13 @@ type SerializableValue = {
|
|
|
333
333
|
type ToolParameters = StandardSchemaV1;
|
|
334
334
|
declare class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {
|
|
335
335
|
#private;
|
|
336
|
+
/**
|
|
337
|
+
* The port the HTTP server is actually listening on, or `null` when it is
|
|
338
|
+
* not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a
|
|
339
|
+
* free port and read it back here — this avoids the race inherent in
|
|
340
|
+
* picking a port first and binding it afterwards.
|
|
341
|
+
*/
|
|
342
|
+
get port(): null | number;
|
|
336
343
|
get serverState(): ServerState;
|
|
337
344
|
constructor(options: ServerOptions<T>);
|
|
338
345
|
addPrompt(prompt: Prompt<T>): void;
|
package/dist/ViteMCP.d.ts
CHANGED
|
@@ -333,6 +333,13 @@ type SerializableValue = {
|
|
|
333
333
|
type ToolParameters = StandardSchemaV1;
|
|
334
334
|
declare class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {
|
|
335
335
|
#private;
|
|
336
|
+
/**
|
|
337
|
+
* The port the HTTP server is actually listening on, or `null` when it is
|
|
338
|
+
* not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a
|
|
339
|
+
* free port and read it back here — this avoids the race inherent in
|
|
340
|
+
* picking a port first and binding it afterwards.
|
|
341
|
+
*/
|
|
342
|
+
get port(): null | number;
|
|
336
343
|
get serverState(): ServerState;
|
|
337
344
|
constructor(options: ServerOptions<T>);
|
|
338
345
|
addPrompt(prompt: Prompt<T>): void;
|
package/dist/ViteMCP.js
CHANGED
|
@@ -435,6 +435,16 @@ var ServerState = /* @__PURE__ */ ((ServerState2) => {
|
|
|
435
435
|
return ServerState2;
|
|
436
436
|
})(ServerState || {});
|
|
437
437
|
var ViteMCP = class {
|
|
438
|
+
/**
|
|
439
|
+
* The port the HTTP server is actually listening on, or `null` when it is
|
|
440
|
+
* not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a
|
|
441
|
+
* free port and read it back here — this avoids the race inherent in
|
|
442
|
+
* picking a port first and binding it afterwards.
|
|
443
|
+
*/
|
|
444
|
+
get port() {
|
|
445
|
+
const address = this.#httpServer?.address();
|
|
446
|
+
return address && typeof address === "object" ? address.port : null;
|
|
447
|
+
}
|
|
438
448
|
get serverState() {
|
|
439
449
|
return this.#serverState;
|
|
440
450
|
}
|
|
@@ -959,7 +969,7 @@ var ViteMCP = class {
|
|
|
959
969
|
)
|
|
960
970
|
);
|
|
961
971
|
this.#logger.info(
|
|
962
|
-
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${config.host ?? "127.0.0.1"}:${config.port}${endpoint}`
|
|
972
|
+
`[ViteMCP info] server is running on ${useTls ? "HTTPS" : "HTTP"} at ${useTls ? "https" : "http"}://${config.host ?? "127.0.0.1"}:${this.port ?? config.port}${endpoint}`
|
|
963
973
|
);
|
|
964
974
|
}
|
|
965
975
|
/**
|
package/dist/ViteMCP.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ViteMCP.ts","../src/auth/router.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"sourcesContent":["import {\n acceptedContent,\n type CacheScope,\n completable,\n createMcpHandler,\n fromJsonSchema,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n type McpHttpHandler,\n McpServer,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport parseURITemplate from \"uri-templates\";\nimport { strictJsonSchema, toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\ntype MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const mimeType = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mimeType?.mime ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\"),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n version: `${number}.${number}.${number}`;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Authenticate<T> = (request: Request) => Promise<T>;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype LoadContext<T extends ViteMCPAuth> = Omit<Context<T>, \"reportProgress\">;\n\ntype Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\ntype ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\ntype ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\ntype SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\ntype ToolParameters = StandardSchemaV1;\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n const loaded = await direct.load(this.#makeContext(undefined, undefined));\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return { ...first, mimeType: first.mimeType ?? direct.mimeType, uri };\n }\n\n for (const template of this.#resourceTemplates) {\n const params = parseURITemplate(template.uriTemplate).fromUri(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined),\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return { ...first, mimeType: first.mimeType ?? template.mimeType, uri };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n this.#stdioHandle = serveStdio(() => this.#buildServer(undefined));\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n async #buildServer(auth: T | undefined): Promise<McpServer> {\n const server = new McpServer(\n { name: this.#options.name, version: this.#options.version },\n { instructions: this.#options.instructions },\n );\n\n for (const tool of this.#tools) {\n if (tool.canAccess && !tool.canAccess(auth)) {\n continue;\n }\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: (await this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n )) as never,\n outputSchema: (await this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n )) as never,\n },\n (async (args: unknown, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n\n try {\n const result = await (tool.timeoutMs\n ? withTimeout(\n tool.execute(args, context),\n tool.timeoutMs,\n tool.name,\n )\n : tool.execute(args, context));\n return normalizeToolResult(result);\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(error.extras ? { structuredContent: error.extras } : {}),\n };\n }\n throw error;\n }\n }) as never,\n );\n }\n\n for (const resource of this.#resources) {\n if (resource.canAccess && !resource.canAccess(auth)) {\n continue;\n }\n\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const template of this.#resourceTemplates) {\n if (template.canAccess && !template.canAccess(auth)) {\n continue;\n }\n\n const complete: Record<string, (value: string) => Promise<string[]>> = {};\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n if (prompt.canAccess && !prompt.canAccess(auth)) {\n continue;\n }\n\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: promptArgsSchema(prompt),\n description: prompt.description,\n } as never,\n (async (args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n }) as never,\n );\n }\n\n return server;\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /** Bridges the v2 per-request context onto ViteMCP's `Context`. */\n #makeContext(auth: T | undefined, rawCtx: unknown): Context<T> {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n \"io.modelcontextprotocol/logLevel\"?: string;\n progressToken?: number | string;\n };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n };\n };\n const mcpReq = ctx?.mcpReq;\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`. Failures are swallowed: a log line must never take down\n // the request.\n const requestedLevel = mcpReq?._meta?.[\"io.modelcontextprotocol/logLevel\"];\n\n const emit = (level: string, message: string, data?: SerializableValue) => {\n if (!requestedLevel) {\n return;\n }\n\n void mcpReq\n ?.notify?.({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n })\n ?.catch(() => {});\n };\n\n return {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(mcpReq?.inputResponses, key, schema as never) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await mcpReq?.notify?.({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the value.\n requestState: mcpReq?.requestState?.<string>(),\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n async (ctx) => {\n // `ctx.requestInfo` is the real field; a previous cast invented `req`\n // and silently handed every hook `undefined`.\n const request = ctx.requestInfo;\n\n const auth =\n this.#authenticate && request\n ? await this.#authenticate(request)\n : undefined;\n\n return this.#buildServer(auth);\n },\n {\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n const oauth = this.#options.oauth ?? this.#options.auth?.getOAuthConfig();\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n return handler.fetch(c.req.raw);\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, Object.fromEntries(response.headers));\n res.end(Buffer.from(await response.arrayBuffer()));\n } catch (error) {\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n if (!res.headersSent) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n }\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${config.port}${endpoint}`,\n );\n }\n\n /**\n * Converts a schema the SDK cannot consume directly. Zod v4 emits JSON\n * Schema natively; valibot/arktype go via xsschema.\n */\n async #toSdkSchema(schema: unknown, label: string): Promise<unknown> {\n if (!schema) {\n return undefined;\n }\n\n const standard = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n\n if (standard?.jsonSchema) {\n return schema;\n }\n\n try {\n const json = strictJsonSchema(await toJsonSchema(schema as never));\n return fromJsonSchema(json as never);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n}\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`. The work itself is not cancelled\n * — `execute` owns whatever it started — but the caller stops waiting.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeoutMs: number,\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {\n timeoutMs,\n toolName,\n }),\n );\n }, timeoutMs);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/** Renders a byte cap the way the error message should read (e.g. \"1 MiB\"). */\nconst formatBytes = (bytes: number): string => {\n if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {\n return `${bytes / (1024 * 1024)} MiB`;\n }\n\n if (bytes >= 1024 && bytes % 1024 === 0) {\n return `${bytes / 1024} KiB`;\n }\n\n return `${bytes} bytes`;\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const completer =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n // On the schema, not here: the SDK derives `prompts/list` arguments from\n // the schema's JSON Schema.\n const valueSchema = arg.enum?.length\n ? z.enum(arg.enum as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return z.object(shape);\n};\n\n/** Normalizes the several shapes `execute` may return into a CallToolResult. */\nconst normalizeToolResult = (result: unknown): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n if (\n value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\"\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nexport const readCappedBody = async (\n request: Request,\n): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via Basic auth. Body wins.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator !== -1) {\n params.client_id ||= decodeURIComponent(decoded.slice(0, separator));\n params.client_secret ||= decodeURIComponent(\n decoded.slice(separator + 1),\n );\n }\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","export class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n } else {\n this.#cache.clear();\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(url);\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n this.#inFlight.delete(url);\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(url: string): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // store in cache with expiration\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n let ajvModule;\n\n try {\n ajvModule = await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n const ajv = new Ajv({ allErrors: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(schema);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n const path = error.instancePath\n .split(\"/\")\n .filter(Boolean)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return Number.isInteger(index) && segment !== \"\" ? index : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,OAEf;AACP;AAAA,EACE;AAAA,OAEK;AAEP,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;AACrB,SAAS,YAAY;AACrB,OAAO,UAAU;AACjB,OAAO,WAAW;AAClB,SAAS,cAAc,aAAa;AACpC,SAAS,SAAAC,cAAa;AACtB,OAAO,sBAAsB;AAC7B,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,SAAS;;;AC7BlB,SAAS,YAAY;AAKd,IAAM,4BAA4B,OAAO;AAOhD,IAAM,gBAAgB,CAAC,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A,MACE;AAAA,OACC,OAAO,WAAmB,MAAM,UAAU,KAAK,GAAG;AAAA,IACrD,IACA;AACJ,UAAM,IAAI,IAAI,IAAK,IAAI,WAAW,OAAO,KAAK,SAAS;AAAA,EACzD;AAEA,SAAO,EAAE,OAAO,KAAK;AACvB;AAGA,IAAM,sBAAsB,CAAC,WAA6B;AACxD,MAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,WAAO,EAAE,SAAS,CAAC,EAAE;AAAA,EACvB;AAEA,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC,EAAE;AAAA,EACrD;AAEA,MAAI,OAAO,WAAW,UAAU;AAC9B,UAAM,QAAQ;AAGd,QAAI,MAAM,eAAe,oBAAoB,MAAM,QAAQ,MAAM,OAAO,GAAG;AACzE,aAAO;AAAA,IACT;AAEA,QACE,MAAM,SAAS,UACf,MAAM,SAAS,WACf,MAAM,SAAS,WACf,MAAM,SAAS,cACf,MAAM,SAAS,iBACf;AACA,aAAO,EAAE,SAAS,CAAC,KAAK,EAAE;AAAA,IAC5B;AAIA,WAAO;AAAA,MACL,SAAS,CAAC,EAAE,MAAM,KAAK,UAAU,KAAK,GAAG,MAAM,OAAO,CAAC;AAAA,MACvD,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,OAAO,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE;AAC7D;","names":["Hono","fetch","fetch","ServerState","Hono"]}
|
|
1
|
+
{"version":3,"sources":["../src/ViteMCP.ts","../src/auth/router.ts","../src/DiscoveryDocumentCache.ts","../src/jsonSchemaAdapter.ts"],"sourcesContent":["import {\n acceptedContent,\n type CacheScope,\n completable,\n createMcpHandler,\n fromJsonSchema,\n type InputRequest,\n inputRequired,\n type InputRequiredResult,\n localhostAllowedOrigins,\n type McpHttpHandler,\n McpServer,\n originValidationResponse,\n ResourceTemplate as SDKResourceTemplate,\n type ToolAnnotations as SDKToolAnnotations,\n} from \"@modelcontextprotocol/server\";\nimport {\n serveStdio,\n type StdioServerHandle,\n} from \"@modelcontextprotocol/server/stdio\";\nimport { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { readFile } from \"fs/promises\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport http from \"http\";\nimport https from \"https\";\nimport { setTimeout as delay } from \"timers/promises\";\nimport { fetch } from \"undici\";\nimport parseURITemplate from \"uri-templates\";\nimport { strictJsonSchema, toJsonSchema } from \"xsschema\";\nimport { z } from \"zod\";\n\nimport type { OAuthProxy } from \"./auth/OAuthProxy.js\";\nimport type {\n AuthProvider,\n OAuthSession,\n} from \"./auth/providers/AuthProvider.js\";\n\nimport { createOAuthRouter, OAUTH_PROXY_MAX_BODY_SIZE } from \"./auth/router.js\";\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n log: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport const MEDIA_FETCH_TIMEOUT_MS = 30000;\n\ntype MediaSource = { timeoutMs?: number } & (\n | { buffer: Buffer }\n | { path: string }\n | { url: string }\n);\n\nexport abstract class ViteMCPError extends Error {\n public constructor(message?: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class UnexpectedStateError extends ViteMCPError {\n public extras?: Record<string, unknown>;\n\n public constructor(message: string, extras?: Record<string, unknown>) {\n super(message);\n this.name = new.target.name;\n this.extras = extras;\n }\n}\n\n/**\n * An error that is meant to be surfaced to the user, rather than logged as an\n * internal failure. Thrown from a tool handler, it becomes the tool's error\n * result rather than a protocol-level error.\n */\nexport class UserError extends UnexpectedStateError {}\n\nconst readMedia = async (\n source: MediaSource,\n kind: \"audio\" | \"image\",\n): Promise<{ data: string; mimeType: string }> => {\n let rawData: Buffer;\n\n try {\n if (\"url\" in source) {\n const response = await fetch(source.url, {\n signal: AbortSignal.timeout(source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n throw new Error(`Server responded with status: ${response.status}`);\n }\n\n rawData = Buffer.from(await response.arrayBuffer());\n } else if (\"path\" in source) {\n rawData = await readFile(source.path);\n } else if (\"buffer\" in source) {\n rawData = source.buffer;\n } else {\n throw new Error(\n `Invalid ${kind} source: provide one of url, path, or buffer`,\n );\n }\n } catch (error) {\n if (\"url\" in source) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `timed out after ${source.timeoutMs ?? MEDIA_FETCH_TIMEOUT_MS}ms`\n : error instanceof Error\n ? error.message\n : String(error);\n\n throw new Error(\n `Failed to fetch ${kind} from URL (${source.url}): ${reason}`,\n );\n }\n\n if (error instanceof Error) {\n throw error;\n }\n\n throw new Error(`Unexpected error processing ${kind}: ${String(error)}`);\n }\n\n const { fileTypeFromBuffer } = await import(\"file-type\");\n const mimeType = await fileTypeFromBuffer(rawData);\n\n return {\n data: rawData.toString(\"base64\"),\n mimeType: mimeType?.mime ?? (kind === \"image\" ? \"image/png\" : \"audio/mpeg\"),\n };\n};\n\nexport const imageContent = async (\n source: MediaSource,\n): Promise<ImageContent> => {\n const { data, mimeType } = await readMedia(source, \"image\");\n return { data, mimeType, type: \"image\" } as const;\n};\n\nexport const audioContent = async (\n source: MediaSource,\n): Promise<AudioContent> => {\n const { data, mimeType } = await readMedia(source, \"audio\");\n return { data, mimeType, type: \"audio\" } as const;\n};\n\nexport enum ServerState {\n Error = \"error\",\n Running = \"running\",\n Starting = \"starting\",\n Stopped = \"stopped\",\n}\n\nexport type AudioContent = {\n data: string;\n mimeType: string;\n type: \"audio\";\n};\n\n/**\n * Freshness hint attached to cacheable results (`tools/list`, `prompts/list`,\n * `resources/list`, `resources/templates/list`, `resources/read`). Required by\n * the 2026-07-28 revision's `CacheableResult`.\n */\nexport type CacheHint = {\n cacheScope?: CacheScope;\n ttlMs?: number;\n};\n\n/** The spec's completion payload. */\nexport type Completion = {\n hasMore?: boolean;\n total?: number;\n values: string[];\n};\n\nexport type Content =\n | AudioContent\n | ImageContent\n | ResourceContent\n | ResourceLink\n | TextContent;\n\nexport type ContentResult = {\n content: Content[];\n isError?: boolean;\n structuredContent?: unknown;\n};\n\n/**\n * Context handed to `execute` / `load`. Everything here is per-request: the\n * 2026-07-28 revision has no protocol session.\n */\nexport type Context<T extends ViteMCPAuth> = {\n /** Authentication result for this request, if an `authenticate` hook ran. */\n auth: T | undefined;\n\n /**\n * Builds an elicitation request for {@link Context.inputRequired}.\n *\n * A builder, not a promise — the server cannot block waiting for a reply.\n * The client re-issues the whole request with `inputResponses` populated.\n */\n elicit: (params: {\n message: string;\n requestedSchema: StandardSchemaV1;\n }) => InputRequest;\n\n /**\n * Reads one entry of `inputResponses` and validates it against the schema\n * used to request it. Returns `undefined` when the client declined or the\n * content does not match.\n */\n input: <S extends StandardSchemaV1>(\n key: string,\n schema: S,\n ) => StandardSchemaV1.InferOutput<S> | undefined;\n\n /**\n * Ask the client for more input and end this round.\n *\n * `requestState` round-trips through the client, so it is\n * attacker-controlled on return: sign it if it affects authorization.\n */\n inputRequired: (\n inputRequests: Record<string, InputRequest>,\n requestState?: string,\n ) => InputRequiredResult;\n\n /**\n * Present when the client is retrying a request that previously returned\n * `input_required`. Absent on the first call.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Emits `notifications/message`. The spec forbids emitting these unless the\n * request opted in via `_meta` log level, so these are dropped when the\n * client did not ask for logs.\n */\n log: {\n debug: (message: string, data?: SerializableValue) => void;\n error: (message: string, data?: SerializableValue) => void;\n info: (message: string, data?: SerializableValue) => void;\n warn: (message: string, data?: SerializableValue) => void;\n };\n\n reportProgress: (progress: Progress) => Promise<void>;\n\n /** Request ID of the current MCP request. */\n requestId?: string;\n\n /** The `requestState` echoed back by the client on an MRTR retry. */\n requestState?: string;\n};\n\nexport type ImageContent = {\n data: string;\n mimeType: string;\n type: \"image\";\n};\n\n/**\n * A single loaded resource body. `uri` is optional: when omitted the server\n * fills it in from the resource (or the expanded template) that produced it.\n */\nexport type LoadedResource = {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri?: string;\n};\n\nexport type Prompt<T extends ViteMCPAuth> = {\n arguments?: PromptArgument[];\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any argument. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<{ messages: unknown[] } | string>;\n name: string;\n};\n\nexport type PromptArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n /** Constrains the argument to a fixed set of values. */\n enum?: string[];\n name: string;\n required?: boolean;\n};\n\nexport type Resource<T extends ViteMCPAuth> = {\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n load: (context: LoadContext<T>) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uri: string;\n};\n\nexport type ResourceTemplate<T extends ViteMCPAuth> = {\n arguments?: ResourceTemplateArgument[];\n cache?: CacheHint;\n canAccess?: (auth: T | undefined) => boolean;\n /** Completes any template variable. Per-argument `complete` wins over this. */\n complete?: (name: string, value: string) => Promise<Completion>;\n description?: string;\n load: (\n args: Record<string, string>,\n context: LoadContext<T>,\n ) => Promise<LoadedResource | LoadedResource[]>;\n mimeType?: string;\n name: string;\n uriTemplate: string;\n};\n\nexport type ResourceTemplateArgument = {\n complete?: (value: string) => Promise<Completion>;\n description?: string;\n name: string;\n required?: boolean;\n};\n\nexport type ServerOptions<T extends ViteMCPAuth> = {\n auth?: AuthProvider<T extends OAuthSession ? T : OAuthSession>;\n authenticate?: Authenticate<T>;\n health?: {\n enabled?: boolean;\n message?: string;\n path?: string;\n status?: number;\n };\n instructions?: string;\n logger?: Logger;\n name: string;\n oauth?: {\n authorizationServer?: Record<string, unknown>;\n enabled?: boolean;\n protectedResource?: Record<string, unknown>;\n proxy?: OAuthProxy;\n };\n version: `${number}.${number}.${number}`;\n};\n\nexport type TextContent = {\n text: string;\n type: \"text\";\n};\n\nexport type Tool<\n T extends ViteMCPAuth,\n Params extends ToolParameters = ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n> = {\n _meta?: Record<string, unknown>;\n annotations?: SDKToolAnnotations;\n canAccess?: (auth: T | undefined) => boolean;\n description?: string;\n execute: (\n args: StandardSchemaV1.InferOutput<Params>,\n context: Context<T>,\n ) => Promise<\n | AudioContent\n | ContentResult\n | ImageContent\n | InputRequiredResult\n | ResourceContent\n | ResourceLink\n | StandardSchemaV1.InferOutput<OutputParams>\n | string\n | TextContent\n | void\n >;\n name: string;\n outputSchema?: OutputParams;\n parameters?: Params;\n timeoutMs?: number;\n};\n\nexport type ViteMCPAuth = Record<string, unknown> | undefined;\n\ntype Authenticate<T> = (request: Request) => Promise<T>;\n\ntype Literal = boolean | null | number | string | undefined;\n\ntype LoadContext<T extends ViteMCPAuth> = Omit<Context<T>, \"reportProgress\">;\n\ntype Progress = {\n message?: string;\n progress: number;\n total?: number;\n};\n\ntype ResourceContent = {\n resource: {\n blob?: string;\n mimeType?: string;\n text?: string;\n uri: string;\n };\n type: \"resource\";\n};\n\ntype ResourceLink = {\n description?: string;\n mimeType?: string;\n name: string;\n type: \"resource_link\";\n uri: string;\n};\n\ntype SerializableValue =\n | { [key: string]: SerializableValue }\n | Literal\n | SerializableValue[];\n\ntype ToolParameters = StandardSchemaV1;\n\nexport class ViteMCP<T extends ViteMCPAuth = ViteMCPAuth> {\n /**\n * The port the HTTP server is actually listening on, or `null` when it is\n * not running over HTTP. Pass `httpStream.port: 0` to let the OS assign a\n * free port and read it back here — this avoids the race inherent in\n * picking a port first and binding it afterwards.\n */\n public get port(): null | number {\n const address = this.#httpServer?.address();\n return address && typeof address === \"object\" ? address.port : null;\n }\n\n public get serverState(): ServerState {\n return this.#serverState;\n }\n #authenticate: Authenticate<T> | undefined;\n #connectedServers: McpServer[] = [];\n #corsMiddleware: null | ReturnType<typeof cors> = null;\n #handler: McpHttpHandler | null = null;\n #honoApp = new Hono();\n #httpServer: http.Server | https.Server | null = null;\n #logger: Logger;\n #options: ServerOptions<T>;\n #prompts: Prompt<T>[] = [];\n #resources: Resource<T>[] = [];\n #resourceTemplates: ResourceTemplate<T>[] = [];\n #serverState: ServerState = ServerState.Stopped;\n #stdioHandle: null | StdioServerHandle = null;\n\n #tools: Tool<T>[] = [];\n\n public constructor(options: ServerOptions<T>) {\n this.#options = options;\n this.#logger = options.logger ?? console;\n\n // An AuthProvider supplies the authenticate hook. Resolved here rather\n // than inside the HTTP path so the wiring is not silently absent on\n // stdio / `connect()`.\n const provider = options.auth;\n this.#authenticate =\n options.authenticate ??\n (provider\n ? (((request: Request) =>\n provider.authenticate(request)) as unknown as Authenticate<T>)\n : undefined);\n\n this.#honoApp = this.#freshApp();\n }\n\n public addPrompt(prompt: Prompt<T>) {\n this.#prompts.push(prompt);\n this.#notifyListChanged(\"prompts\");\n }\n\n public addPrompts(prompts: Prompt<T>[]) {\n for (const prompt of prompts) {\n this.#prompts.push(prompt);\n }\n this.#notifyListChanged(\"prompts\");\n }\n\n public addResource(resource: Resource<T>) {\n this.#resources.push(resource);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResources(resources: Resource<T>[]) {\n for (const resource of resources) {\n this.#resources.push(resource);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplate(template: ResourceTemplate<T>) {\n this.#resourceTemplates.push(template);\n this.#notifyListChanged(\"resources\");\n }\n\n public addResourceTemplates(templates: ResourceTemplate<T>[]) {\n for (const template of templates) {\n this.#resourceTemplates.push(template);\n }\n this.#notifyListChanged(\"resources\");\n }\n\n public addTool<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tool: Tool<T, Params, OutputParams>) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n this.#notifyListChanged(\"tools\");\n }\n\n public addTools<\n Params extends ToolParameters,\n OutputParams extends ToolParameters = ToolParameters,\n >(tools: Tool<T, Params, OutputParams>[]) {\n for (const tool of tools) {\n assertStandardSchema(tool.parameters, tool.name, \"parameters\");\n assertStandardSchema(tool.outputSchema, tool.name, \"outputSchema\");\n this.#tools.push(tool as unknown as Tool<T>);\n }\n this.#notifyListChanged(\"tools\");\n }\n\n /**\n * Connects the server to an arbitrary transport — used for in-memory unit\n * testing, where a linked transport pair replaces a real socket.\n */\n public async connect(\n transport: Parameters<McpServer[\"connect\"]>[0],\n ): Promise<McpServer> {\n const server = await this.#buildServer(undefined);\n await server.connect(transport);\n this.#connectedServers.push(server);\n this.#serverState = ServerState.Running;\n return server;\n }\n\n /**\n * Resolves a resource (or resource template) URI to an embeddable resource\n * body, for returning inline from a tool.\n */\n public async embedded(uri: string): Promise<LoadedResource> {\n const direct = this.#resources.find((resource) => resource.uri === uri);\n\n if (direct) {\n const loaded = await direct.load(this.#makeContext(undefined, undefined));\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(`Resource loaded no content: ${uri}`, {\n uri,\n });\n }\n\n return { ...first, mimeType: first.mimeType ?? direct.mimeType, uri };\n }\n\n for (const template of this.#resourceTemplates) {\n const params = parseURITemplate(template.uriTemplate).fromUri(uri);\n\n if (!params) {\n continue;\n }\n\n const loaded = await template.load(\n params as Record<string, string>,\n this.#makeContext(undefined, undefined),\n );\n const first = Array.isArray(loaded) ? loaded[0] : loaded;\n\n if (!first) {\n throw new UnexpectedStateError(\n `Resource template loaded no content: ${uri}`,\n { uri },\n );\n }\n\n return { ...first, mimeType: first.mimeType ?? template.mimeType, uri };\n }\n\n throw new UnexpectedStateError(`Resource not found: ${uri}`, { uri });\n }\n\n /** The Hono app serving the HTTP transport, for mounting custom routes. */\n public getApp(): Hono {\n return this.#honoApp;\n }\n\n /**\n * Publishes `notifications/resources/updated` for a URI to any subscription\n * that opted in to it.\n */\n public notifyResourceUpdated(uri: string): void {\n this.#handler?.notify.resourceUpdated(uri);\n }\n\n public removePrompt(name: string) {\n this.#prompts = this.#prompts.filter((p) => p.name !== name);\n this.#notifyListChanged(\"prompts\");\n }\n\n public removePrompts(names: string[]) {\n this.#prompts = this.#prompts.filter((p) => !names.includes(p.name));\n this.#notifyListChanged(\"prompts\");\n }\n\n public removeResource(name: string) {\n this.#resources = this.#resources.filter((r) => r.name !== name);\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResources(names: string[]) {\n this.#resources = this.#resources.filter((r) => !names.includes(r.name));\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplate(name: string) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => r.name !== name,\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeResourceTemplates(names: string[]) {\n this.#resourceTemplates = this.#resourceTemplates.filter(\n (r) => !names.includes(r.name),\n );\n this.#notifyListChanged(\"resources\");\n }\n\n public removeTool(name: string) {\n this.#tools = this.#tools.filter((t) => t.name !== name);\n this.#notifyListChanged(\"tools\");\n }\n\n public removeTools(names: string[]) {\n this.#tools = this.#tools.filter((t) => !names.includes(t.name));\n this.#notifyListChanged(\"tools\");\n }\n\n public async start(\n options:\n | {\n httpStream: {\n /** Origins permitted to reach the MCP endpoint (DNS-rebinding guard). */\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n /**\n * Whether to also serve 2025-era clients. Defaults to\n * `\"stateless\"`: the SDK client negotiates 2025 unless given\n * `versionNegotiation: { mode: \"auto\" }`. `\"reject\"` serves only\n * 2026-07-28 and enforces `Mcp-Method`/`Mcp-Name`.\n */\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n };\n transportType: \"httpStream\";\n }\n | { transportType: \"stdio\" },\n ): Promise<void> {\n this.#serverState = ServerState.Starting;\n\n try {\n if (options.transportType === \"stdio\") {\n this.#stdioHandle = serveStdio(() => this.#buildServer(undefined));\n this.#logger.info(`[ViteMCP info] server is running on stdio`);\n } else {\n await this.#startHttp(options.httpStream);\n }\n\n this.#serverState = ServerState.Running;\n } catch (error) {\n this.#serverState = ServerState.Error;\n throw error;\n }\n }\n\n public async stop(): Promise<void> {\n // Hono seals its matcher once used, so a restarted server needs a fresh\n // app; the routes are re-registered by the next `start()`.\n this.#honoApp = this.#freshApp();\n this.#corsMiddleware = null;\n\n for (const server of this.#connectedServers) {\n await server.close().catch(() => {});\n }\n this.#connectedServers = [];\n\n await this.#stdioHandle?.close?.();\n this.#stdioHandle = null;\n\n await this.#handler?.close();\n this.#handler = null;\n\n if (this.#httpServer) {\n await new Promise<void>((resolve) =>\n this.#httpServer!.close(() => resolve()),\n );\n this.#httpServer = null;\n }\n\n this.#serverState = ServerState.Stopped;\n }\n\n async #buildServer(auth: T | undefined): Promise<McpServer> {\n const server = new McpServer(\n { name: this.#options.name, version: this.#options.version },\n { instructions: this.#options.instructions },\n );\n\n for (const tool of this.#tools) {\n if (tool.canAccess && !tool.canAccess(auth)) {\n continue;\n }\n\n server.registerTool(\n tool.name,\n {\n _meta: tool._meta,\n annotations: tool.annotations,\n description: tool.description,\n inputSchema: (await this.#toSdkSchema(\n tool.parameters,\n `Tool \"${tool.name}\" parameters`,\n )) as never,\n outputSchema: (await this.#toSdkSchema(\n tool.outputSchema,\n `Tool \"${tool.name}\" outputSchema`,\n )) as never,\n },\n (async (args: unknown, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n\n try {\n const result = await (tool.timeoutMs\n ? withTimeout(\n tool.execute(args, context),\n tool.timeoutMs,\n tool.name,\n )\n : tool.execute(args, context));\n return normalizeToolResult(result);\n } catch (error) {\n if (error instanceof UserError) {\n return {\n content: [{ text: error.message, type: \"text\" }],\n isError: true,\n ...(error.extras ? { structuredContent: error.extras } : {}),\n };\n }\n throw error;\n }\n }) as never,\n );\n }\n\n for (const resource of this.#resources) {\n if (resource.canAccess && !resource.canAccess(auth)) {\n continue;\n }\n\n server.registerResource(\n resource.name,\n resource.uri,\n {\n cacheHint: resource.cache,\n description: resource.description,\n mimeType: resource.mimeType,\n },\n (async (uri: URL, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await resource.load(context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? resource.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const template of this.#resourceTemplates) {\n if (template.canAccess && !template.canAccess(auth)) {\n continue;\n }\n\n const complete: Record<string, (value: string) => Promise<string[]>> = {};\n for (const arg of template.arguments ?? []) {\n const completer =\n arg.complete ??\n (template.complete\n ? (value: string) => template.complete!(arg.name, value)\n : undefined);\n\n if (completer) {\n complete[arg.name] = async (value: string) =>\n (await completer(value)).values;\n }\n }\n\n server.registerResource(\n template.name,\n new SDKResourceTemplate(template.uriTemplate, {\n complete: complete as never,\n list: undefined,\n }),\n {\n cacheHint: template.cache,\n description: template.description,\n mimeType: template.mimeType,\n },\n (async (uri: URL, args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await template.load(args ?? {}, context);\n const bodies = Array.isArray(loaded) ? loaded : [loaded];\n return {\n contents: bodies.map((body) => ({\n ...body,\n mimeType: body.mimeType ?? template.mimeType,\n uri: body.uri ?? uri.toString(),\n })),\n };\n }) as never,\n );\n }\n\n for (const prompt of this.#prompts) {\n if (prompt.canAccess && !prompt.canAccess(auth)) {\n continue;\n }\n\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: promptArgsSchema(prompt),\n description: prompt.description,\n } as never,\n (async (args: Record<string, string>, ctx: unknown) => {\n const context = this.#makeContext(auth, ctx);\n const loaded = await prompt.load(args ?? {}, context);\n\n if (typeof loaded !== \"string\") {\n return loaded;\n }\n\n return {\n messages: [\n {\n content: { text: loaded, type: \"text\" },\n role: \"user\" as const,\n },\n ],\n };\n }) as never,\n );\n }\n\n return server;\n }\n\n /** Builds the Hono app with the CORS shim installed ahead of user routes. */\n #freshApp(): Hono {\n const app = new Hono();\n\n app.use(\"*\", (c, next) =>\n this.#corsMiddleware ? this.#corsMiddleware(c, next) : next(),\n );\n\n return app;\n }\n\n /** Bridges the v2 per-request context onto ViteMCP's `Context`. */\n #makeContext(auth: T | undefined, rawCtx: unknown): Context<T> {\n const ctx = rawCtx as {\n mcpReq?: {\n _meta?: {\n \"io.modelcontextprotocol/logLevel\"?: string;\n progressToken?: number | string;\n };\n id?: string;\n inputResponses?: Record<string, unknown>;\n notify?: (n: unknown) => Promise<void>;\n requestState?: <T>() => T | undefined;\n };\n };\n const mcpReq = ctx?.mcpReq;\n\n // The spec forbids `notifications/message` for a request that did not opt\n // in via `_meta`. Failures are swallowed: a log line must never take down\n // the request.\n const requestedLevel = mcpReq?._meta?.[\"io.modelcontextprotocol/logLevel\"];\n\n const emit = (level: string, message: string, data?: SerializableValue) => {\n if (!requestedLevel) {\n return;\n }\n\n void mcpReq\n ?.notify?.({\n method: \"notifications/message\",\n params: { data: { context: data, message }, level },\n })\n ?.catch(() => {});\n };\n\n return {\n auth,\n elicit: (params) =>\n inputRequired.elicit({\n message: params.message,\n requestedSchema: params.requestedSchema as never,\n }),\n input: (key, schema) =>\n acceptedContent(mcpReq?.inputResponses, key, schema as never) as never,\n inputRequired: (inputRequests, requestState) =>\n inputRequired({ inputRequests, requestState }),\n inputResponses: mcpReq?.inputResponses,\n log: {\n debug: (m, d) => emit(\"debug\", m, d),\n error: (m, d) => emit(\"error\", m, d),\n info: (m, d) => emit(\"info\", m, d),\n warn: (m, d) => emit(\"warning\", m, d),\n },\n reportProgress: async (progress) => {\n const progressToken = mcpReq?._meta?.progressToken;\n\n // No token means the client did not ask for progress on this request;\n // emitting anyway would be an uncorrelatable notification.\n if (progressToken === undefined) {\n return;\n }\n\n await mcpReq?.notify?.({\n method: \"notifications/progress\",\n params: {\n message: progress.message,\n progress: progress.progress,\n progressToken,\n total: progress.total,\n },\n });\n },\n requestId: mcpReq?.id,\n // The SDK exposes this as an accessor; call it so callers get the value.\n requestState: mcpReq?.requestState?.<string>(),\n };\n }\n\n /**\n * Publishes a change event to any open `subscriptions/listen` stream. This\n * replaces the 2025-era `notifications/*_list_changed` broadcast, which had\n * no addressee on a stateless transport.\n */\n #notifyListChanged(kind: \"prompts\" | \"resources\" | \"tools\") {\n // Typed on purpose: a cast here once let wrong method names no-op.\n const notifier = this.#handler?.notify;\n\n if (!notifier) {\n return;\n }\n\n if (kind === \"tools\") notifier.toolsChanged();\n if (kind === \"prompts\") notifier.promptsChanged();\n if (kind === \"resources\") notifier.resourcesChanged();\n }\n\n async #startHttp(config: {\n allowedOrigins?: string[];\n basePath?: string;\n cors?: false | Parameters<typeof cors>[0];\n enableJsonResponse?: boolean;\n endpoint?: string;\n host?: string;\n legacy?: \"reject\" | \"stateless\";\n maxBodySize?: number;\n port: number;\n sslCa?: string;\n sslCert?: string;\n sslKey?: string;\n }): Promise<void> {\n this.#handler = createMcpHandler(\n async (ctx) => {\n // `ctx.requestInfo` is the real field; a previous cast invented `req`\n // and silently handed every hook `undefined`.\n const request = ctx.requestInfo;\n\n const auth =\n this.#authenticate && request\n ? await this.#authenticate(request)\n : undefined;\n\n return this.#buildServer(auth);\n },\n {\n // Tradeoff: `server/discover` advertises only 2026-07-28, so legacy\n // requests are answered unadvertised and skip Mcp-* validation.\n legacy: config.legacy ?? \"stateless\",\n ...(config.enableJsonResponse ? { responseMode: \"json\" as const } : {}),\n onerror: (error) => this.#logger.error(\"[ViteMCP error]\", error),\n },\n );\n\n this.#corsMiddleware = config.cors === false ? null : cors(config.cors);\n\n const oauth = this.#options.oauth ?? this.#options.auth?.getOAuthConfig();\n\n if (\n oauth?.enabled !== false &&\n (oauth?.proxy ?? oauth?.authorizationServer ?? oauth?.protectedResource)\n ) {\n this.#honoApp.route(\n \"/\",\n createOAuthRouter({\n authorizationServer: oauth.authorizationServer,\n basePath: config.basePath,\n endpoint: config.endpoint ?? \"/mcp\",\n protectedResource: oauth.protectedResource,\n proxy: oauth.proxy,\n }),\n );\n }\n\n const health = this.#options.health;\n if (health?.enabled !== false) {\n this.#honoApp.get(health?.path ?? \"/health\", (c) =>\n c.text(health?.message ?? \"ok\", (health?.status ?? 200) as 200),\n );\n }\n\n const endpoint = `${config.basePath ?? \"\"}${config.endpoint ?? \"/mcp\"}`;\n const handler = this.#handler;\n const host = config.host ?? \"127.0.0.1\";\n const isLoopback = [\"::1\", \"127.0.0.1\", \"localhost\"].includes(host);\n\n // Default-deny on loopback (the DNS-rebinding case); a routable bind is\n // assumed deliberate and must configure its own origins.\n const allowedOrigins =\n config.allowedOrigins ?? (isLoopback ? localhostAllowedOrigins() : []);\n\n if (!config.allowedOrigins && !isLoopback) {\n this.#logger.warn(\n `[ViteMCP warning] no 'allowedOrigins' configured while bound to ${host}; browser origins will be rejected`,\n );\n }\n\n // A Hono route, not a pre-routing short-circuit, so CORS covers it.\n // Routing around Hono 405'd every preflight — and this revision makes\n // every POST preflighted via `Mcp-Method`/`Mcp-Name`.\n this.#honoApp.all(endpoint, async (c) => {\n // Transport security (MUST): a present-but-unrecognised Origin is 403.\n // Stops DNS rebinding; requests with no Origin are unaffected.\n const rejected = originValidationResponse(c.req.raw, allowedOrigins);\n\n if (rejected) {\n return rejected;\n }\n\n return handler.fetch(c.req.raw);\n });\n\n const app = this.#honoApp;\n const maxBodySize = config.maxBodySize ?? OAUTH_PROXY_MAX_BODY_SIZE;\n\n const useTls = Boolean(config.sslCert && config.sslKey);\n\n const requestListener = (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ) => {\n void (async () => {\n try {\n // The cap must apply before conversion: reading first and\n // measuring after is the DoS this guards against.\n const body = await readCappedNodeBody(req, maxBodySize);\n\n if (body === OVERSIZE) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n // Drain rather than pause (pausing stalls the response), then\n // half-close once the 400 has flushed. A forced destroy would RST\n // while the client is still writing and discard the response.\n req.resume();\n res.once(\"finish\", () => res.socket?.end());\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: `Request body exceeds ${formatBytes(maxBodySize)}`,\n }),\n );\n return;\n }\n\n // Node req/res go through as Hono's env so custom routes can still\n // reach `c.env.incoming`.\n const response = await app.fetch(\n nodeToWebRequest(req, body, useTls),\n {\n incoming: req,\n outgoing: res,\n },\n );\n\n res.writeHead(response.status, Object.fromEntries(response.headers));\n res.end(Buffer.from(await response.arrayBuffer()));\n } catch (error) {\n // A body that aborts mid-stream rejects here. Settle with a 400\n // rather than leaving the exchange pending forever.\n this.#logger.debug(`[ViteMCP debug] request failed:`, error);\n\n if (!res.headersSent) {\n res.writeHead(400, {\n Connection: \"close\",\n \"Content-Type\": \"application/json\",\n });\n }\n\n res.end(\n JSON.stringify({\n error: \"invalid_request\",\n error_description: \"Request body could not be read\",\n }),\n );\n }\n })();\n };\n\n // TLS is terminated here when certs are supplied, rather than assuming a\n // proxy in front.\n this.#httpServer = useTls\n ? https.createServer(\n {\n ...(config.sslCa ? { ca: await readFile(config.sslCa) } : {}),\n cert: await readFile(config.sslCert!),\n key: await readFile(config.sslKey!),\n },\n requestListener,\n )\n : http.createServer(requestListener);\n\n await new Promise<void>((resolve) =>\n this.#httpServer!.listen(\n config.port,\n config.host ?? \"127.0.0.1\",\n resolve,\n ),\n );\n\n this.#logger.info(\n `[ViteMCP info] server is running on ${useTls ? \"HTTPS\" : \"HTTP\"} at ${\n useTls ? \"https\" : \"http\"\n }://${config.host ?? \"127.0.0.1\"}:${this.port ?? config.port}${endpoint}`,\n );\n }\n\n /**\n * Converts a schema the SDK cannot consume directly. Zod v4 emits JSON\n * Schema natively; valibot/arktype go via xsschema.\n */\n async #toSdkSchema(schema: unknown, label: string): Promise<unknown> {\n if (!schema) {\n return undefined;\n }\n\n const standard = (schema as { \"~standard\"?: { jsonSchema?: unknown } })[\n \"~standard\"\n ];\n\n if (standard?.jsonSchema) {\n return schema;\n }\n\n try {\n const json = strictJsonSchema(await toJsonSchema(schema as never));\n return fromJsonSchema(json as never);\n } catch (error) {\n throw new UnexpectedStateError(\n `${label} is not a supported Standard Schema: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { label },\n );\n }\n }\n}\n\n/**\n * Builds a web-standard Request from a Node request whose body is already\n * consumed. The SDK's `toWebRequest` would either re-read the drained stream\n * or JSON-stringify the body a second time.\n */\nconst nodeToWebRequest = (\n req: http.IncomingMessage,\n body: Buffer,\n secure: boolean,\n): Request => {\n const host = req.headers.host ?? \"localhost\";\n // Scheme has to follow the listener, or absolute URLs derived from\n // `c.req.url` (issuers, redirect URIs) come out as http:// under TLS.\n const url = `${secure ? \"https\" : \"http\"}://${host}${req.url ?? \"/\"}`;\n const headers = new Headers();\n\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined || name.startsWith(\":\")) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, value);\n }\n }\n\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body.byteLength > 0;\n\n return new Request(url, {\n headers,\n method,\n ...(hasBody ? { body } : {}),\n });\n};\n\n/**\n * Rejects if a tool outruns its `timeoutMs`. The work itself is not cancelled\n * — `execute` owns whatever it started — but the caller stops waiting.\n */\nconst withTimeout = <T>(\n work: Promise<T>,\n timeoutMs: number,\n toolName: string,\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new UserError(`Tool '${toolName}' timed out after ${timeoutMs}ms`, {\n timeoutMs,\n toolName,\n }),\n );\n }, timeoutMs);\n\n work.then(resolve, reject).finally(() => clearTimeout(timer));\n });\n\n/** Renders a byte cap the way the error message should read (e.g. \"1 MiB\"). */\nconst formatBytes = (bytes: number): string => {\n if (bytes >= 1024 * 1024 && bytes % (1024 * 1024) === 0) {\n return `${bytes / (1024 * 1024)} MiB`;\n }\n\n if (bytes >= 1024 && bytes % 1024 === 0) {\n return `${bytes / 1024} KiB`;\n }\n\n return `${bytes} bytes`;\n};\n\n/** Sentinel returned when a request body exceeds the configured cap. */\nconst OVERSIZE = Symbol(\"oversize\");\n\n/**\n * Reads a Node request body with a hard cap, bailing out as soon as the limit\n * is crossed rather than after the fact. A declared `Content-Length` over the\n * cap short-circuits before any chunk is read.\n */\nconst readCappedNodeBody = async (\n req: http.IncomingMessage,\n maxBytes: number,\n): Promise<Buffer | typeof OVERSIZE> => {\n const declared = Number(req.headers[\"content-length\"] ?? 0);\n\n if (declared > maxBytes) {\n return OVERSIZE;\n }\n\n let size = 0;\n const chunks: Buffer[] = [];\n\n for await (const chunk of req) {\n const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);\n size += buf.byteLength;\n\n if (size > maxBytes) {\n return OVERSIZE;\n }\n\n chunks.push(buf);\n }\n\n return Buffer.concat(chunks);\n};\n\n/** Rejects non-Standard-Schema at registration, not on first call. */\nconst assertStandardSchema = (\n schema: unknown,\n toolName: string,\n field: \"outputSchema\" | \"parameters\",\n) => {\n if (schema === undefined) {\n return;\n }\n\n const standard = (schema as { \"~standard\"?: { validate?: unknown } })?.[\n \"~standard\"\n ];\n\n if (typeof standard?.validate !== \"function\") {\n throw new UnexpectedStateError(\n `Tool '${toolName}' ${field} must implement Standard Schema. If you are using Zod, upgrade to version 3.24 or later.`,\n { toolName },\n );\n }\n};\n\nconst promptArgsSchema = <T extends ViteMCPAuth>(prompt: Prompt<T>) => {\n const args = prompt.arguments;\n\n if (!args?.length) {\n return undefined;\n }\n\n const shape: Record<string, z.ZodType> = {};\n for (const arg of args) {\n const completer =\n arg.complete ??\n (prompt.complete\n ? (value: string) => prompt.complete!(arg.name, value)\n : undefined);\n // On the schema, not here: the SDK derives `prompts/list` arguments from\n // the schema's JSON Schema.\n const valueSchema = arg.enum?.length\n ? z.enum(arg.enum as [string, ...string[]])\n : z.string();\n const described = arg.description\n ? valueSchema.describe(arg.description)\n : valueSchema;\n const base = completer\n ? completable(\n described,\n (async (value: string) => (await completer(value)).values) as never,\n )\n : described;\n shape[arg.name] = (arg.required ? base : base.optional()) as z.ZodType;\n }\n\n return z.object(shape);\n};\n\n/** Normalizes the several shapes `execute` may return into a CallToolResult. */\nconst normalizeToolResult = (result: unknown): unknown => {\n if (result === undefined || result === null) {\n return { content: [] };\n }\n\n if (typeof result === \"string\") {\n return { content: [{ text: result, type: \"text\" }] };\n }\n\n if (typeof result === \"object\") {\n const value = result as Record<string, unknown>;\n\n // Already an input_required (MRTR) or a full content result — pass through.\n if (value.resultType === \"input_required\" || Array.isArray(value.content)) {\n return value;\n }\n\n if (\n value.type === \"text\" ||\n value.type === \"image\" ||\n value.type === \"audio\" ||\n value.type === \"resource\" ||\n value.type === \"resource_link\"\n ) {\n return { content: [value] };\n }\n\n // Also carry serialized JSON as text, for clients that ignore\n // `structuredContent`.\n return {\n content: [{ text: JSON.stringify(value), type: \"text\" }],\n structuredContent: value,\n };\n }\n\n return { content: [{ text: String(result), type: \"text\" }] };\n};\n\nexport { delay };\n\n// Convenience re-exports so the common auth surface is reachable from the\n// package root; `@vitemcp/server/auth` remains the full module.\nexport {\n AuthProvider,\n AzureProvider,\n getAuthSession,\n GitHubProvider,\n GoogleProvider,\n OAuthProvider,\n requireAll,\n requireAny,\n requireAuth,\n requireRole,\n requireScopes,\n} from \"./auth/index.js\";\n\nexport type {\n AuthProviderConfig,\n AzureProviderConfig,\n AzureSession,\n GenericOAuthProviderConfig,\n GitHubSession,\n GoogleSession,\n OAuthSession,\n} from \"./auth/index.js\";\n\nexport { DiscoveryDocumentCache } from \"./DiscoveryDocumentCache.js\";\n\nexport {\n jsonSchemaAdapter,\n type JsonSchemaObject,\n type JsonSchemaStandardSchema,\n} from \"./jsonSchemaAdapter.js\";\n","/** OAuth proxy HTTP routes, as a Hono router. */\nimport { Hono } from \"hono\";\n\nimport type { OAuthProxy } from \"./OAuthProxy.js\";\n\n/** Bodies larger than this are rejected before parsing (DoS guard). */\nexport const OAUTH_PROXY_MAX_BODY_SIZE = 1024 * 1024;\n\ntype OAuthErrorish = {\n statusCode?: number;\n toJSON?: () => unknown;\n};\n\nconst errorResponse = (error: unknown) => {\n const err = error as OAuthErrorish;\n return {\n body: err.toJSON?.() ?? { error: \"invalid_request\" },\n status: (err.statusCode ?? 400) as 400,\n };\n};\n\n/**\n * Reads a body under a hard cap, enforced *while* reading — measuring after\n * buffering would let a client push arbitrary bytes into memory.\n *\n * Returns `null` when the body is too large, aborted, or unreadable.\n */\nconst readCappedBody = async (request: Request): Promise<null | string> => {\n const declared = request.headers.get(\"content-length\");\n\n if (declared && Number(declared) > OAUTH_PROXY_MAX_BODY_SIZE) {\n return null;\n }\n\n if (!request.body) {\n try {\n const text = await request.text();\n return text.length > OAUTH_PROXY_MAX_BODY_SIZE ? null : text;\n } catch {\n return null;\n }\n }\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n size += value.byteLength;\n\n if (size > OAUTH_PROXY_MAX_BODY_SIZE) {\n await reader.cancel().catch(() => {});\n return null;\n }\n\n chunks.push(value);\n }\n } catch {\n // Aborted or errored mid-body: settle rather than leaving it pending.\n return null;\n }\n\n return Buffer.concat(chunks).toString(\"utf8\");\n};\n\nconst readJsonBody = async (request: Request): Promise<null | unknown> => {\n const text = await readCappedBody(request);\n\n if (text === null) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n};\n\nconst tooLarge = {\n error: \"invalid_request\",\n error_description: `Request body exceeds ${OAUTH_PROXY_MAX_BODY_SIZE / (1024 * 1024)} MiB`,\n};\n\n/**\n * RFC 8414 / 9728 metadata is snake_case on the wire; config is camelCase.\n * Top-level keys only — nested values are caller-defined payloads.\n */\nconst toSnakeCase = (value: unknown): unknown => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([k, v]) => [\n k.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase(),\n v,\n ]),\n );\n};\n\nexport type OAuthRouterOptions = {\n authorizationServer?: unknown;\n /** Path prefix the server is mounted under, e.g. \"/issuer1\". */\n basePath?: string;\n /** MCP endpoint path, e.g. \"/mcp\". */\n endpoint?: string;\n protectedResource?: unknown;\n /** Optional: discovery metadata can be served without a proxy. */\n proxy?: OAuthProxy;\n};\n\nexport const createOAuthRouter = (options: OAuthRouterOptions): Hono => {\n const app = new Hono();\n const { proxy } = options;\n\n const basePath = options.basePath ?? \"\";\n const endpoint = options.endpoint ?? \"\";\n\n // RFC 8414 §3 / 9728 §3: exact routes, not wildcards — an unrelated suffix\n // must 404 rather than serve metadata.\n const serve = (path: string, body: unknown) =>\n app.get(path, (c) => c.json(body as never));\n\n if (options.authorizationServer) {\n // Issuer-scoped: under a base path, the bare root is not valid.\n serve(\n `/.well-known/oauth-authorization-server${basePath}`,\n toSnakeCase(options.authorizationServer),\n );\n }\n\n if (options.protectedResource) {\n const body = toSnakeCase(options.protectedResource);\n const scoped = `/.well-known/oauth-protected-resource${basePath}${endpoint}`;\n\n // Sub-path takes priority; root stays as the documented fallback.\n serve(scoped, body);\n\n if (scoped !== \"/.well-known/oauth-protected-resource\") {\n serve(\"/.well-known/oauth-protected-resource\", body);\n }\n }\n\n if (!proxy) {\n return app;\n }\n\n // RFC 7591 Dynamic Client Registration.\n app.post(`${basePath}/oauth/register`, async (c) => {\n const body = await readJsonBody(c.req.raw);\n\n if (body === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n return c.json(await proxy.registerClient(body as never), 201);\n } catch (error) {\n const { body: errBody, status } = errorResponse(error);\n return c.json(errBody as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/authorize`, async (c) => {\n try {\n const params = Object.fromEntries(\n new URL(c.req.url).searchParams.entries(),\n );\n return await proxy.authorize(params as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.post(`${basePath}/oauth/token`, async (c) => {\n const raw = c.req.raw;\n const text = await readCappedBody(raw);\n\n if (text === null) {\n return c.json(tooLarge, 400);\n }\n\n try {\n const params = Object.fromEntries(new URLSearchParams(text).entries());\n\n // RFC 6749 §2.3.1: credentials may arrive via Basic auth. Body wins.\n const authHeader = raw.headers.get(\"authorization\");\n\n if (authHeader?.toLowerCase().startsWith(\"basic \")) {\n const decoded = Buffer.from(authHeader.slice(6), \"base64\").toString(\n \"utf8\",\n );\n const separator = decoded.indexOf(\":\");\n\n if (separator !== -1) {\n params.client_id ||= decodeURIComponent(decoded.slice(0, separator));\n params.client_secret ||= decodeURIComponent(\n decoded.slice(separator + 1),\n );\n }\n }\n\n const result =\n params.grant_type === \"refresh_token\"\n ? await proxy.exchangeRefreshToken(params as never)\n : await proxy.exchangeAuthorizationCode(params as never);\n\n return c.json(result as never);\n } catch (error) {\n const { body, status } = errorResponse(error);\n return c.json(body as never, status);\n }\n });\n\n app.get(`${basePath}/oauth/callback`, async (c) =>\n proxy.handleCallback(c.req.raw),\n );\n\n app.all(`${basePath}/oauth/consent`, async (c) =>\n proxy.handleConsent(c.req.raw),\n );\n\n return app;\n};\n","export class DiscoveryDocumentCache {\n public get size(): number {\n return this.#cache.size;\n }\n\n #cache: Map<\n string,\n {\n data: unknown;\n expiresAt: number;\n }\n > = new Map();\n\n #inFlight: Map<string, Promise<unknown>> = new Map();\n\n #timeoutMs: number;\n\n #ttl: number;\n\n /**\n * @param options - configuration options\n * @param options.timeoutMs - timeout in miliseconds for the upstream fetch\n * @param options.ttl - time-to-live in miliseconds\n */\n public constructor(options: { timeoutMs?: number; ttl?: number } = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10000; // default 10 seconds\n this.#ttl = options.ttl ?? 3600000; // default 1 hour\n }\n\n /**\n * @param url - optional URL to clear. if omitted, clears all cached documents.\n */\n public clear(url?: string): void {\n if (url) {\n this.#cache.delete(url);\n } else {\n this.#cache.clear();\n }\n }\n\n /**\n * fetches a discovery document from the given URL.\n * uses cached value if available and not expired.\n * coalesces concurrent requests for the same URL to prevent duplicate fetches.\n *\n * @param url - the discovery document URL (e.g., /.well-known/openid-configuration)\n * @returns the discovery document as a JSON object\n * @throws Error if the fetch fails or returns non-OK status\n */\n public async get(url: string): Promise<unknown> {\n const now = Date.now();\n const cached = this.#cache.get(url);\n\n // return cached value if still valid\n if (cached && cached.expiresAt > now) {\n return cached.data;\n }\n\n // check if there’s already an in-flight request for this URL\n const inFlight = this.#inFlight.get(url);\n\n if (inFlight) {\n return inFlight;\n }\n\n // create a new fetch promise and store it\n const fetchPromise = this.#fetchAndCache(url);\n\n this.#inFlight.set(url, fetchPromise);\n\n try {\n const data = await fetchPromise;\n return data;\n } finally {\n // clean up in-flight promise after completion\n // (success or failure)\n this.#inFlight.delete(url);\n }\n }\n\n /**\n * @param url - the URL to check\n * @returns true if the URL is cached and nott expired\n */\n public has(url: string): boolean {\n const cached = this.#cache.get(url);\n\n if (!cached) {\n return false;\n }\n\n const now = Date.now();\n\n if (cached.expiresAt <= now) {\n // expired, remove from cache\n this.#cache.delete(url);\n return false;\n }\n\n return true;\n }\n\n async #fetchAndCache(url: string): Promise<unknown> {\n // fetch fresh document, bounded by the configured timeout\n let res: Response;\n try {\n res = await fetch(url, {\n signal: AbortSignal.timeout(this.#timeoutMs),\n });\n } catch (error) {\n if (\n error instanceof Error &&\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n ) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: timed out after ${this.#timeoutMs}ms`,\n );\n }\n throw error;\n }\n\n if (!res.ok) {\n throw new Error(\n `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`,\n );\n }\n\n const data = await res.json();\n // calculate expiration time AFTER fetch completes\n const expiresAt = Date.now() + this.#ttl;\n\n // store in cache with expiration\n this.#cache.set(url, {\n data,\n expiresAt,\n });\n\n return data;\n }\n}\n","import { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A plain JSON Schema object descriptor.\n */\nexport type JsonSchemaObject = {\n [key: string]: unknown;\n $schema?: string;\n additionalProperties?: boolean;\n properties?: Record<string, unknown>;\n required?: string[];\n type: string;\n};\n\n/**\n * A Standard Schema that also carries the JSON Schema it was built from.\n *\n * `~standard.jsonSchema` is the Standard JSON Schema extension. Anything that\n * knows about it — including the `xsschema` conversion ViteMCP uses to build\n * `tools/list` — reads the schema straight off the object instead of trying to\n * derive one from a validation library it does not recognise.\n */\nexport interface JsonSchemaStandardSchema extends StandardSchemaV1 {\n readonly \"~standard\": {\n readonly jsonSchema: {\n readonly input: () => JsonSchemaObject;\n readonly output: () => JsonSchemaObject;\n };\n } & StandardSchemaV1.Props;\n}\n\ninterface AjvErrorObject {\n instancePath: string;\n keyword: string;\n message?: string;\n params?: Record<string, unknown>;\n}\n\ntype AjvValidateFunction = {\n errors?: AjvErrorObject[] | null;\n (data: unknown): boolean;\n};\n\n/**\n * Wraps a plain JSON Schema object for use as a tool's `parameters` or\n * `outputSchema`, without pulling in Zod or Valibot.\n *\n * Validation uses AJV, an optional peer dependency — install `ajv` (plus\n * `ajv-formats` for `format` keywords). It is imported on first validation, so\n * servers that never call it pay nothing.\n *\n * @example\n * ```ts\n * server.addTool({\n * name: \"greet\",\n * parameters: jsonSchemaAdapter({\n * type: \"object\",\n * properties: { name: { type: \"string\" } },\n * required: [\"name\"],\n * }),\n * execute: async ({ name }) => `Hello, ${name}!`,\n * });\n * ```\n */\nexport function jsonSchemaAdapter(\n schema: JsonSchemaObject,\n): JsonSchemaStandardSchema {\n // Compiling a schema makes AJV generate and evaluate JavaScript, so it has\n // to happen once rather than per call. The promise is memoised, not just the\n // result, so concurrent first calls share a single compilation.\n let compiled: Promise<AjvValidateFunction> | undefined;\n\n const getValidator = (): Promise<AjvValidateFunction> => {\n compiled ??= compileSchema(schema).catch((error: unknown) => {\n // Do not memoise a failure: a missing dependency should be reported on\n // every call, not swallowed after the first.\n compiled = undefined;\n throw error;\n });\n\n return compiled;\n };\n\n return {\n \"~standard\": {\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n validate: async (\n data: unknown,\n ): Promise<StandardSchemaV1.Result<unknown>> => {\n const validate = await getValidator();\n\n if (validate(data)) {\n return { value: data };\n }\n\n return { issues: (validate.errors ?? []).map(toIssue) };\n },\n vendor: \"json-schema\",\n version: 1,\n },\n };\n}\n\nasync function compileSchema(\n schema: JsonSchemaObject,\n): Promise<AjvValidateFunction> {\n let ajvModule;\n\n try {\n ajvModule = await import(\"ajv\");\n } catch {\n throw new Error(\n 'The \"ajv\" package is required to validate JSON Schema tool parameters. ' +\n \"Install it with: npm install ajv\",\n );\n }\n\n // ajv ships CommonJS, so depending on the loader the class arrives as the\n // module namespace, as `.default`, or as `.default.default`.\n const Ajv = unwrapDefault(unwrapDefault(ajvModule)) as unknown as new (\n options: Record<string, unknown>,\n ) => {\n compile: (schema: unknown) => AjvValidateFunction;\n };\n\n const ajv = new Ajv({ allErrors: true, strict: false });\n\n try {\n const formatsModule = await import(\"ajv-formats\");\n const addFormats = unwrapDefault(\n unwrapDefault(formatsModule),\n ) as unknown as (ajv: unknown) => void;\n\n addFormats(ajv);\n } catch {\n // ajv-formats is optional; `format` keywords are simply not enforced.\n }\n\n return ajv.compile(schema);\n}\n\nfunction toIssue(error: AjvErrorObject): StandardSchemaV1.Issue {\n const path = error.instancePath\n .split(\"/\")\n .filter(Boolean)\n // JSON Pointer escapes, per RFC 6901.\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"))\n .map((segment): number | string => {\n const index = Number(segment);\n return Number.isInteger(index) && segment !== \"\" ? index : segment;\n });\n\n // AJV reports a missing property against its parent object, with the name in\n // `params`. Appending it points the issue at the field the user has to fix.\n const missingProperty = error.params?.missingProperty;\n\n if (error.keyword === \"required\" && typeof missingProperty === \"string\") {\n path.push(missingProperty);\n }\n\n return {\n message: error.message || \"Validation error\",\n path,\n };\n}\n\nfunction unwrapDefault(value: unknown): unknown {\n return typeof value === \"object\" && value !== null && \"default\" in value\n ? (value as { default: unknown }).default\n : value;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,OAEf;AACP;AAAA,EACE;AAAA,OAEK;AAEP,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;AACrB,SAAS,YAAY;AACrB,OAAO,UAAU;AACjB,OAAO,WAAW;AAClB,SAAS,cAAc,aAAa;AACpC,SAAS,SAAAC,cAAa;AACtB,OAAO,sBAAsB;AAC7B,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,SAAS;;;AC7BlB,SAAS,YAAY;AAKd,IAAM,4BAA4B,OAAO;AAOhD,IAAM,gBAAgB,CAAC,UAAmB;AACxC,QAAM,MAAM;AACZ,SAAO;AAAA,IACL,MAAM,IAAI,SAAS,KAAK,EAAE,OAAO,kBAAkB;AAAA,IACnD,QAAS,IAAI,cAAc;AAAA,EAC7B;AACF;AAQA,IAAM,iBAAiB,OAAO,YAA6C;AACzE,QAAM,WAAW,QAAQ,QAAQ,IAAI,gBAAgB;AAErD,MAAI,YAAY,OAAO,QAAQ,IAAI,2BAA2B;AAC5D,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,QAAQ,MAAM;AACjB,QAAI;AACF,YAAM,OAAO,MAAM,QAAQ,KAAK;AAChC,aAAO,KAAK,SAAS,4BAA4B,OAAO;AAAA,IAC1D,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,QAAM,SAAS,QAAQ,KAAK,UAAU;AACtC,QAAM,SAAuB,CAAC;AAC9B,MAAI,OAAO;AAEX,MAAI;AACF,eAAS;AACP,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,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QAAQ;AAGd,QAAI,MAAM,eAAe,oBAAoB,MAAM,QAAQ,MAAM,OAAO,GAAG;AACzE,aAAO;AAAA,IACT;AAEA,QACE,MAAM,SAAS,UACf,MAAM,SAAS,WACf,MAAM,SAAS,WACf,MAAM,SAAS,cACf,MAAM,SAAS,iBACf;AACA,aAAO,EAAE,SAAS,CAAC,KAAK,EAAE;AAAA,IAC5B;AAIA,WAAO;AAAA,MACL,SAAS,CAAC,EAAE,MAAM,KAAK,UAAU,KAAK,GAAG,MAAM,OAAO,CAAC;AAAA,MACvD,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,OAAO,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE;AAC7D;","names":["Hono","fetch","fetch","ServerState","Hono"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vitemcp/server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"main": "./dist/ViteMCP.cjs",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "tsup",
|
|
7
|
-
"lint": "prettier --check . && eslint . && tsc --noEmit && jsr publish --dry-run",
|
|
7
|
+
"lint": "prettier --check . && eslint . && tsc --noEmit && knip && jsr publish --dry-run",
|
|
8
8
|
"test": "vitest run",
|
|
9
9
|
"format": "prettier --write . && eslint --fix .",
|
|
10
10
|
"test:coverage": "vitest run --coverage"
|
|
@@ -60,15 +60,11 @@
|
|
|
60
60
|
"./package.json": "./package.json"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@modelcontextprotocol/core": "^2.0.0",
|
|
64
|
-
"@modelcontextprotocol/node": "^2.0.0",
|
|
65
63
|
"@modelcontextprotocol/server": "^2.0.0",
|
|
66
64
|
"@standard-schema/spec": "^1.0.0",
|
|
67
65
|
"execa": "^9.6.1",
|
|
68
66
|
"file-type": "^21.1.1",
|
|
69
|
-
"fuse.js": "^7.1.0",
|
|
70
67
|
"hono": "^4.11.5",
|
|
71
|
-
"strict-event-emitter-types": "^2.0.0",
|
|
72
68
|
"undici": "^7.16.0",
|
|
73
69
|
"uri-templates": "^0.2.0",
|
|
74
70
|
"xsschema": "^0.4.3",
|
|
@@ -133,11 +129,10 @@
|
|
|
133
129
|
"eslint": "^9.39.1",
|
|
134
130
|
"eslint-config-prettier": "^10.1.8",
|
|
135
131
|
"eslint-plugin-perfectionist": "^4.15.1",
|
|
136
|
-
"eslint-plugin-prettier": "^5.5.4",
|
|
137
|
-
"eventsource-client": "^1.2.0",
|
|
138
132
|
"get-port-please": "^3.2.0",
|
|
139
133
|
"jiti": "^2.6.1",
|
|
140
134
|
"jsr": "^0.13.5",
|
|
135
|
+
"knip": "^6.31.0",
|
|
141
136
|
"prettier": "^3.7.4",
|
|
142
137
|
"semantic-release": "^25.0.2",
|
|
143
138
|
"tsup": "^8.5.1",
|