@mastra/fastify 0.0.0-agent-chat-ui-20260305212602
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/CHANGELOG.md +617 -0
- package/LICENSE.md +30 -0
- package/README.md +85 -0
- package/dist/index.cjs +796 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +794 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var busboy = require('@fastify/busboy');
|
|
4
|
+
var error = require('@mastra/server/handlers/error');
|
|
5
|
+
var serverAdapter = require('@mastra/server/server-adapter');
|
|
6
|
+
|
|
7
|
+
// src/index.ts
|
|
8
|
+
|
|
9
|
+
// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
|
|
10
|
+
var util;
|
|
11
|
+
(function(util2) {
|
|
12
|
+
util2.assertEqual = (_) => {
|
|
13
|
+
};
|
|
14
|
+
function assertIs(_arg) {
|
|
15
|
+
}
|
|
16
|
+
util2.assertIs = assertIs;
|
|
17
|
+
function assertNever(_x) {
|
|
18
|
+
throw new Error();
|
|
19
|
+
}
|
|
20
|
+
util2.assertNever = assertNever;
|
|
21
|
+
util2.arrayToEnum = (items) => {
|
|
22
|
+
const obj = {};
|
|
23
|
+
for (const item of items) {
|
|
24
|
+
obj[item] = item;
|
|
25
|
+
}
|
|
26
|
+
return obj;
|
|
27
|
+
};
|
|
28
|
+
util2.getValidEnumValues = (obj) => {
|
|
29
|
+
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
|
30
|
+
const filtered = {};
|
|
31
|
+
for (const k of validKeys) {
|
|
32
|
+
filtered[k] = obj[k];
|
|
33
|
+
}
|
|
34
|
+
return util2.objectValues(filtered);
|
|
35
|
+
};
|
|
36
|
+
util2.objectValues = (obj) => {
|
|
37
|
+
return util2.objectKeys(obj).map(function(e) {
|
|
38
|
+
return obj[e];
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
|
|
42
|
+
const keys = [];
|
|
43
|
+
for (const key in object) {
|
|
44
|
+
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
45
|
+
keys.push(key);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return keys;
|
|
49
|
+
};
|
|
50
|
+
util2.find = (arr, checker) => {
|
|
51
|
+
for (const item of arr) {
|
|
52
|
+
if (checker(item))
|
|
53
|
+
return item;
|
|
54
|
+
}
|
|
55
|
+
return void 0;
|
|
56
|
+
};
|
|
57
|
+
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
|
|
58
|
+
function joinValues(array, separator = " | ") {
|
|
59
|
+
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
|
|
60
|
+
}
|
|
61
|
+
util2.joinValues = joinValues;
|
|
62
|
+
util2.jsonStringifyReplacer = (_, value) => {
|
|
63
|
+
if (typeof value === "bigint") {
|
|
64
|
+
return value.toString();
|
|
65
|
+
}
|
|
66
|
+
return value;
|
|
67
|
+
};
|
|
68
|
+
})(util || (util = {}));
|
|
69
|
+
var objectUtil;
|
|
70
|
+
(function(objectUtil2) {
|
|
71
|
+
objectUtil2.mergeShapes = (first, second) => {
|
|
72
|
+
return {
|
|
73
|
+
...first,
|
|
74
|
+
...second
|
|
75
|
+
// second overwrites first
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
})(objectUtil || (objectUtil = {}));
|
|
79
|
+
util.arrayToEnum([
|
|
80
|
+
"string",
|
|
81
|
+
"nan",
|
|
82
|
+
"number",
|
|
83
|
+
"integer",
|
|
84
|
+
"float",
|
|
85
|
+
"boolean",
|
|
86
|
+
"date",
|
|
87
|
+
"bigint",
|
|
88
|
+
"symbol",
|
|
89
|
+
"function",
|
|
90
|
+
"undefined",
|
|
91
|
+
"null",
|
|
92
|
+
"array",
|
|
93
|
+
"object",
|
|
94
|
+
"unknown",
|
|
95
|
+
"promise",
|
|
96
|
+
"void",
|
|
97
|
+
"never",
|
|
98
|
+
"map",
|
|
99
|
+
"set"
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
|
|
103
|
+
util.arrayToEnum([
|
|
104
|
+
"invalid_type",
|
|
105
|
+
"invalid_literal",
|
|
106
|
+
"custom",
|
|
107
|
+
"invalid_union",
|
|
108
|
+
"invalid_union_discriminator",
|
|
109
|
+
"invalid_enum_value",
|
|
110
|
+
"unrecognized_keys",
|
|
111
|
+
"invalid_arguments",
|
|
112
|
+
"invalid_return_type",
|
|
113
|
+
"invalid_date",
|
|
114
|
+
"invalid_string",
|
|
115
|
+
"too_small",
|
|
116
|
+
"too_big",
|
|
117
|
+
"invalid_intersection_types",
|
|
118
|
+
"not_multiple_of",
|
|
119
|
+
"not_finite"
|
|
120
|
+
]);
|
|
121
|
+
var ZodError = class _ZodError extends Error {
|
|
122
|
+
get errors() {
|
|
123
|
+
return this.issues;
|
|
124
|
+
}
|
|
125
|
+
constructor(issues) {
|
|
126
|
+
super();
|
|
127
|
+
this.issues = [];
|
|
128
|
+
this.addIssue = (sub) => {
|
|
129
|
+
this.issues = [...this.issues, sub];
|
|
130
|
+
};
|
|
131
|
+
this.addIssues = (subs = []) => {
|
|
132
|
+
this.issues = [...this.issues, ...subs];
|
|
133
|
+
};
|
|
134
|
+
const actualProto = new.target.prototype;
|
|
135
|
+
if (Object.setPrototypeOf) {
|
|
136
|
+
Object.setPrototypeOf(this, actualProto);
|
|
137
|
+
} else {
|
|
138
|
+
this.__proto__ = actualProto;
|
|
139
|
+
}
|
|
140
|
+
this.name = "ZodError";
|
|
141
|
+
this.issues = issues;
|
|
142
|
+
}
|
|
143
|
+
format(_mapper) {
|
|
144
|
+
const mapper = _mapper || function(issue) {
|
|
145
|
+
return issue.message;
|
|
146
|
+
};
|
|
147
|
+
const fieldErrors = { _errors: [] };
|
|
148
|
+
const processError = (error) => {
|
|
149
|
+
for (const issue of error.issues) {
|
|
150
|
+
if (issue.code === "invalid_union") {
|
|
151
|
+
issue.unionErrors.map(processError);
|
|
152
|
+
} else if (issue.code === "invalid_return_type") {
|
|
153
|
+
processError(issue.returnTypeError);
|
|
154
|
+
} else if (issue.code === "invalid_arguments") {
|
|
155
|
+
processError(issue.argumentsError);
|
|
156
|
+
} else if (issue.path.length === 0) {
|
|
157
|
+
fieldErrors._errors.push(mapper(issue));
|
|
158
|
+
} else {
|
|
159
|
+
let curr = fieldErrors;
|
|
160
|
+
let i = 0;
|
|
161
|
+
while (i < issue.path.length) {
|
|
162
|
+
const el = issue.path[i];
|
|
163
|
+
const terminal = i === issue.path.length - 1;
|
|
164
|
+
if (!terminal) {
|
|
165
|
+
curr[el] = curr[el] || { _errors: [] };
|
|
166
|
+
} else {
|
|
167
|
+
curr[el] = curr[el] || { _errors: [] };
|
|
168
|
+
curr[el]._errors.push(mapper(issue));
|
|
169
|
+
}
|
|
170
|
+
curr = curr[el];
|
|
171
|
+
i++;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
processError(this);
|
|
177
|
+
return fieldErrors;
|
|
178
|
+
}
|
|
179
|
+
static assert(value) {
|
|
180
|
+
if (!(value instanceof _ZodError)) {
|
|
181
|
+
throw new Error(`Not a ZodError: ${value}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
toString() {
|
|
185
|
+
return this.message;
|
|
186
|
+
}
|
|
187
|
+
get message() {
|
|
188
|
+
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
|
|
189
|
+
}
|
|
190
|
+
get isEmpty() {
|
|
191
|
+
return this.issues.length === 0;
|
|
192
|
+
}
|
|
193
|
+
flatten(mapper = (issue) => issue.message) {
|
|
194
|
+
const fieldErrors = {};
|
|
195
|
+
const formErrors = [];
|
|
196
|
+
for (const sub of this.issues) {
|
|
197
|
+
if (sub.path.length > 0) {
|
|
198
|
+
const firstEl = sub.path[0];
|
|
199
|
+
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
|
|
200
|
+
fieldErrors[firstEl].push(mapper(sub));
|
|
201
|
+
} else {
|
|
202
|
+
formErrors.push(mapper(sub));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { formErrors, fieldErrors };
|
|
206
|
+
}
|
|
207
|
+
get formErrors() {
|
|
208
|
+
return this.flatten();
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
ZodError.create = (issues) => {
|
|
212
|
+
const error = new ZodError(issues);
|
|
213
|
+
return error;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// src/index.ts
|
|
217
|
+
var _hasPermissionPromise;
|
|
218
|
+
function loadHasPermission() {
|
|
219
|
+
if (!_hasPermissionPromise) {
|
|
220
|
+
_hasPermissionPromise = import('@mastra/core/auth/ee').then((m) => m.hasPermission).catch(() => {
|
|
221
|
+
console.error(
|
|
222
|
+
"[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest"
|
|
223
|
+
);
|
|
224
|
+
return void 0;
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return _hasPermissionPromise;
|
|
228
|
+
}
|
|
229
|
+
function toWebRequest(request) {
|
|
230
|
+
const protocol = request.protocol || "http";
|
|
231
|
+
const host = request.headers.host || "localhost";
|
|
232
|
+
const url = `${protocol}://${host}${request.url}`;
|
|
233
|
+
const headers = new Headers();
|
|
234
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
235
|
+
if (value) {
|
|
236
|
+
if (Array.isArray(value)) {
|
|
237
|
+
value.forEach((v) => headers.append(key, v));
|
|
238
|
+
} else {
|
|
239
|
+
headers.set(key, value);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return new globalThis.Request(url, {
|
|
244
|
+
method: request.method,
|
|
245
|
+
headers
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
var MastraServer = class extends serverAdapter.MastraServer {
|
|
249
|
+
createContextMiddleware() {
|
|
250
|
+
return async (request, _reply) => {
|
|
251
|
+
let bodyRequestContext;
|
|
252
|
+
let paramsRequestContext;
|
|
253
|
+
if (request.method === "POST" || request.method === "PUT") {
|
|
254
|
+
const contentType = request.headers["content-type"];
|
|
255
|
+
if (contentType?.includes("application/json") && request.body) {
|
|
256
|
+
const body = request.body;
|
|
257
|
+
if (body.requestContext) {
|
|
258
|
+
bodyRequestContext = body.requestContext;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (request.method === "GET") {
|
|
263
|
+
try {
|
|
264
|
+
const query = request.query;
|
|
265
|
+
const encodedRequestContext = query.requestContext;
|
|
266
|
+
if (typeof encodedRequestContext === "string") {
|
|
267
|
+
try {
|
|
268
|
+
paramsRequestContext = JSON.parse(encodedRequestContext);
|
|
269
|
+
} catch {
|
|
270
|
+
try {
|
|
271
|
+
const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
|
|
272
|
+
paramsRequestContext = JSON.parse(json);
|
|
273
|
+
} catch {
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
} catch {
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });
|
|
281
|
+
request.requestContext = requestContext;
|
|
282
|
+
request.mastra = this.mastra;
|
|
283
|
+
request.tools = this.tools || {};
|
|
284
|
+
if (this.taskStore) {
|
|
285
|
+
request.taskStore = this.taskStore;
|
|
286
|
+
}
|
|
287
|
+
request.customRouteAuthConfig = this.customRouteAuthConfig;
|
|
288
|
+
const controller = new AbortController();
|
|
289
|
+
request.raw.on("close", () => {
|
|
290
|
+
if (!request.raw.complete) {
|
|
291
|
+
controller.abort();
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
request.abortSignal = controller.signal;
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
async stream(route, reply, result) {
|
|
298
|
+
const rawHeaders = reply.getHeaders();
|
|
299
|
+
const existingHeaders = {};
|
|
300
|
+
for (const [key, value] of Object.entries(rawHeaders)) {
|
|
301
|
+
if (value === void 0) continue;
|
|
302
|
+
const lowerKey = key.toLowerCase();
|
|
303
|
+
if (lowerKey === "content-length" || lowerKey === "transfer-encoding") continue;
|
|
304
|
+
existingHeaders[key] = value;
|
|
305
|
+
}
|
|
306
|
+
reply.hijack();
|
|
307
|
+
const streamFormat = route.streamFormat || "stream";
|
|
308
|
+
const sseHeaders = streamFormat === "sse" ? {
|
|
309
|
+
"Content-Type": "text/event-stream",
|
|
310
|
+
"Cache-Control": "no-cache",
|
|
311
|
+
Connection: "keep-alive",
|
|
312
|
+
"X-Accel-Buffering": "no"
|
|
313
|
+
} : {
|
|
314
|
+
"Content-Type": "text/plain"
|
|
315
|
+
};
|
|
316
|
+
reply.raw.writeHead(200, {
|
|
317
|
+
...existingHeaders,
|
|
318
|
+
...sseHeaders,
|
|
319
|
+
"Transfer-Encoding": "chunked"
|
|
320
|
+
});
|
|
321
|
+
const readableStream = result instanceof ReadableStream ? result : result.fullStream;
|
|
322
|
+
const reader = readableStream.getReader();
|
|
323
|
+
reply.raw.on("close", () => {
|
|
324
|
+
void reader.cancel("request aborted");
|
|
325
|
+
});
|
|
326
|
+
try {
|
|
327
|
+
while (true) {
|
|
328
|
+
const { done, value } = await reader.read();
|
|
329
|
+
if (done) break;
|
|
330
|
+
if (value) {
|
|
331
|
+
const shouldRedact = this.streamOptions?.redact ?? true;
|
|
332
|
+
const outputValue = shouldRedact ? serverAdapter.redactStreamChunk(value) : value;
|
|
333
|
+
if (streamFormat === "sse") {
|
|
334
|
+
reply.raw.write(`data: ${JSON.stringify(outputValue)}
|
|
335
|
+
|
|
336
|
+
`);
|
|
337
|
+
} else {
|
|
338
|
+
reply.raw.write(JSON.stringify(outputValue) + "");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
} catch (error) {
|
|
343
|
+
this.mastra.getLogger()?.error("Error in stream processing", {
|
|
344
|
+
error: error instanceof Error ? { message: error.message, stack: error.stack } : error
|
|
345
|
+
});
|
|
346
|
+
} finally {
|
|
347
|
+
reply.raw.end();
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
async getParams(route, request) {
|
|
351
|
+
const urlParams = request.params || {};
|
|
352
|
+
const queryParams = serverAdapter.normalizeQueryParams(request.query || {});
|
|
353
|
+
let body;
|
|
354
|
+
let bodyParseError;
|
|
355
|
+
if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
|
|
356
|
+
const contentType = request.headers["content-type"] || "";
|
|
357
|
+
if (contentType.includes("multipart/form-data")) {
|
|
358
|
+
try {
|
|
359
|
+
const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
|
|
360
|
+
body = await this.parseMultipartFormData(request, maxFileSize);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
this.mastra.getLogger()?.error("Failed to parse multipart form data", {
|
|
363
|
+
error: error instanceof Error ? { message: error.message, stack: error.stack } : error
|
|
364
|
+
});
|
|
365
|
+
if (error instanceof Error && error.message.toLowerCase().includes("size")) {
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
bodyParseError = {
|
|
369
|
+
message: error instanceof Error ? error.message : "Failed to parse multipart form data"
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
} else {
|
|
373
|
+
body = request.body;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return { urlParams, queryParams, body, bodyParseError };
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Parse multipart/form-data using @fastify/busboy.
|
|
380
|
+
* Converts file uploads to Buffers and parses JSON field values.
|
|
381
|
+
*
|
|
382
|
+
* @param request - The Fastify request object
|
|
383
|
+
* @param maxFileSize - Optional maximum file size in bytes
|
|
384
|
+
*/
|
|
385
|
+
parseMultipartFormData(request, maxFileSize) {
|
|
386
|
+
return new Promise((resolve, reject) => {
|
|
387
|
+
const result = {};
|
|
388
|
+
const busboy$1 = new busboy.Busboy({
|
|
389
|
+
headers: {
|
|
390
|
+
"content-type": request.headers["content-type"]
|
|
391
|
+
},
|
|
392
|
+
limits: maxFileSize ? { fileSize: maxFileSize } : void 0
|
|
393
|
+
});
|
|
394
|
+
busboy$1.on("file", (fieldname, file) => {
|
|
395
|
+
const chunks = [];
|
|
396
|
+
let limitExceeded = false;
|
|
397
|
+
file.on("data", (chunk) => {
|
|
398
|
+
chunks.push(chunk);
|
|
399
|
+
});
|
|
400
|
+
file.on("limit", () => {
|
|
401
|
+
limitExceeded = true;
|
|
402
|
+
reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
|
|
403
|
+
});
|
|
404
|
+
file.on("end", () => {
|
|
405
|
+
if (!limitExceeded) {
|
|
406
|
+
result[fieldname] = Buffer.concat(chunks);
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
busboy$1.on("field", (fieldname, value) => {
|
|
411
|
+
try {
|
|
412
|
+
result[fieldname] = JSON.parse(value);
|
|
413
|
+
} catch {
|
|
414
|
+
result[fieldname] = value;
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
busboy$1.on("finish", () => {
|
|
418
|
+
resolve(result);
|
|
419
|
+
});
|
|
420
|
+
busboy$1.on("error", (error) => {
|
|
421
|
+
reject(error);
|
|
422
|
+
});
|
|
423
|
+
request.raw.pipe(busboy$1);
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
async sendResponse(route, reply, result, request, prefix) {
|
|
427
|
+
const resolvedPrefix = prefix ?? this.prefix ?? "";
|
|
428
|
+
if (route.responseType === "json") {
|
|
429
|
+
await reply.send(result);
|
|
430
|
+
} else if (route.responseType === "stream") {
|
|
431
|
+
await this.stream(route, reply, result);
|
|
432
|
+
} else if (route.responseType === "datastream-response") {
|
|
433
|
+
const fetchResponse = result;
|
|
434
|
+
fetchResponse.headers.forEach((value, key) => reply.header(key, value));
|
|
435
|
+
reply.status(fetchResponse.status);
|
|
436
|
+
if (fetchResponse.body) {
|
|
437
|
+
const reader = fetchResponse.body.getReader();
|
|
438
|
+
try {
|
|
439
|
+
while (true) {
|
|
440
|
+
const { done, value } = await reader.read();
|
|
441
|
+
if (done) break;
|
|
442
|
+
reply.raw.write(value);
|
|
443
|
+
}
|
|
444
|
+
} finally {
|
|
445
|
+
reply.raw.end();
|
|
446
|
+
}
|
|
447
|
+
} else {
|
|
448
|
+
reply.raw.end();
|
|
449
|
+
}
|
|
450
|
+
} else if (route.responseType === "mcp-http") {
|
|
451
|
+
if (!request) {
|
|
452
|
+
await reply.status(500).send({ error: "Request object required for MCP transport" });
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const { server, httpPath, mcpOptions: routeMcpOptions } = result;
|
|
456
|
+
try {
|
|
457
|
+
reply.hijack();
|
|
458
|
+
const rawReq = request.raw;
|
|
459
|
+
if (request.body !== void 0) {
|
|
460
|
+
rawReq.body = request.body;
|
|
461
|
+
}
|
|
462
|
+
const options = { ...this.mcpOptions, ...routeMcpOptions };
|
|
463
|
+
await server.startHTTP({
|
|
464
|
+
url: new URL(request.url, `http://${request.headers.host}`),
|
|
465
|
+
httpPath: `${resolvedPrefix}${httpPath}`,
|
|
466
|
+
req: rawReq,
|
|
467
|
+
res: reply.raw,
|
|
468
|
+
options: Object.keys(options).length > 0 ? options : void 0
|
|
469
|
+
});
|
|
470
|
+
} catch {
|
|
471
|
+
if (!reply.raw.headersSent) {
|
|
472
|
+
reply.raw.writeHead(500, { "Content-Type": "application/json" });
|
|
473
|
+
reply.raw.end(
|
|
474
|
+
JSON.stringify({
|
|
475
|
+
jsonrpc: "2.0",
|
|
476
|
+
error: { code: -32603, message: "Internal server error" },
|
|
477
|
+
id: null
|
|
478
|
+
})
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
} else if (route.responseType === "mcp-sse") {
|
|
483
|
+
if (!request) {
|
|
484
|
+
await reply.status(500).send({ error: "Request object required for MCP transport" });
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
const { server, ssePath, messagePath } = result;
|
|
488
|
+
try {
|
|
489
|
+
reply.hijack();
|
|
490
|
+
const rawReq = request.raw;
|
|
491
|
+
if (request.body !== void 0) {
|
|
492
|
+
rawReq.body = request.body;
|
|
493
|
+
}
|
|
494
|
+
await server.startSSE({
|
|
495
|
+
url: new URL(request.url, `http://${request.headers.host}`),
|
|
496
|
+
ssePath: `${resolvedPrefix}${ssePath}`,
|
|
497
|
+
messagePath: `${resolvedPrefix}${messagePath}`,
|
|
498
|
+
req: rawReq,
|
|
499
|
+
res: reply.raw
|
|
500
|
+
});
|
|
501
|
+
} catch {
|
|
502
|
+
if (!reply.raw.headersSent) {
|
|
503
|
+
reply.raw.writeHead(500, { "Content-Type": "application/json" });
|
|
504
|
+
reply.raw.end(JSON.stringify({ error: "Error handling MCP SSE request" }));
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
reply.status(500);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
async registerRoute(app, route, { prefix: prefixParam } = {}) {
|
|
512
|
+
const prefix = prefixParam ?? this.prefix ?? "";
|
|
513
|
+
const fullPath = `${prefix}${route.path}`;
|
|
514
|
+
const fastifyPath = fullPath;
|
|
515
|
+
const handler = async (request, reply) => {
|
|
516
|
+
const authError = await this.checkRouteAuth(route, {
|
|
517
|
+
path: String(request.url.split("?")[0] || "/"),
|
|
518
|
+
method: String(request.method || "GET"),
|
|
519
|
+
getHeader: (name) => request.headers[name.toLowerCase()],
|
|
520
|
+
getQuery: (name) => request.query[name],
|
|
521
|
+
requestContext: request.requestContext,
|
|
522
|
+
request: toWebRequest(request),
|
|
523
|
+
buildAuthorizeContext: () => toWebRequest(request)
|
|
524
|
+
});
|
|
525
|
+
if (authError) {
|
|
526
|
+
return reply.status(authError.status).send({ error: authError.error });
|
|
527
|
+
}
|
|
528
|
+
const params = await this.getParams(route, request);
|
|
529
|
+
if (params.bodyParseError) {
|
|
530
|
+
return reply.status(400).send({
|
|
531
|
+
error: "Invalid request body",
|
|
532
|
+
issues: [{ field: "body", message: params.bodyParseError.message }]
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
if (params.queryParams) {
|
|
536
|
+
try {
|
|
537
|
+
params.queryParams = await this.parseQueryParams(route, params.queryParams);
|
|
538
|
+
} catch (error$1) {
|
|
539
|
+
this.mastra.getLogger()?.error("Error parsing query params", {
|
|
540
|
+
error: error$1 instanceof Error ? { message: error$1.message, stack: error$1.stack } : error$1
|
|
541
|
+
});
|
|
542
|
+
if (error$1 instanceof ZodError) {
|
|
543
|
+
return reply.status(400).send(error.formatZodError(error$1, "query parameters"));
|
|
544
|
+
}
|
|
545
|
+
return reply.status(400).send({
|
|
546
|
+
error: "Invalid query parameters",
|
|
547
|
+
issues: [{ field: "unknown", message: error$1 instanceof Error ? error$1.message : "Unknown error" }]
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
if (params.body) {
|
|
552
|
+
try {
|
|
553
|
+
params.body = await this.parseBody(route, params.body);
|
|
554
|
+
} catch (error$1) {
|
|
555
|
+
this.mastra.getLogger()?.error("Error parsing body", {
|
|
556
|
+
error: error$1 instanceof Error ? { message: error$1.message, stack: error$1.stack } : error$1
|
|
557
|
+
});
|
|
558
|
+
if (error$1 instanceof ZodError) {
|
|
559
|
+
return reply.status(400).send(error.formatZodError(error$1, "request body"));
|
|
560
|
+
}
|
|
561
|
+
return reply.status(400).send({
|
|
562
|
+
error: "Invalid request body",
|
|
563
|
+
issues: [{ field: "unknown", message: error$1 instanceof Error ? error$1.message : "Unknown error" }]
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (params.urlParams) {
|
|
568
|
+
try {
|
|
569
|
+
params.urlParams = await this.parsePathParams(route, params.urlParams);
|
|
570
|
+
} catch (error$1) {
|
|
571
|
+
this.mastra.getLogger()?.error("Error parsing path params", {
|
|
572
|
+
error: error$1 instanceof Error ? { message: error$1.message, stack: error$1.stack } : error$1
|
|
573
|
+
});
|
|
574
|
+
if (error$1 instanceof ZodError) {
|
|
575
|
+
return reply.status(400).send(error.formatZodError(error$1, "path parameters"));
|
|
576
|
+
}
|
|
577
|
+
return reply.status(400).send({
|
|
578
|
+
error: "Invalid path parameters",
|
|
579
|
+
issues: [{ field: "unknown", message: error$1 instanceof Error ? error$1.message : "Unknown error" }]
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const handlerParams = {
|
|
584
|
+
...params.urlParams,
|
|
585
|
+
...params.queryParams,
|
|
586
|
+
...typeof params.body === "object" ? params.body : {},
|
|
587
|
+
requestContext: request.requestContext,
|
|
588
|
+
mastra: this.mastra,
|
|
589
|
+
tools: request.tools,
|
|
590
|
+
taskStore: request.taskStore,
|
|
591
|
+
abortSignal: request.abortSignal,
|
|
592
|
+
routePrefix: prefix
|
|
593
|
+
};
|
|
594
|
+
const authConfig = this.mastra.getServer()?.auth;
|
|
595
|
+
if (authConfig) {
|
|
596
|
+
const hasPermission = await loadHasPermission();
|
|
597
|
+
if (hasPermission) {
|
|
598
|
+
const userPermissions = request.requestContext.get("userPermissions");
|
|
599
|
+
const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
|
|
600
|
+
if (permissionError) {
|
|
601
|
+
return reply.status(permissionError.status).send({
|
|
602
|
+
error: permissionError.error,
|
|
603
|
+
message: permissionError.message
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
const result = await route.handler(handlerParams);
|
|
610
|
+
await this.sendResponse(route, reply, result, request, prefix);
|
|
611
|
+
} catch (error) {
|
|
612
|
+
this.mastra.getLogger()?.error("Error calling handler", {
|
|
613
|
+
error: error instanceof Error ? { message: error.message, stack: error.stack } : error,
|
|
614
|
+
path: route.path,
|
|
615
|
+
method: route.method
|
|
616
|
+
});
|
|
617
|
+
let status = 500;
|
|
618
|
+
if (error && typeof error === "object") {
|
|
619
|
+
if ("status" in error) {
|
|
620
|
+
status = error.status;
|
|
621
|
+
} else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
|
|
622
|
+
status = error.details.status;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
await reply.status(status).send({ error: error instanceof Error ? error.message : "Unknown error" });
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
const shouldApplyBodyLimit = this.bodyLimitOptions && ["POST", "PUT", "PATCH"].includes(route.method.toUpperCase());
|
|
629
|
+
const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
|
|
630
|
+
const config = shouldApplyBodyLimit && maxSize ? { bodyLimit: maxSize } : void 0;
|
|
631
|
+
if (route.method.toUpperCase() === "ALL") {
|
|
632
|
+
const methods = ["GET", "POST", "PUT", "DELETE", "PATCH"];
|
|
633
|
+
for (const method of methods) {
|
|
634
|
+
try {
|
|
635
|
+
app.route({
|
|
636
|
+
method,
|
|
637
|
+
url: fastifyPath,
|
|
638
|
+
handler,
|
|
639
|
+
config
|
|
640
|
+
});
|
|
641
|
+
} catch (err) {
|
|
642
|
+
if (err instanceof Error && err.message.includes("already declared")) {
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
throw err;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
} else {
|
|
649
|
+
app.route({
|
|
650
|
+
method: route.method,
|
|
651
|
+
url: fastifyPath,
|
|
652
|
+
handler,
|
|
653
|
+
config
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
async registerCustomApiRoutes() {
|
|
658
|
+
if (!await this.buildCustomRouteHandler()) return;
|
|
659
|
+
const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];
|
|
660
|
+
for (const route of routes) {
|
|
661
|
+
const serverRoute = {
|
|
662
|
+
method: route.method,
|
|
663
|
+
path: route.path,
|
|
664
|
+
responseType: "json",
|
|
665
|
+
handler: async () => {
|
|
666
|
+
},
|
|
667
|
+
requiresAuth: route.requiresAuth
|
|
668
|
+
};
|
|
669
|
+
const fastifyHandler = async (request, reply) => {
|
|
670
|
+
const authError = await this.checkRouteAuth(serverRoute, {
|
|
671
|
+
path: String(request.url.split("?")[0] || "/"),
|
|
672
|
+
method: String(request.method || "GET"),
|
|
673
|
+
getHeader: (name) => request.headers[name.toLowerCase()],
|
|
674
|
+
getQuery: (name) => request.query[name],
|
|
675
|
+
requestContext: request.requestContext,
|
|
676
|
+
request: toWebRequest(request),
|
|
677
|
+
buildAuthorizeContext: () => toWebRequest(request)
|
|
678
|
+
});
|
|
679
|
+
if (authError) {
|
|
680
|
+
return reply.status(authError.status).send({ error: authError.error });
|
|
681
|
+
}
|
|
682
|
+
const authConfig = this.mastra.getServer()?.auth;
|
|
683
|
+
if (authConfig) {
|
|
684
|
+
let hasPermission;
|
|
685
|
+
try {
|
|
686
|
+
({ hasPermission } = await import('@mastra/core/auth/ee'));
|
|
687
|
+
} catch {
|
|
688
|
+
console.error(
|
|
689
|
+
"[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest"
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
if (hasPermission) {
|
|
693
|
+
const userPermissions = request.requestContext.get("userPermissions");
|
|
694
|
+
const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
|
|
695
|
+
if (permissionError) {
|
|
696
|
+
return reply.status(permissionError.status).send({
|
|
697
|
+
error: permissionError.error,
|
|
698
|
+
message: permissionError.message
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
const response = await this.handleCustomRouteRequest(
|
|
704
|
+
`http://${request.headers.host}${request.url}`,
|
|
705
|
+
request.method,
|
|
706
|
+
request.headers,
|
|
707
|
+
request.body,
|
|
708
|
+
request.requestContext
|
|
709
|
+
);
|
|
710
|
+
if (!response) {
|
|
711
|
+
reply.status(404).send({ error: "Not Found" });
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
reply.hijack();
|
|
715
|
+
await this.writeCustomRouteResponse(response, reply.raw);
|
|
716
|
+
};
|
|
717
|
+
if (route.method === "ALL") {
|
|
718
|
+
const methods = ["GET", "POST", "PUT", "DELETE", "PATCH"];
|
|
719
|
+
for (const method of methods) {
|
|
720
|
+
this.app.route({ method, url: route.path, handler: fastifyHandler });
|
|
721
|
+
}
|
|
722
|
+
} else {
|
|
723
|
+
this.app.route({
|
|
724
|
+
method: route.method,
|
|
725
|
+
url: route.path,
|
|
726
|
+
handler: fastifyHandler
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
registerContextMiddleware() {
|
|
732
|
+
this.app.removeContentTypeParser("application/json");
|
|
733
|
+
this.app.addContentTypeParser("application/json", { parseAs: "string" }, (_request, body, done) => {
|
|
734
|
+
try {
|
|
735
|
+
if (!body || typeof body === "string" && body.trim() === "") {
|
|
736
|
+
done(null, void 0);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const parsed = JSON.parse(body);
|
|
740
|
+
done(null, parsed);
|
|
741
|
+
} catch (err) {
|
|
742
|
+
done(err, void 0);
|
|
743
|
+
}
|
|
744
|
+
});
|
|
745
|
+
this.app.addContentTypeParser("multipart/form-data", (_request, _payload, done) => {
|
|
746
|
+
done(null, void 0);
|
|
747
|
+
});
|
|
748
|
+
this.app.addHook("preHandler", this.createContextMiddleware());
|
|
749
|
+
}
|
|
750
|
+
registerAuthMiddleware() {
|
|
751
|
+
}
|
|
752
|
+
registerHttpLoggingMiddleware() {
|
|
753
|
+
if (!this.httpLoggingConfig?.enabled) {
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
this.app.addHook("onRequest", async (request, reply) => {
|
|
757
|
+
const urlPath = request.url.split("?")[0];
|
|
758
|
+
if (!this.shouldLogRequest(urlPath)) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
const start = Date.now();
|
|
762
|
+
const method = request.method;
|
|
763
|
+
const path = urlPath;
|
|
764
|
+
reply.raw.once("finish", () => {
|
|
765
|
+
const duration = Date.now() - start;
|
|
766
|
+
const status = reply.statusCode;
|
|
767
|
+
const level = this.httpLoggingConfig?.level || "info";
|
|
768
|
+
const logData = {
|
|
769
|
+
method,
|
|
770
|
+
path,
|
|
771
|
+
status,
|
|
772
|
+
duration: `${duration}ms`
|
|
773
|
+
};
|
|
774
|
+
if (this.httpLoggingConfig?.includeQueryParams) {
|
|
775
|
+
logData.query = request.query;
|
|
776
|
+
}
|
|
777
|
+
if (this.httpLoggingConfig?.includeHeaders) {
|
|
778
|
+
const headers = { ...request.headers };
|
|
779
|
+
const redactHeaders = this.httpLoggingConfig.redactHeaders || [];
|
|
780
|
+
redactHeaders.forEach((h) => {
|
|
781
|
+
const key = h.toLowerCase();
|
|
782
|
+
if (headers[key] !== void 0) {
|
|
783
|
+
headers[key] = "[REDACTED]";
|
|
784
|
+
}
|
|
785
|
+
});
|
|
786
|
+
logData.headers = headers;
|
|
787
|
+
}
|
|
788
|
+
this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);
|
|
789
|
+
});
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
exports.MastraServer = MastraServer;
|
|
795
|
+
//# sourceMappingURL=index.cjs.map
|
|
796
|
+
//# sourceMappingURL=index.cjs.map
|