@mcpjam/inspector 0.9.30 → 0.9.40

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.
@@ -1,5 +1,6 @@
1
1
  // index.ts
2
2
  import { serve } from "@hono/node-server";
3
+ import dotenv from "dotenv";
3
4
  import fixPath from "fix-path";
4
5
  import { Hono as Hono13 } from "hono";
5
6
  import { cors } from "hono/cors";
@@ -185,7 +186,7 @@ var servers_default = servers;
185
186
 
186
187
  // routes/mcp/tools.ts
187
188
  import { Hono as Hono3 } from "hono";
188
- import { zodToJsonSchema } from "zod-to-json-schema";
189
+ import { zodToJsonSchema } from "@alcyone-labs/zod-to-json-schema";
189
190
  var tools = new Hono3();
190
191
  var activeExecution = null;
191
192
  function nowIso() {
@@ -212,17 +213,17 @@ tools.post("/list", async (c) => {
212
213
  }
213
214
  const flattenedTools = await mcp2.getToolsetsForServer(serverId);
214
215
  const toolsWithJsonSchema = {};
215
- for (const [name17, tool] of Object.entries(flattenedTools)) {
216
- let inputSchema = tool.inputSchema;
216
+ for (const [name, tool2] of Object.entries(flattenedTools)) {
217
+ let inputSchema = tool2.inputSchema;
217
218
  try {
218
219
  inputSchema = zodToJsonSchema(inputSchema);
219
220
  } catch {
220
221
  }
221
- toolsWithJsonSchema[name17] = {
222
- name: name17,
223
- description: tool.description,
222
+ toolsWithJsonSchema[name] = {
223
+ name,
224
+ description: tool2.description,
224
225
  inputSchema,
225
- outputSchema: tool.outputSchema
226
+ outputSchema: tool2.outputSchema
226
227
  };
227
228
  }
228
229
  return c.json({ tools: toolsWithJsonSchema });
@@ -465,11 +466,11 @@ prompts.post("/list", async (c) => {
465
466
  });
466
467
  prompts.post("/get", async (c) => {
467
468
  try {
468
- const { serverId, name: name17, args } = await c.req.json();
469
+ const { serverId, name, args } = await c.req.json();
469
470
  if (!serverId) {
470
471
  return c.json({ success: false, error: "serverId is required" }, 400);
471
472
  }
472
- if (!name17) {
473
+ if (!name) {
473
474
  return c.json(
474
475
  {
475
476
  success: false,
@@ -480,7 +481,7 @@ prompts.post("/get", async (c) => {
480
481
  }
481
482
  const mcpJamClientManager2 = c.mcpJamClientManager;
482
483
  const content = await mcpJamClientManager2.getPrompt(
483
- name17,
484
+ name,
484
485
  serverId,
485
486
  args || {}
486
487
  );
@@ -500,7 +501,7 @@ var prompts_default = prompts;
500
501
 
501
502
  // routes/mcp/chat.ts
502
503
  import { Hono as Hono6 } from "hono";
503
- import { Agent } from "@mastra/core/agent";
504
+ import { streamText } from "ai";
504
505
  import { TextEncoder as TextEncoder2 } from "util";
505
506
 
506
507
  // ../client/src/lib/chat-utils.ts
@@ -520,2630 +521,319 @@ function getDefaultTemperatureByProvider(provider) {
520
521
  }
521
522
  }
522
523
 
523
- // node_modules/ai-v5/node_modules/@ai-sdk/provider/dist/index.mjs
524
- var marker = "vercel.ai.error";
525
- var symbol = Symbol.for(marker);
526
- var _a;
527
- var _AISDKError = class _AISDKError2 extends Error {
528
- /**
529
- * Creates an AI SDK Error.
530
- *
531
- * @param {Object} params - The parameters for creating the error.
532
- * @param {string} params.name - The name of the error.
533
- * @param {string} params.message - The error message.
534
- * @param {unknown} [params.cause] - The underlying cause of the error.
535
- */
536
- constructor({
537
- name: name143,
538
- message,
539
- cause
540
- }) {
541
- super(message);
542
- this[_a] = true;
543
- this.name = name143;
544
- this.cause = cause;
545
- }
546
- /**
547
- * Checks if the given error is an AI SDK Error.
548
- * @param {unknown} error - The error to check.
549
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
550
- */
551
- static isInstance(error) {
552
- return _AISDKError2.hasMarker(error, marker);
553
- }
554
- static hasMarker(error, marker153) {
555
- const markerSymbol = Symbol.for(marker153);
556
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
557
- }
558
- };
559
- _a = symbol;
560
- var AISDKError = _AISDKError;
561
- var name = "AI_APICallError";
562
- var marker2 = `vercel.ai.error.${name}`;
563
- var symbol2 = Symbol.for(marker2);
564
- var _a2;
565
- _a2 = symbol2;
566
- var name2 = "AI_EmptyResponseBodyError";
567
- var marker3 = `vercel.ai.error.${name2}`;
568
- var symbol3 = Symbol.for(marker3);
569
- var _a3;
570
- _a3 = symbol3;
571
- function getErrorMessage(error) {
572
- if (error == null) {
573
- return "unknown error";
574
- }
575
- if (typeof error === "string") {
576
- return error;
577
- }
578
- if (error instanceof Error) {
579
- return error.message;
580
- }
581
- return JSON.stringify(error);
582
- }
583
- var name3 = "AI_InvalidArgumentError";
584
- var marker4 = `vercel.ai.error.${name3}`;
585
- var symbol4 = Symbol.for(marker4);
586
- var _a4;
587
- var InvalidArgumentError = class extends AISDKError {
588
- constructor({
589
- message,
590
- cause,
591
- argument
592
- }) {
593
- super({ name: name3, message, cause });
594
- this[_a4] = true;
595
- this.argument = argument;
596
- }
597
- static isInstance(error) {
598
- return AISDKError.hasMarker(error, marker4);
599
- }
600
- };
601
- _a4 = symbol4;
602
- var name4 = "AI_InvalidPromptError";
603
- var marker5 = `vercel.ai.error.${name4}`;
604
- var symbol5 = Symbol.for(marker5);
605
- var _a5;
606
- _a5 = symbol5;
607
- var name5 = "AI_InvalidResponseDataError";
608
- var marker6 = `vercel.ai.error.${name5}`;
609
- var symbol6 = Symbol.for(marker6);
610
- var _a6;
611
- _a6 = symbol6;
612
- var name6 = "AI_JSONParseError";
613
- var marker7 = `vercel.ai.error.${name6}`;
614
- var symbol7 = Symbol.for(marker7);
615
- var _a7;
616
- var JSONParseError = class extends AISDKError {
617
- constructor({ text: text2, cause }) {
618
- super({
619
- name: name6,
620
- message: `JSON parsing failed: Text: ${text2}.
621
- Error message: ${getErrorMessage(cause)}`,
622
- cause
623
- });
624
- this[_a7] = true;
625
- this.text = text2;
626
- }
627
- static isInstance(error) {
628
- return AISDKError.hasMarker(error, marker7);
629
- }
630
- };
631
- _a7 = symbol7;
632
- var name7 = "AI_LoadAPIKeyError";
633
- var marker8 = `vercel.ai.error.${name7}`;
634
- var symbol8 = Symbol.for(marker8);
635
- var _a8;
636
- _a8 = symbol8;
637
- var name8 = "AI_LoadSettingError";
638
- var marker9 = `vercel.ai.error.${name8}`;
639
- var symbol9 = Symbol.for(marker9);
640
- var _a9;
641
- _a9 = symbol9;
642
- var name9 = "AI_NoContentGeneratedError";
643
- var marker10 = `vercel.ai.error.${name9}`;
644
- var symbol10 = Symbol.for(marker10);
645
- var _a10;
646
- _a10 = symbol10;
647
- var name10 = "AI_NoSuchModelError";
648
- var marker11 = `vercel.ai.error.${name10}`;
649
- var symbol11 = Symbol.for(marker11);
650
- var _a11;
651
- _a11 = symbol11;
652
- var name11 = "AI_TooManyEmbeddingValuesForCallError";
653
- var marker12 = `vercel.ai.error.${name11}`;
654
- var symbol12 = Symbol.for(marker12);
655
- var _a12;
656
- _a12 = symbol12;
657
- var name12 = "AI_TypeValidationError";
658
- var marker13 = `vercel.ai.error.${name12}`;
659
- var symbol13 = Symbol.for(marker13);
660
- var _a13;
661
- var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
662
- constructor({ value, cause }) {
663
- super({
664
- name: name12,
665
- message: `Type validation failed: Value: ${JSON.stringify(value)}.
666
- Error message: ${getErrorMessage(cause)}`,
667
- cause
668
- });
669
- this[_a13] = true;
670
- this.value = value;
671
- }
672
- static isInstance(error) {
673
- return AISDKError.hasMarker(error, marker13);
674
- }
675
- /**
676
- * Wraps an error into a TypeValidationError.
677
- * If the cause is already a TypeValidationError with the same value, it returns the cause.
678
- * Otherwise, it creates a new TypeValidationError.
679
- *
680
- * @param {Object} params - The parameters for wrapping the error.
681
- * @param {unknown} params.value - The value that failed validation.
682
- * @param {unknown} params.cause - The original error or cause of the validation failure.
683
- * @returns {TypeValidationError} A TypeValidationError instance.
684
- */
685
- static wrap({
686
- value,
687
- cause
688
- }) {
689
- return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
524
+ // utils/chat-helpers.ts
525
+ import { createAnthropic } from "@ai-sdk/anthropic";
526
+ import { createDeepSeek } from "@ai-sdk/deepseek";
527
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
528
+ import { createOpenAI } from "@ai-sdk/openai";
529
+ import { createOllama } from "ollama-ai-provider-v2";
530
+ var createLlmModel = (modelDefinition, apiKey, ollamaBaseUrl) => {
531
+ if (!modelDefinition?.id || !modelDefinition?.provider) {
532
+ throw new Error(
533
+ `Invalid model definition: ${JSON.stringify(modelDefinition)}`
534
+ );
690
535
  }
691
- };
692
- _a13 = symbol13;
693
- var TypeValidationError = _TypeValidationError;
694
- var name13 = "AI_UnsupportedFunctionalityError";
695
- var marker14 = `vercel.ai.error.${name13}`;
696
- var symbol14 = Symbol.for(marker14);
697
- var _a14;
698
- _a14 = symbol14;
699
-
700
- // node_modules/ai-v5/node_modules/@ai-sdk/provider-utils/dist/index.mjs
701
- import * as z4 from "zod/v4";
702
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
703
- import { ZodFirstPartyTypeKind } from "zod/v3";
704
- import {
705
- ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
706
- } from "zod/v3";
707
- var createIdGenerator = ({
708
- prefix,
709
- size = 16,
710
- alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
711
- separator = "-"
712
- } = {}) => {
713
- const generator = () => {
714
- const alphabetLength = alphabet.length;
715
- const chars = new Array(size);
716
- for (let i = 0; i < size; i++) {
717
- chars[i] = alphabet[Math.random() * alphabetLength | 0];
536
+ switch (modelDefinition.provider) {
537
+ case "anthropic":
538
+ return createAnthropic({ apiKey })(modelDefinition.id);
539
+ case "openai":
540
+ return createOpenAI({ apiKey })(modelDefinition.id);
541
+ case "deepseek":
542
+ return createDeepSeek({ apiKey })(modelDefinition.id);
543
+ case "google":
544
+ return createGoogleGenerativeAI({ apiKey })(modelDefinition.id);
545
+ case "ollama": {
546
+ const raw = ollamaBaseUrl || "http://localhost:11434/api";
547
+ const normalized = /\/api\/?$/.test(raw) ? raw : `${raw.replace(/\/+$/, "")}/api`;
548
+ return createOllama({ baseURL: normalized })(modelDefinition.id);
718
549
  }
719
- return chars.join("");
720
- };
721
- if (prefix == null) {
722
- return generator;
723
- }
724
- if (alphabet.includes(separator)) {
725
- throw new InvalidArgumentError({
726
- argument: "separator",
727
- message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
728
- });
550
+ default:
551
+ throw new Error(
552
+ `Unsupported provider: ${modelDefinition.provider} for model: ${modelDefinition.id}`
553
+ );
729
554
  }
730
- return () => `${prefix}${separator}${generator()}`;
731
555
  };
732
- var generateId = createIdGenerator();
733
- var suspectProtoRx = /"__proto__"\s*:/;
734
- var suspectConstructorRx = /"constructor"\s*:/;
735
- function _parse(text2) {
736
- const obj = JSON.parse(text2);
737
- if (obj === null || typeof obj !== "object") {
738
- return obj;
739
- }
740
- if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
741
- return obj;
742
- }
743
- return filter(obj);
744
- }
745
- function filter(obj) {
746
- let next = [obj];
747
- while (next.length) {
748
- const nodes = next;
749
- next = [];
750
- for (const node of nodes) {
751
- if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
752
- throw new SyntaxError("Object contains forbidden prototype property");
753
- }
754
- if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
755
- throw new SyntaxError("Object contains forbidden prototype property");
756
- }
757
- for (const key in node) {
758
- const value = node[key];
759
- if (value && typeof value === "object") {
760
- next.push(value);
761
- }
762
- }
763
- }
764
- }
765
- return obj;
766
- }
767
- function secureJsonParse(text2) {
768
- const { stackTraceLimit } = Error;
769
- Error.stackTraceLimit = 0;
770
- try {
771
- return _parse(text2);
772
- } finally {
773
- Error.stackTraceLimit = stackTraceLimit;
774
- }
775
- }
776
- var validatorSymbol = Symbol.for("vercel.ai.validator");
777
- function validator(validate) {
778
- return { [validatorSymbol]: true, validate };
779
- }
780
- function isValidator(value) {
781
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
556
+
557
+ // ../shared/tools.ts
558
+ import { z } from "zod";
559
+ import { zodToJsonSchema as zodToJsonSchema2 } from "@alcyone-labs/zod-to-json-schema";
560
+ import { tool } from "ai";
561
+ var fallbackInputSchema = z.object({}).passthrough();
562
+ var UNREPRESENTABLE_JSON_SCHEMA_MESSAGES = [
563
+ "Custom types cannot be represented in JSON Schema",
564
+ "Function types cannot be represented in JSON Schema"
565
+ ];
566
+ function isUnrepresentableSchemaError(error) {
567
+ return error instanceof Error && UNREPRESENTABLE_JSON_SCHEMA_MESSAGES.some(
568
+ (message) => error.message.includes(message)
569
+ );
782
570
  }
783
- function asValidator(value) {
784
- return isValidator(value) ? value : standardSchemaValidator(value);
571
+ function isZodSchema(value) {
572
+ return Boolean(
573
+ value && typeof value === "object" && "safeParse" in value
574
+ );
785
575
  }
786
- function standardSchemaValidator(standardSchema) {
787
- return validator(async (value) => {
788
- const result = await standardSchema["~standard"].validate(value);
789
- return result.issues == null ? { success: true, value: result.value } : {
790
- success: false,
791
- error: new TypeValidationError({
792
- value,
793
- cause: result.issues
794
- })
795
- };
796
- });
576
+ function isDirectlyUnrepresentable(schema) {
577
+ const schemaType = schema?._def?.type;
578
+ return schemaType === "custom" || schemaType === "function";
797
579
  }
798
- async function safeValidateTypes({
799
- value,
800
- schema
801
- }) {
802
- const validator2 = asValidator(schema);
803
- try {
804
- if (validator2.validate == null) {
805
- return { success: true, value, rawValue: value };
806
- }
807
- const result = await validator2.validate(value);
808
- if (result.success) {
809
- return { success: true, value: result.value, rawValue: value };
580
+ function canConvertToJSONSchema(schema) {
581
+ const toJSONSchema = z.toJSONSchema;
582
+ if (typeof toJSONSchema === "function") {
583
+ try {
584
+ toJSONSchema(schema);
585
+ return true;
586
+ } catch (error) {
587
+ if (isUnrepresentableSchemaError(error)) {
588
+ return false;
589
+ }
590
+ throw error;
810
591
  }
811
- return {
812
- success: false,
813
- error: TypeValidationError.wrap({ value, cause: result.error }),
814
- rawValue: value
815
- };
816
- } catch (error) {
817
- return {
818
- success: false,
819
- error: TypeValidationError.wrap({ value, cause: error }),
820
- rawValue: value
821
- };
822
592
  }
823
- }
824
- async function safeParseJSON({
825
- text: text2,
826
- schema
827
- }) {
828
593
  try {
829
- const value = secureJsonParse(text2);
830
- if (schema == null) {
831
- return { success: true, value, rawValue: value };
832
- }
833
- return await safeValidateTypes({ value, schema });
594
+ zodToJsonSchema2(schema);
595
+ return true;
834
596
  } catch (error) {
835
- return {
836
- success: false,
837
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
838
- rawValue: void 0
839
- };
840
- }
841
- }
842
- var getRelativePath = (pathA, pathB) => {
843
- let i = 0;
844
- for (; i < pathA.length && i < pathB.length; i++) {
845
- if (pathA[i] !== pathB[i])
846
- break;
597
+ if (isUnrepresentableSchemaError(error)) {
598
+ return false;
599
+ }
600
+ throw error;
847
601
  }
848
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
849
- };
850
- var ignoreOverride = Symbol(
851
- "Let zodToJsonSchema decide on which parser to use"
852
- );
853
- var defaultOptions = {
854
- name: void 0,
855
- $refStrategy: "root",
856
- basePath: ["#"],
857
- effectStrategy: "input",
858
- pipeStrategy: "all",
859
- dateStrategy: "format:date-time",
860
- mapStrategy: "entries",
861
- removeAdditionalStrategy: "passthrough",
862
- allowedAdditionalProperties: true,
863
- rejectedAdditionalProperties: false,
864
- definitionPath: "definitions",
865
- strictUnions: false,
866
- definitions: {},
867
- errorMessages: false,
868
- patternStrategy: "escape",
869
- applyRegexFlags: false,
870
- emailStrategy: "format:email",
871
- base64Strategy: "contentEncoding:base64",
872
- nameStrategy: "ref"
873
- };
874
- var getDefaultOptions = (options) => typeof options === "string" ? {
875
- ...defaultOptions,
876
- name: options
877
- } : {
878
- ...defaultOptions,
879
- ...options
880
- };
881
- function parseAnyDef() {
882
- return {};
883
602
  }
884
- function parseArrayDef(def, refs) {
885
- var _a17, _b, _c;
886
- const res = {
887
- type: "array"
888
- };
889
- if (((_a17 = def.type) == null ? void 0 : _a17._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
890
- res.items = parseDef(def.type._def, {
891
- ...refs,
892
- currentPath: [...refs.currentPath, "items"]
893
- });
894
- }
895
- if (def.minLength) {
896
- res.minItems = def.minLength.value;
603
+ function ensureInputSchema(schema) {
604
+ if (!isZodSchema(schema)) {
605
+ return fallbackInputSchema;
897
606
  }
898
- if (def.maxLength) {
899
- res.maxItems = def.maxLength.value;
607
+ if (isDirectlyUnrepresentable(schema)) {
608
+ return fallbackInputSchema;
900
609
  }
901
- if (def.exactLength) {
902
- res.minItems = def.exactLength.value;
903
- res.maxItems = def.exactLength.value;
904
- }
905
- return res;
906
- }
907
- function parseBigintDef(def) {
908
- const res = {
909
- type: "integer",
910
- format: "int64"
911
- };
912
- if (!def.checks)
913
- return res;
914
- for (const check of def.checks) {
915
- switch (check.kind) {
916
- case "min":
917
- if (check.inclusive) {
918
- res.minimum = check.value;
919
- } else {
920
- res.exclusiveMinimum = check.value;
921
- }
922
- break;
923
- case "max":
924
- if (check.inclusive) {
925
- res.maximum = check.value;
926
- } else {
927
- res.exclusiveMaximum = check.value;
928
- }
929
- break;
930
- case "multipleOf":
931
- res.multipleOf = check.value;
932
- break;
933
- }
610
+ if (!canConvertToJSONSchema(schema)) {
611
+ return fallbackInputSchema;
934
612
  }
935
- return res;
936
- }
937
- function parseBooleanDef() {
938
- return { type: "boolean" };
939
- }
940
- function parseBrandedDef(_def, refs) {
941
- return parseDef(_def.type._def, refs);
613
+ return schema;
942
614
  }
943
- var parseCatchDef = (def, refs) => {
944
- return parseDef(def.innerType._def, refs);
945
- };
946
- function parseDateDef(def, refs, overrideDateStrategy) {
947
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
948
- if (Array.isArray(strategy)) {
949
- return {
950
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
951
- };
952
- }
953
- switch (strategy) {
954
- case "string":
955
- case "format:date-time":
956
- return {
957
- type: "string",
958
- format: "date-time"
959
- };
960
- case "format:date":
961
- return {
962
- type: "string",
963
- format: "date"
964
- };
965
- case "integer":
966
- return integerDateParser(def);
615
+ function ensureOutputSchema(schema) {
616
+ if (!isZodSchema(schema)) {
617
+ return void 0;
967
618
  }
968
- }
969
- var integerDateParser = (def) => {
970
- const res = {
971
- type: "integer",
972
- format: "unix-time"
973
- };
974
- for (const check of def.checks) {
975
- switch (check.kind) {
976
- case "min":
977
- res.minimum = check.value;
978
- break;
979
- case "max":
980
- res.maximum = check.value;
981
- break;
982
- }
619
+ if (isDirectlyUnrepresentable(schema)) {
620
+ return void 0;
983
621
  }
984
- return res;
985
- };
986
- function parseDefaultDef(_def, refs) {
987
- return {
988
- ...parseDef(_def.innerType._def, refs),
989
- default: _def.defaultValue()
990
- };
991
- }
992
- function parseEffectsDef(_def, refs) {
993
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
994
- }
995
- function parseEnumDef(def) {
996
- return {
997
- type: "string",
998
- enum: Array.from(def.values)
999
- };
1000
- }
1001
- var isJsonSchema7AllOfType = (type) => {
1002
- if ("type" in type && type.type === "string")
1003
- return false;
1004
- return "allOf" in type;
1005
- };
1006
- function parseIntersectionDef(def, refs) {
1007
- const allOf = [
1008
- parseDef(def.left._def, {
1009
- ...refs,
1010
- currentPath: [...refs.currentPath, "allOf", "0"]
1011
- }),
1012
- parseDef(def.right._def, {
1013
- ...refs,
1014
- currentPath: [...refs.currentPath, "allOf", "1"]
1015
- })
1016
- ].filter((x) => !!x);
1017
- const mergedAllOf = [];
1018
- allOf.forEach((schema) => {
1019
- if (isJsonSchema7AllOfType(schema)) {
1020
- mergedAllOf.push(...schema.allOf);
1021
- } else {
1022
- let nestedSchema = schema;
1023
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
1024
- const { additionalProperties, ...rest } = schema;
1025
- nestedSchema = rest;
1026
- }
1027
- mergedAllOf.push(nestedSchema);
1028
- }
1029
- });
1030
- return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1031
- }
1032
- function parseLiteralDef(def) {
1033
- const parsedType = typeof def.value;
1034
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1035
- return {
1036
- type: Array.isArray(def.value) ? "array" : "object"
1037
- };
622
+ if (!canConvertToJSONSchema(schema)) {
623
+ return void 0;
1038
624
  }
1039
- return {
1040
- type: parsedType === "bigint" ? "integer" : parsedType,
1041
- const: def.value
1042
- };
625
+ return schema;
1043
626
  }
1044
- var emojiRegex = void 0;
1045
- var zodPatterns = {
1046
- /**
1047
- * `c` was changed to `[cC]` to replicate /i flag
1048
- */
1049
- cuid: /^[cC][^\s-]{8,}$/,
1050
- cuid2: /^[0-9a-z]+$/,
1051
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1052
- /**
1053
- * `a-z` was added to replicate /i flag
1054
- */
1055
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1056
- /**
1057
- * Constructed a valid Unicode RegExp
1058
- *
1059
- * Lazily instantiate since this type of regex isn't supported
1060
- * in all envs (e.g. React Native).
1061
- *
1062
- * See:
1063
- * https://github.com/colinhacks/zod/issues/2433
1064
- * Fix in Zod:
1065
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1066
- */
1067
- emoji: () => {
1068
- if (emojiRegex === void 0) {
1069
- emojiRegex = RegExp(
1070
- "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1071
- "u"
1072
- );
1073
- }
1074
- return emojiRegex;
1075
- },
1076
- /**
1077
- * Unused
1078
- */
1079
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1080
- /**
1081
- * Unused
1082
- */
1083
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1084
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1085
- /**
1086
- * Unused
1087
- */
1088
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1089
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1090
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1091
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1092
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
1093
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1094
- };
1095
- function parseStringDef(def, refs) {
1096
- const res = {
1097
- type: "string"
627
+ function extractPureToolName(toolKey) {
628
+ const separatorIndex = toolKey.indexOf("_");
629
+ if (separatorIndex === -1 || separatorIndex === toolKey.length - 1) {
630
+ return toolKey;
631
+ }
632
+ return toolKey.slice(separatorIndex + 1);
633
+ }
634
+ function convertMastraToolToVercelTool(toolName, mastraTool, options) {
635
+ const inputSchema = ensureInputSchema(mastraTool.inputSchema);
636
+ const outputSchema = ensureOutputSchema(mastraTool.outputSchema);
637
+ const displayName = options?.originalName ?? toolName;
638
+ const vercelToolConfig = {
639
+ type: "dynamic",
640
+ description: mastraTool.description,
641
+ inputSchema
1098
642
  };
1099
- if (def.checks) {
1100
- for (const check of def.checks) {
1101
- switch (check.kind) {
1102
- case "min":
1103
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1104
- break;
1105
- case "max":
1106
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1107
- break;
1108
- case "email":
1109
- switch (refs.emailStrategy) {
1110
- case "format:email":
1111
- addFormat(res, "email", check.message, refs);
1112
- break;
1113
- case "format:idn-email":
1114
- addFormat(res, "idn-email", check.message, refs);
1115
- break;
1116
- case "pattern:zod":
1117
- addPattern(res, zodPatterns.email, check.message, refs);
1118
- break;
1119
- }
1120
- break;
1121
- case "url":
1122
- addFormat(res, "uri", check.message, refs);
1123
- break;
1124
- case "uuid":
1125
- addFormat(res, "uuid", check.message, refs);
1126
- break;
1127
- case "regex":
1128
- addPattern(res, check.regex, check.message, refs);
1129
- break;
1130
- case "cuid":
1131
- addPattern(res, zodPatterns.cuid, check.message, refs);
1132
- break;
1133
- case "cuid2":
1134
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1135
- break;
1136
- case "startsWith":
1137
- addPattern(
1138
- res,
1139
- RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1140
- check.message,
1141
- refs
1142
- );
1143
- break;
1144
- case "endsWith":
1145
- addPattern(
1146
- res,
1147
- RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1148
- check.message,
1149
- refs
1150
- );
1151
- break;
1152
- case "datetime":
1153
- addFormat(res, "date-time", check.message, refs);
1154
- break;
1155
- case "date":
1156
- addFormat(res, "date", check.message, refs);
1157
- break;
1158
- case "time":
1159
- addFormat(res, "time", check.message, refs);
1160
- break;
1161
- case "duration":
1162
- addFormat(res, "duration", check.message, refs);
1163
- break;
1164
- case "length":
1165
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1166
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1167
- break;
1168
- case "includes": {
1169
- addPattern(
1170
- res,
1171
- RegExp(escapeLiteralCheckValue(check.value, refs)),
1172
- check.message,
1173
- refs
643
+ if (outputSchema) {
644
+ vercelToolConfig.outputSchema = outputSchema;
645
+ }
646
+ if (typeof mastraTool.execute === "function") {
647
+ vercelToolConfig.execute = async (input, options2) => {
648
+ const executionArgs = { context: input };
649
+ if (options2) {
650
+ executionArgs.runtimeContext = options2;
651
+ }
652
+ const result = await mastraTool.execute?.(executionArgs, options2);
653
+ if (outputSchema) {
654
+ const parsed = outputSchema.safeParse(result);
655
+ if (!parsed.success) {
656
+ throw new Error(
657
+ `Mastra tool '${displayName}' returned invalid output: ${parsed.error.message}`
1174
658
  );
1175
- break;
1176
- }
1177
- case "ip": {
1178
- if (check.version !== "v6") {
1179
- addFormat(res, "ipv4", check.message, refs);
1180
- }
1181
- if (check.version !== "v4") {
1182
- addFormat(res, "ipv6", check.message, refs);
1183
- }
1184
- break;
1185
- }
1186
- case "base64url":
1187
- addPattern(res, zodPatterns.base64url, check.message, refs);
1188
- break;
1189
- case "jwt":
1190
- addPattern(res, zodPatterns.jwt, check.message, refs);
1191
- break;
1192
- case "cidr": {
1193
- if (check.version !== "v6") {
1194
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1195
- }
1196
- if (check.version !== "v4") {
1197
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1198
- }
1199
- break;
1200
- }
1201
- case "emoji":
1202
- addPattern(res, zodPatterns.emoji(), check.message, refs);
1203
- break;
1204
- case "ulid": {
1205
- addPattern(res, zodPatterns.ulid, check.message, refs);
1206
- break;
1207
- }
1208
- case "base64": {
1209
- switch (refs.base64Strategy) {
1210
- case "format:binary": {
1211
- addFormat(res, "binary", check.message, refs);
1212
- break;
1213
- }
1214
- case "contentEncoding:base64": {
1215
- res.contentEncoding = "base64";
1216
- break;
1217
- }
1218
- case "pattern:zod": {
1219
- addPattern(res, zodPatterns.base64, check.message, refs);
1220
- break;
1221
- }
1222
- }
1223
- break;
1224
659
  }
1225
- case "nanoid": {
1226
- addPattern(res, zodPatterns.nanoid, check.message, refs);
1227
- }
1228
- case "toLowerCase":
1229
- case "toUpperCase":
1230
- case "trim":
1231
- break;
1232
- default:
1233
- /* @__PURE__ */ ((_) => {
1234
- })(check);
660
+ return parsed.data;
1235
661
  }
1236
- }
1237
- }
1238
- return res;
1239
- }
1240
- function escapeLiteralCheckValue(literal, refs) {
1241
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1242
- }
1243
- var ALPHA_NUMERIC = new Set(
1244
- "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1245
- );
1246
- function escapeNonAlphaNumeric(source) {
1247
- let result = "";
1248
- for (let i = 0; i < source.length; i++) {
1249
- if (!ALPHA_NUMERIC.has(source[i])) {
1250
- result += "\\";
1251
- }
1252
- result += source[i];
1253
- }
1254
- return result;
1255
- }
1256
- function addFormat(schema, value, message, refs) {
1257
- var _a17;
1258
- if (schema.format || ((_a17 = schema.anyOf) == null ? void 0 : _a17.some((x) => x.format))) {
1259
- if (!schema.anyOf) {
1260
- schema.anyOf = [];
1261
- }
1262
- if (schema.format) {
1263
- schema.anyOf.push({
1264
- format: schema.format
1265
- });
1266
- delete schema.format;
1267
- }
1268
- schema.anyOf.push({
1269
- format: value,
1270
- ...message && refs.errorMessages && { errorMessage: { format: message } }
1271
- });
1272
- } else {
1273
- schema.format = value;
1274
- }
1275
- }
1276
- function addPattern(schema, regex, message, refs) {
1277
- var _a17;
1278
- if (schema.pattern || ((_a17 = schema.allOf) == null ? void 0 : _a17.some((x) => x.pattern))) {
1279
- if (!schema.allOf) {
1280
- schema.allOf = [];
1281
- }
1282
- if (schema.pattern) {
1283
- schema.allOf.push({
1284
- pattern: schema.pattern
1285
- });
1286
- delete schema.pattern;
1287
- }
1288
- schema.allOf.push({
1289
- pattern: stringifyRegExpWithFlags(regex, refs),
1290
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1291
- });
1292
- } else {
1293
- schema.pattern = stringifyRegExpWithFlags(regex, refs);
1294
- }
1295
- }
1296
- function stringifyRegExpWithFlags(regex, refs) {
1297
- var _a17;
1298
- if (!refs.applyRegexFlags || !regex.flags) {
1299
- return regex.source;
662
+ return result;
663
+ };
1300
664
  }
1301
- const flags = {
1302
- i: regex.flags.includes("i"),
1303
- // Case-insensitive
1304
- m: regex.flags.includes("m"),
1305
- // `^` and `$` matches adjacent to newline characters
1306
- s: regex.flags.includes("s")
1307
- // `.` matches newlines
1308
- };
1309
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
1310
- let pattern = "";
1311
- let isEscaped = false;
1312
- let inCharGroup = false;
1313
- let inCharRange = false;
1314
- for (let i = 0; i < source.length; i++) {
1315
- if (isEscaped) {
1316
- pattern += source[i];
1317
- isEscaped = false;
1318
- continue;
665
+ try {
666
+ return tool(vercelToolConfig);
667
+ } catch (error) {
668
+ if (!isUnrepresentableSchemaError(error)) {
669
+ throw error;
1319
670
  }
1320
- if (flags.i) {
1321
- if (inCharGroup) {
1322
- if (source[i].match(/[a-z]/)) {
1323
- if (inCharRange) {
1324
- pattern += source[i];
1325
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1326
- inCharRange = false;
1327
- } else if (source[i + 1] === "-" && ((_a17 = source[i + 2]) == null ? void 0 : _a17.match(/[a-z]/))) {
1328
- pattern += source[i];
1329
- inCharRange = true;
1330
- } else {
1331
- pattern += `${source[i]}${source[i].toUpperCase()}`;
1332
- }
1333
- continue;
671
+ if (vercelToolConfig.outputSchema) {
672
+ const {
673
+ outputSchema: _unusedOutputSchema,
674
+ ...configWithoutOutputSchema
675
+ } = vercelToolConfig;
676
+ try {
677
+ return tool(configWithoutOutputSchema);
678
+ } catch (errorWithoutOutputSchema) {
679
+ if (!isUnrepresentableSchemaError(errorWithoutOutputSchema)) {
680
+ throw errorWithoutOutputSchema;
1334
681
  }
1335
- } else if (source[i].match(/[a-z]/)) {
1336
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1337
- continue;
1338
- }
1339
- }
1340
- if (flags.m) {
1341
- if (source[i] === "^") {
1342
- pattern += `(^|(?<=[\r
1343
- ]))`;
1344
- continue;
1345
- } else if (source[i] === "$") {
1346
- pattern += `($|(?=[\r
1347
- ]))`;
1348
- continue;
1349
- }
1350
- }
1351
- if (flags.s && source[i] === ".") {
1352
- pattern += inCharGroup ? `${source[i]}\r
1353
- ` : `[${source[i]}\r
1354
- ]`;
1355
- continue;
1356
- }
1357
- pattern += source[i];
1358
- if (source[i] === "\\") {
1359
- isEscaped = true;
1360
- } else if (inCharGroup && source[i] === "]") {
1361
- inCharGroup = false;
1362
- } else if (!inCharGroup && source[i] === "[") {
1363
- inCharGroup = true;
1364
- }
1365
- }
1366
- try {
1367
- new RegExp(pattern);
1368
- } catch (e) {
1369
- console.warn(
1370
- `Could not convert regex pattern at ${refs.currentPath.join(
1371
- "/"
1372
- )} to a flag-independent form! Falling back to the flag-ignorant source`
1373
- );
1374
- return regex.source;
1375
- }
1376
- return pattern;
1377
- }
1378
- function parseRecordDef(def, refs) {
1379
- var _a17, _b, _c, _d, _e, _f;
1380
- const schema = {
1381
- type: "object",
1382
- additionalProperties: (_a17 = parseDef(def.valueType._def, {
1383
- ...refs,
1384
- currentPath: [...refs.currentPath, "additionalProperties"]
1385
- })) != null ? _a17 : refs.allowedAdditionalProperties
1386
- };
1387
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1388
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1389
- return {
1390
- ...schema,
1391
- propertyNames: keyType
1392
- };
1393
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1394
- return {
1395
- ...schema,
1396
- propertyNames: {
1397
- enum: def.keyType._def.values
682
+ const fallbackConfig2 = {
683
+ ...configWithoutOutputSchema,
684
+ inputSchema: fallbackInputSchema
685
+ };
686
+ return tool(fallbackConfig2);
1398
687
  }
1399
- };
1400
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1401
- const { type, ...keyType } = parseBrandedDef(
1402
- def.keyType._def,
1403
- refs
1404
- );
1405
- return {
1406
- ...schema,
1407
- propertyNames: keyType
1408
- };
1409
- }
1410
- return schema;
1411
- }
1412
- function parseMapDef(def, refs) {
1413
- if (refs.mapStrategy === "record") {
1414
- return parseRecordDef(def, refs);
1415
- }
1416
- const keys = parseDef(def.keyType._def, {
1417
- ...refs,
1418
- currentPath: [...refs.currentPath, "items", "items", "0"]
1419
- }) || parseAnyDef();
1420
- const values = parseDef(def.valueType._def, {
1421
- ...refs,
1422
- currentPath: [...refs.currentPath, "items", "items", "1"]
1423
- }) || parseAnyDef();
1424
- return {
1425
- type: "array",
1426
- maxItems: 125,
1427
- items: {
1428
- type: "array",
1429
- items: [keys, values],
1430
- minItems: 2,
1431
- maxItems: 2
1432
- }
1433
- };
1434
- }
1435
- function parseNativeEnumDef(def) {
1436
- const object2 = def.values;
1437
- const actualKeys = Object.keys(def.values).filter((key) => {
1438
- return typeof object2[object2[key]] !== "number";
1439
- });
1440
- const actualValues = actualKeys.map((key) => object2[key]);
1441
- const parsedTypes = Array.from(
1442
- new Set(actualValues.map((values) => typeof values))
1443
- );
1444
- return {
1445
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1446
- enum: actualValues
1447
- };
1448
- }
1449
- function parseNeverDef() {
1450
- return { not: parseAnyDef() };
1451
- }
1452
- function parseNullDef() {
1453
- return {
1454
- type: "null"
1455
- };
1456
- }
1457
- var primitiveMappings = {
1458
- ZodString: "string",
1459
- ZodNumber: "number",
1460
- ZodBigInt: "integer",
1461
- ZodBoolean: "boolean",
1462
- ZodNull: "null"
1463
- };
1464
- function parseUnionDef(def, refs) {
1465
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1466
- if (options.every(
1467
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1468
- )) {
1469
- const types = options.reduce((types2, x) => {
1470
- const type = primitiveMappings[x._def.typeName];
1471
- return type && !types2.includes(type) ? [...types2, type] : types2;
1472
- }, []);
1473
- return {
1474
- type: types.length > 1 ? types : types[0]
1475
- };
1476
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1477
- const types = options.reduce(
1478
- (acc, x) => {
1479
- const type = typeof x._def.value;
1480
- switch (type) {
1481
- case "string":
1482
- case "number":
1483
- case "boolean":
1484
- return [...acc, type];
1485
- case "bigint":
1486
- return [...acc, "integer"];
1487
- case "object":
1488
- if (x._def.value === null)
1489
- return [...acc, "null"];
1490
- case "symbol":
1491
- case "undefined":
1492
- case "function":
1493
- default:
1494
- return acc;
1495
- }
1496
- },
1497
- []
1498
- );
1499
- if (types.length === options.length) {
1500
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1501
- return {
1502
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1503
- enum: options.reduce(
1504
- (acc, x) => {
1505
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1506
- },
1507
- []
1508
- )
1509
- };
1510
- }
1511
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1512
- return {
1513
- type: "string",
1514
- enum: options.reduce(
1515
- (acc, x) => [
1516
- ...acc,
1517
- ...x._def.values.filter((x2) => !acc.includes(x2))
1518
- ],
1519
- []
1520
- )
1521
- };
1522
- }
1523
- return asAnyOf(def, refs);
1524
- }
1525
- var asAnyOf = (def, refs) => {
1526
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1527
- (x, i) => parseDef(x._def, {
1528
- ...refs,
1529
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
1530
- })
1531
- ).filter(
1532
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1533
- );
1534
- return anyOf.length ? { anyOf } : void 0;
1535
- };
1536
- function parseNullableDef(def, refs) {
1537
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1538
- def.innerType._def.typeName
1539
- ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1540
- return {
1541
- type: [
1542
- primitiveMappings[def.innerType._def.typeName],
1543
- "null"
1544
- ]
1545
- };
1546
- }
1547
- const base = parseDef(def.innerType._def, {
1548
- ...refs,
1549
- currentPath: [...refs.currentPath, "anyOf", "0"]
1550
- });
1551
- return base && { anyOf: [base, { type: "null" }] };
1552
- }
1553
- function parseNumberDef(def) {
1554
- const res = {
1555
- type: "number"
1556
- };
1557
- if (!def.checks)
1558
- return res;
1559
- for (const check of def.checks) {
1560
- switch (check.kind) {
1561
- case "int":
1562
- res.type = "integer";
1563
- break;
1564
- case "min":
1565
- if (check.inclusive) {
1566
- res.minimum = check.value;
1567
- } else {
1568
- res.exclusiveMinimum = check.value;
1569
- }
1570
- break;
1571
- case "max":
1572
- if (check.inclusive) {
1573
- res.maximum = check.value;
1574
- } else {
1575
- res.exclusiveMaximum = check.value;
1576
- }
1577
- break;
1578
- case "multipleOf":
1579
- res.multipleOf = check.value;
1580
- break;
1581
- }
1582
- }
1583
- return res;
1584
- }
1585
- function parseObjectDef(def, refs) {
1586
- const result = {
1587
- type: "object",
1588
- properties: {}
1589
- };
1590
- const required = [];
1591
- const shape = def.shape();
1592
- for (const propName in shape) {
1593
- let propDef = shape[propName];
1594
- if (propDef === void 0 || propDef._def === void 0) {
1595
- continue;
1596
- }
1597
- const propOptional = safeIsOptional(propDef);
1598
- const parsedDef = parseDef(propDef._def, {
1599
- ...refs,
1600
- currentPath: [...refs.currentPath, "properties", propName],
1601
- propertyPath: [...refs.currentPath, "properties", propName]
1602
- });
1603
- if (parsedDef === void 0) {
1604
- continue;
1605
- }
1606
- result.properties[propName] = parsedDef;
1607
- if (!propOptional) {
1608
- required.push(propName);
1609
- }
1610
- }
1611
- if (required.length) {
1612
- result.required = required;
1613
- }
1614
- const additionalProperties = decideAdditionalProperties(def, refs);
1615
- if (additionalProperties !== void 0) {
1616
- result.additionalProperties = additionalProperties;
1617
- }
1618
- return result;
1619
- }
1620
- function decideAdditionalProperties(def, refs) {
1621
- if (def.catchall._def.typeName !== "ZodNever") {
1622
- return parseDef(def.catchall._def, {
1623
- ...refs,
1624
- currentPath: [...refs.currentPath, "additionalProperties"]
1625
- });
1626
- }
1627
- switch (def.unknownKeys) {
1628
- case "passthrough":
1629
- return refs.allowedAdditionalProperties;
1630
- case "strict":
1631
- return refs.rejectedAdditionalProperties;
1632
- case "strip":
1633
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1634
- }
1635
- }
1636
- function safeIsOptional(schema) {
1637
- try {
1638
- return schema.isOptional();
1639
- } catch (e) {
1640
- return true;
1641
- }
1642
- }
1643
- var parseOptionalDef = (def, refs) => {
1644
- var _a17;
1645
- if (refs.currentPath.toString() === ((_a17 = refs.propertyPath) == null ? void 0 : _a17.toString())) {
1646
- return parseDef(def.innerType._def, refs);
1647
- }
1648
- const innerSchema = parseDef(def.innerType._def, {
1649
- ...refs,
1650
- currentPath: [...refs.currentPath, "anyOf", "1"]
1651
- });
1652
- return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1653
- };
1654
- var parsePipelineDef = (def, refs) => {
1655
- if (refs.pipeStrategy === "input") {
1656
- return parseDef(def.in._def, refs);
1657
- } else if (refs.pipeStrategy === "output") {
1658
- return parseDef(def.out._def, refs);
1659
- }
1660
- const a = parseDef(def.in._def, {
1661
- ...refs,
1662
- currentPath: [...refs.currentPath, "allOf", "0"]
1663
- });
1664
- const b = parseDef(def.out._def, {
1665
- ...refs,
1666
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1667
- });
1668
- return {
1669
- allOf: [a, b].filter((x) => x !== void 0)
1670
- };
1671
- };
1672
- function parsePromiseDef(def, refs) {
1673
- return parseDef(def.type._def, refs);
1674
- }
1675
- function parseSetDef(def, refs) {
1676
- const items = parseDef(def.valueType._def, {
1677
- ...refs,
1678
- currentPath: [...refs.currentPath, "items"]
1679
- });
1680
- const schema = {
1681
- type: "array",
1682
- uniqueItems: true,
1683
- items
1684
- };
1685
- if (def.minSize) {
1686
- schema.minItems = def.minSize.value;
1687
- }
1688
- if (def.maxSize) {
1689
- schema.maxItems = def.maxSize.value;
1690
- }
1691
- return schema;
1692
- }
1693
- function parseTupleDef(def, refs) {
1694
- if (def.rest) {
1695
- return {
1696
- type: "array",
1697
- minItems: def.items.length,
1698
- items: def.items.map(
1699
- (x, i) => parseDef(x._def, {
1700
- ...refs,
1701
- currentPath: [...refs.currentPath, "items", `${i}`]
1702
- })
1703
- ).reduce(
1704
- (acc, x) => x === void 0 ? acc : [...acc, x],
1705
- []
1706
- ),
1707
- additionalItems: parseDef(def.rest._def, {
1708
- ...refs,
1709
- currentPath: [...refs.currentPath, "additionalItems"]
1710
- })
1711
- };
1712
- } else {
1713
- return {
1714
- type: "array",
1715
- minItems: def.items.length,
1716
- maxItems: def.items.length,
1717
- items: def.items.map(
1718
- (x, i) => parseDef(x._def, {
1719
- ...refs,
1720
- currentPath: [...refs.currentPath, "items", `${i}`]
1721
- })
1722
- ).reduce(
1723
- (acc, x) => x === void 0 ? acc : [...acc, x],
1724
- []
1725
- )
1726
- };
1727
- }
1728
- }
1729
- function parseUndefinedDef() {
1730
- return {
1731
- not: parseAnyDef()
1732
- };
1733
- }
1734
- function parseUnknownDef() {
1735
- return parseAnyDef();
1736
- }
1737
- var parseReadonlyDef = (def, refs) => {
1738
- return parseDef(def.innerType._def, refs);
1739
- };
1740
- var selectParser = (def, typeName, refs) => {
1741
- switch (typeName) {
1742
- case ZodFirstPartyTypeKind3.ZodString:
1743
- return parseStringDef(def, refs);
1744
- case ZodFirstPartyTypeKind3.ZodNumber:
1745
- return parseNumberDef(def);
1746
- case ZodFirstPartyTypeKind3.ZodObject:
1747
- return parseObjectDef(def, refs);
1748
- case ZodFirstPartyTypeKind3.ZodBigInt:
1749
- return parseBigintDef(def);
1750
- case ZodFirstPartyTypeKind3.ZodBoolean:
1751
- return parseBooleanDef();
1752
- case ZodFirstPartyTypeKind3.ZodDate:
1753
- return parseDateDef(def, refs);
1754
- case ZodFirstPartyTypeKind3.ZodUndefined:
1755
- return parseUndefinedDef();
1756
- case ZodFirstPartyTypeKind3.ZodNull:
1757
- return parseNullDef();
1758
- case ZodFirstPartyTypeKind3.ZodArray:
1759
- return parseArrayDef(def, refs);
1760
- case ZodFirstPartyTypeKind3.ZodUnion:
1761
- case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1762
- return parseUnionDef(def, refs);
1763
- case ZodFirstPartyTypeKind3.ZodIntersection:
1764
- return parseIntersectionDef(def, refs);
1765
- case ZodFirstPartyTypeKind3.ZodTuple:
1766
- return parseTupleDef(def, refs);
1767
- case ZodFirstPartyTypeKind3.ZodRecord:
1768
- return parseRecordDef(def, refs);
1769
- case ZodFirstPartyTypeKind3.ZodLiteral:
1770
- return parseLiteralDef(def);
1771
- case ZodFirstPartyTypeKind3.ZodEnum:
1772
- return parseEnumDef(def);
1773
- case ZodFirstPartyTypeKind3.ZodNativeEnum:
1774
- return parseNativeEnumDef(def);
1775
- case ZodFirstPartyTypeKind3.ZodNullable:
1776
- return parseNullableDef(def, refs);
1777
- case ZodFirstPartyTypeKind3.ZodOptional:
1778
- return parseOptionalDef(def, refs);
1779
- case ZodFirstPartyTypeKind3.ZodMap:
1780
- return parseMapDef(def, refs);
1781
- case ZodFirstPartyTypeKind3.ZodSet:
1782
- return parseSetDef(def, refs);
1783
- case ZodFirstPartyTypeKind3.ZodLazy:
1784
- return () => def.getter()._def;
1785
- case ZodFirstPartyTypeKind3.ZodPromise:
1786
- return parsePromiseDef(def, refs);
1787
- case ZodFirstPartyTypeKind3.ZodNaN:
1788
- case ZodFirstPartyTypeKind3.ZodNever:
1789
- return parseNeverDef();
1790
- case ZodFirstPartyTypeKind3.ZodEffects:
1791
- return parseEffectsDef(def, refs);
1792
- case ZodFirstPartyTypeKind3.ZodAny:
1793
- return parseAnyDef();
1794
- case ZodFirstPartyTypeKind3.ZodUnknown:
1795
- return parseUnknownDef();
1796
- case ZodFirstPartyTypeKind3.ZodDefault:
1797
- return parseDefaultDef(def, refs);
1798
- case ZodFirstPartyTypeKind3.ZodBranded:
1799
- return parseBrandedDef(def, refs);
1800
- case ZodFirstPartyTypeKind3.ZodReadonly:
1801
- return parseReadonlyDef(def, refs);
1802
- case ZodFirstPartyTypeKind3.ZodCatch:
1803
- return parseCatchDef(def, refs);
1804
- case ZodFirstPartyTypeKind3.ZodPipeline:
1805
- return parsePipelineDef(def, refs);
1806
- case ZodFirstPartyTypeKind3.ZodFunction:
1807
- case ZodFirstPartyTypeKind3.ZodVoid:
1808
- case ZodFirstPartyTypeKind3.ZodSymbol:
1809
- return void 0;
1810
- default:
1811
- return /* @__PURE__ */ ((_) => void 0)(typeName);
1812
- }
1813
- };
1814
- function parseDef(def, refs, forceResolution = false) {
1815
- var _a17;
1816
- const seenItem = refs.seen.get(def);
1817
- if (refs.override) {
1818
- const overrideResult = (_a17 = refs.override) == null ? void 0 : _a17.call(
1819
- refs,
1820
- def,
1821
- refs,
1822
- seenItem,
1823
- forceResolution
1824
- );
1825
- if (overrideResult !== ignoreOverride) {
1826
- return overrideResult;
1827
- }
1828
- }
1829
- if (seenItem && !forceResolution) {
1830
- const seenSchema = get$ref(seenItem, refs);
1831
- if (seenSchema !== void 0) {
1832
- return seenSchema;
1833
- }
1834
- }
1835
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1836
- refs.seen.set(def, newItem);
1837
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1838
- const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1839
- if (jsonSchema2) {
1840
- addMeta(def, refs, jsonSchema2);
1841
- }
1842
- if (refs.postProcess) {
1843
- const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1844
- newItem.jsonSchema = jsonSchema2;
1845
- return postProcessResult;
1846
- }
1847
- newItem.jsonSchema = jsonSchema2;
1848
- return jsonSchema2;
1849
- }
1850
- var get$ref = (item, refs) => {
1851
- switch (refs.$refStrategy) {
1852
- case "root":
1853
- return { $ref: item.path.join("/") };
1854
- case "relative":
1855
- return { $ref: getRelativePath(refs.currentPath, item.path) };
1856
- case "none":
1857
- case "seen": {
1858
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1859
- console.warn(
1860
- `Recursive reference detected at ${refs.currentPath.join(
1861
- "/"
1862
- )}! Defaulting to any`
1863
- );
1864
- return parseAnyDef();
1865
- }
1866
- return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1867
- }
1868
- }
1869
- };
1870
- var addMeta = (def, refs, jsonSchema2) => {
1871
- if (def.description) {
1872
- jsonSchema2.description = def.description;
1873
- }
1874
- return jsonSchema2;
1875
- };
1876
- var getRefs = (options) => {
1877
- const _options = getDefaultOptions(options);
1878
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1879
- return {
1880
- ..._options,
1881
- currentPath,
1882
- propertyPath: void 0,
1883
- seen: new Map(
1884
- Object.entries(_options.definitions).map(([name17, def]) => [
1885
- def._def,
1886
- {
1887
- def: def._def,
1888
- path: [..._options.basePath, _options.definitionPath, name17],
1889
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1890
- jsonSchema: void 0
1891
- }
1892
- ])
1893
- )
1894
- };
1895
- };
1896
- var zodToJsonSchema2 = (schema, options) => {
1897
- var _a17;
1898
- const refs = getRefs(options);
1899
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1900
- (acc, [name23, schema2]) => {
1901
- var _a23;
1902
- return {
1903
- ...acc,
1904
- [name23]: (_a23 = parseDef(
1905
- schema2._def,
1906
- {
1907
- ...refs,
1908
- currentPath: [...refs.basePath, refs.definitionPath, name23]
1909
- },
1910
- true
1911
- )) != null ? _a23 : parseAnyDef()
1912
- };
1913
- },
1914
- {}
1915
- ) : void 0;
1916
- const name17 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1917
- const main = (_a17 = parseDef(
1918
- schema._def,
1919
- name17 === void 0 ? refs : {
1920
- ...refs,
1921
- currentPath: [...refs.basePath, refs.definitionPath, name17]
1922
- },
1923
- false
1924
- )) != null ? _a17 : parseAnyDef();
1925
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1926
- if (title !== void 0) {
1927
- main.title = title;
1928
- }
1929
- const combined = name17 === void 0 ? definitions ? {
1930
- ...main,
1931
- [refs.definitionPath]: definitions
1932
- } : main : {
1933
- $ref: [
1934
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1935
- refs.definitionPath,
1936
- name17
1937
- ].join("/"),
1938
- [refs.definitionPath]: {
1939
- ...definitions,
1940
- [name17]: main
1941
- }
1942
- };
1943
- combined.$schema = "http://json-schema.org/draft-07/schema#";
1944
- return combined;
1945
- };
1946
- var zod_to_json_schema_default = zodToJsonSchema2;
1947
- function zod3Schema(zodSchema2, options) {
1948
- var _a17;
1949
- const useReferences = (_a17 = options == null ? void 0 : options.useReferences) != null ? _a17 : false;
1950
- return jsonSchema(
1951
- zod_to_json_schema_default(zodSchema2, {
1952
- $refStrategy: useReferences ? "root" : "none"
1953
- }),
1954
- {
1955
- validate: async (value) => {
1956
- const result = await zodSchema2.safeParseAsync(value);
1957
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1958
- }
1959
- }
1960
- );
1961
- }
1962
- function zod4Schema(zodSchema2, options) {
1963
- var _a17;
1964
- const useReferences = (_a17 = options == null ? void 0 : options.useReferences) != null ? _a17 : false;
1965
- const z4JSONSchema = z4.toJSONSchema(zodSchema2, {
1966
- target: "draft-7",
1967
- io: "output",
1968
- reused: useReferences ? "ref" : "inline"
1969
- });
1970
- return jsonSchema(z4JSONSchema, {
1971
- validate: async (value) => {
1972
- const result = await z4.safeParseAsync(zodSchema2, value);
1973
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1974
- }
1975
- });
1976
- }
1977
- function isZod4Schema(zodSchema2) {
1978
- return "_zod" in zodSchema2;
1979
- }
1980
- function zodSchema(zodSchema2, options) {
1981
- if (isZod4Schema(zodSchema2)) {
1982
- return zod4Schema(zodSchema2, options);
1983
- } else {
1984
- return zod3Schema(zodSchema2, options);
1985
- }
1986
- }
1987
- var schemaSymbol = Symbol.for("vercel.ai.schema");
1988
- function jsonSchema(jsonSchema2, {
1989
- validate
1990
- } = {}) {
1991
- return {
1992
- [schemaSymbol]: true,
1993
- _type: void 0,
1994
- // should never be used directly
1995
- [validatorSymbol]: true,
1996
- jsonSchema: jsonSchema2,
1997
- validate
1998
- };
1999
- }
2000
- function isSchema(value) {
2001
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2002
- }
2003
- function asSchema(schema) {
2004
- return schema == null ? jsonSchema({
2005
- properties: {},
2006
- additionalProperties: false
2007
- }) : isSchema(schema) ? schema : zodSchema(schema);
2008
- }
2009
- var { btoa, atob } = globalThis;
2010
-
2011
- // node_modules/ai-v5/dist/index.mjs
2012
- import { z } from "zod/v4";
2013
- import { z as z6 } from "zod/v4";
2014
- import { z as z5 } from "zod/v4";
2015
- import { z as z3 } from "zod/v4";
2016
- import { z as z2 } from "zod/v4";
2017
- import { z as z42 } from "zod/v4";
2018
- import { z as z7 } from "zod/v4";
2019
- import { z as z9 } from "zod/v4";
2020
- import { z as z8 } from "zod/v4";
2021
- import { z as z10 } from "zod/v4";
2022
- var __defProp = Object.defineProperty;
2023
- var __export = (target, all) => {
2024
- for (var name17 in all)
2025
- __defProp(target, name17, { get: all[name17], enumerable: true });
2026
- };
2027
- var name14 = "AI_NoOutputSpecifiedError";
2028
- var marker15 = `vercel.ai.error.${name14}`;
2029
- var symbol15 = Symbol.for(marker15);
2030
- var _a15;
2031
- _a15 = symbol15;
2032
- var name22 = "AI_InvalidArgumentError";
2033
- var marker22 = `vercel.ai.error.${name22}`;
2034
- var symbol22 = Symbol.for(marker22);
2035
- var _a22;
2036
- _a22 = symbol22;
2037
- var name32 = "AI_InvalidStreamPartError";
2038
- var marker32 = `vercel.ai.error.${name32}`;
2039
- var symbol32 = Symbol.for(marker32);
2040
- var _a32;
2041
- _a32 = symbol32;
2042
- var name42 = "AI_InvalidToolInputError";
2043
- var marker42 = `vercel.ai.error.${name42}`;
2044
- var symbol42 = Symbol.for(marker42);
2045
- var _a42;
2046
- _a42 = symbol42;
2047
- var name52 = "AI_MCPClientError";
2048
- var marker52 = `vercel.ai.error.${name52}`;
2049
- var symbol52 = Symbol.for(marker52);
2050
- var _a52;
2051
- _a52 = symbol52;
2052
- var name62 = "AI_NoImageGeneratedError";
2053
- var marker62 = `vercel.ai.error.${name62}`;
2054
- var symbol62 = Symbol.for(marker62);
2055
- var _a62;
2056
- _a62 = symbol62;
2057
- var name72 = "AI_NoObjectGeneratedError";
2058
- var marker72 = `vercel.ai.error.${name72}`;
2059
- var symbol72 = Symbol.for(marker72);
2060
- var _a72;
2061
- var NoObjectGeneratedError = class extends AISDKError {
2062
- constructor({
2063
- message = "No object generated.",
2064
- cause,
2065
- text: text2,
2066
- response,
2067
- usage,
2068
- finishReason
2069
- }) {
2070
- super({ name: name72, message, cause });
2071
- this[_a72] = true;
2072
- this.text = text2;
2073
- this.response = response;
2074
- this.usage = usage;
2075
- this.finishReason = finishReason;
2076
- }
2077
- static isInstance(error) {
2078
- return AISDKError.hasMarker(error, marker72);
2079
- }
2080
- };
2081
- _a72 = symbol72;
2082
- var name82 = "AI_NoOutputGeneratedError";
2083
- var marker82 = `vercel.ai.error.${name82}`;
2084
- var symbol82 = Symbol.for(marker82);
2085
- var _a82;
2086
- _a82 = symbol82;
2087
- var name92 = "AI_NoSuchToolError";
2088
- var marker92 = `vercel.ai.error.${name92}`;
2089
- var symbol92 = Symbol.for(marker92);
2090
- var _a92;
2091
- _a92 = symbol92;
2092
- var name102 = "AI_ToolCallRepairError";
2093
- var marker102 = `vercel.ai.error.${name102}`;
2094
- var symbol102 = Symbol.for(marker102);
2095
- var _a102;
2096
- _a102 = symbol102;
2097
- var name112 = "AI_InvalidDataContentError";
2098
- var marker112 = `vercel.ai.error.${name112}`;
2099
- var symbol112 = Symbol.for(marker112);
2100
- var _a112;
2101
- _a112 = symbol112;
2102
- var name122 = "AI_InvalidMessageRoleError";
2103
- var marker122 = `vercel.ai.error.${name122}`;
2104
- var symbol122 = Symbol.for(marker122);
2105
- var _a122;
2106
- _a122 = symbol122;
2107
- var name132 = "AI_MessageConversionError";
2108
- var marker132 = `vercel.ai.error.${name132}`;
2109
- var symbol132 = Symbol.for(marker132);
2110
- var _a132;
2111
- _a132 = symbol132;
2112
- var name142 = "AI_DownloadError";
2113
- var marker142 = `vercel.ai.error.${name142}`;
2114
- var symbol142 = Symbol.for(marker142);
2115
- var _a142;
2116
- _a142 = symbol142;
2117
- var name15 = "AI_RetryError";
2118
- var marker152 = `vercel.ai.error.${name15}`;
2119
- var symbol152 = Symbol.for(marker152);
2120
- var _a152;
2121
- _a152 = symbol152;
2122
- var dataContentSchema = z.union([
2123
- z.string(),
2124
- z.instanceof(Uint8Array),
2125
- z.instanceof(ArrayBuffer),
2126
- z.custom(
2127
- // Buffer might not be available in some environments such as CloudFlare:
2128
- (value) => {
2129
- var _a17, _b;
2130
- return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2131
- },
2132
- { message: "Must be a Buffer" }
2133
- )
2134
- ]);
2135
- var jsonValueSchema = z2.lazy(
2136
- () => z2.union([
2137
- z2.null(),
2138
- z2.string(),
2139
- z2.number(),
2140
- z2.boolean(),
2141
- z2.record(z2.string(), jsonValueSchema),
2142
- z2.array(jsonValueSchema)
2143
- ])
2144
- );
2145
- var providerMetadataSchema = z3.record(
2146
- z3.string(),
2147
- z3.record(z3.string(), jsonValueSchema)
2148
- );
2149
- var textPartSchema = z42.object({
2150
- type: z42.literal("text"),
2151
- text: z42.string(),
2152
- providerOptions: providerMetadataSchema.optional()
2153
- });
2154
- var imagePartSchema = z42.object({
2155
- type: z42.literal("image"),
2156
- image: z42.union([dataContentSchema, z42.instanceof(URL)]),
2157
- mediaType: z42.string().optional(),
2158
- providerOptions: providerMetadataSchema.optional()
2159
- });
2160
- var filePartSchema = z42.object({
2161
- type: z42.literal("file"),
2162
- data: z42.union([dataContentSchema, z42.instanceof(URL)]),
2163
- filename: z42.string().optional(),
2164
- mediaType: z42.string(),
2165
- providerOptions: providerMetadataSchema.optional()
2166
- });
2167
- var reasoningPartSchema = z42.object({
2168
- type: z42.literal("reasoning"),
2169
- text: z42.string(),
2170
- providerOptions: providerMetadataSchema.optional()
2171
- });
2172
- var toolCallPartSchema = z42.object({
2173
- type: z42.literal("tool-call"),
2174
- toolCallId: z42.string(),
2175
- toolName: z42.string(),
2176
- input: z42.unknown(),
2177
- providerOptions: providerMetadataSchema.optional(),
2178
- providerExecuted: z42.boolean().optional()
2179
- });
2180
- var outputSchema = z42.discriminatedUnion("type", [
2181
- z42.object({
2182
- type: z42.literal("text"),
2183
- value: z42.string()
2184
- }),
2185
- z42.object({
2186
- type: z42.literal("json"),
2187
- value: jsonValueSchema
2188
- }),
2189
- z42.object({
2190
- type: z42.literal("error-text"),
2191
- value: z42.string()
2192
- }),
2193
- z42.object({
2194
- type: z42.literal("error-json"),
2195
- value: jsonValueSchema
2196
- }),
2197
- z42.object({
2198
- type: z42.literal("content"),
2199
- value: z42.array(
2200
- z42.union([
2201
- z42.object({
2202
- type: z42.literal("text"),
2203
- text: z42.string()
2204
- }),
2205
- z42.object({
2206
- type: z42.literal("media"),
2207
- data: z42.string(),
2208
- mediaType: z42.string()
2209
- })
2210
- ])
2211
- )
2212
- })
2213
- ]);
2214
- var toolResultPartSchema = z42.object({
2215
- type: z42.literal("tool-result"),
2216
- toolCallId: z42.string(),
2217
- toolName: z42.string(),
2218
- output: outputSchema,
2219
- providerOptions: providerMetadataSchema.optional()
2220
- });
2221
- var systemModelMessageSchema = z5.object(
2222
- {
2223
- role: z5.literal("system"),
2224
- content: z5.string(),
2225
- providerOptions: providerMetadataSchema.optional()
2226
- }
2227
- );
2228
- var userModelMessageSchema = z5.object({
2229
- role: z5.literal("user"),
2230
- content: z5.union([
2231
- z5.string(),
2232
- z5.array(z5.union([textPartSchema, imagePartSchema, filePartSchema]))
2233
- ]),
2234
- providerOptions: providerMetadataSchema.optional()
2235
- });
2236
- var assistantModelMessageSchema = z5.object({
2237
- role: z5.literal("assistant"),
2238
- content: z5.union([
2239
- z5.string(),
2240
- z5.array(
2241
- z5.union([
2242
- textPartSchema,
2243
- filePartSchema,
2244
- reasoningPartSchema,
2245
- toolCallPartSchema,
2246
- toolResultPartSchema
2247
- ])
2248
- )
2249
- ]),
2250
- providerOptions: providerMetadataSchema.optional()
2251
- });
2252
- var toolModelMessageSchema = z5.object({
2253
- role: z5.literal("tool"),
2254
- content: z5.array(toolResultPartSchema),
2255
- providerOptions: providerMetadataSchema.optional()
2256
- });
2257
- var modelMessageSchema = z5.union([
2258
- systemModelMessageSchema,
2259
- userModelMessageSchema,
2260
- assistantModelMessageSchema,
2261
- toolModelMessageSchema
2262
- ]);
2263
- function stepCountIs(stepCount) {
2264
- return ({ steps }) => steps.length === stepCount;
2265
- }
2266
- var originalGenerateId = createIdGenerator({
2267
- prefix: "aitxt",
2268
- size: 24
2269
- });
2270
- var JsonToSseTransformStream = class extends TransformStream {
2271
- constructor() {
2272
- super({
2273
- transform(part, controller) {
2274
- controller.enqueue(`data: ${JSON.stringify(part)}
2275
-
2276
- `);
2277
- },
2278
- flush(controller) {
2279
- controller.enqueue("data: [DONE]\n\n");
2280
- }
2281
- });
2282
- }
2283
- };
2284
- var uiMessageChunkSchema = z7.union([
2285
- z7.strictObject({
2286
- type: z7.literal("text-start"),
2287
- id: z7.string(),
2288
- providerMetadata: providerMetadataSchema.optional()
2289
- }),
2290
- z7.strictObject({
2291
- type: z7.literal("text-delta"),
2292
- id: z7.string(),
2293
- delta: z7.string(),
2294
- providerMetadata: providerMetadataSchema.optional()
2295
- }),
2296
- z7.strictObject({
2297
- type: z7.literal("text-end"),
2298
- id: z7.string(),
2299
- providerMetadata: providerMetadataSchema.optional()
2300
- }),
2301
- z7.strictObject({
2302
- type: z7.literal("error"),
2303
- errorText: z7.string()
2304
- }),
2305
- z7.strictObject({
2306
- type: z7.literal("tool-input-start"),
2307
- toolCallId: z7.string(),
2308
- toolName: z7.string(),
2309
- providerExecuted: z7.boolean().optional(),
2310
- dynamic: z7.boolean().optional()
2311
- }),
2312
- z7.strictObject({
2313
- type: z7.literal("tool-input-delta"),
2314
- toolCallId: z7.string(),
2315
- inputTextDelta: z7.string()
2316
- }),
2317
- z7.strictObject({
2318
- type: z7.literal("tool-input-available"),
2319
- toolCallId: z7.string(),
2320
- toolName: z7.string(),
2321
- input: z7.unknown(),
2322
- providerExecuted: z7.boolean().optional(),
2323
- providerMetadata: providerMetadataSchema.optional(),
2324
- dynamic: z7.boolean().optional()
2325
- }),
2326
- z7.strictObject({
2327
- type: z7.literal("tool-input-error"),
2328
- toolCallId: z7.string(),
2329
- toolName: z7.string(),
2330
- input: z7.unknown(),
2331
- providerExecuted: z7.boolean().optional(),
2332
- providerMetadata: providerMetadataSchema.optional(),
2333
- dynamic: z7.boolean().optional(),
2334
- errorText: z7.string()
2335
- }),
2336
- z7.strictObject({
2337
- type: z7.literal("tool-output-available"),
2338
- toolCallId: z7.string(),
2339
- output: z7.unknown(),
2340
- providerExecuted: z7.boolean().optional(),
2341
- dynamic: z7.boolean().optional(),
2342
- preliminary: z7.boolean().optional()
2343
- }),
2344
- z7.strictObject({
2345
- type: z7.literal("tool-output-error"),
2346
- toolCallId: z7.string(),
2347
- errorText: z7.string(),
2348
- providerExecuted: z7.boolean().optional(),
2349
- dynamic: z7.boolean().optional()
2350
- }),
2351
- z7.strictObject({
2352
- type: z7.literal("reasoning"),
2353
- text: z7.string(),
2354
- providerMetadata: providerMetadataSchema.optional()
2355
- }),
2356
- z7.strictObject({
2357
- type: z7.literal("reasoning-start"),
2358
- id: z7.string(),
2359
- providerMetadata: providerMetadataSchema.optional()
2360
- }),
2361
- z7.strictObject({
2362
- type: z7.literal("reasoning-delta"),
2363
- id: z7.string(),
2364
- delta: z7.string(),
2365
- providerMetadata: providerMetadataSchema.optional()
2366
- }),
2367
- z7.strictObject({
2368
- type: z7.literal("reasoning-end"),
2369
- id: z7.string(),
2370
- providerMetadata: providerMetadataSchema.optional()
2371
- }),
2372
- z7.strictObject({
2373
- type: z7.literal("reasoning-part-finish")
2374
- }),
2375
- z7.strictObject({
2376
- type: z7.literal("source-url"),
2377
- sourceId: z7.string(),
2378
- url: z7.string(),
2379
- title: z7.string().optional(),
2380
- providerMetadata: providerMetadataSchema.optional()
2381
- }),
2382
- z7.strictObject({
2383
- type: z7.literal("source-document"),
2384
- sourceId: z7.string(),
2385
- mediaType: z7.string(),
2386
- title: z7.string(),
2387
- filename: z7.string().optional(),
2388
- providerMetadata: providerMetadataSchema.optional()
2389
- }),
2390
- z7.strictObject({
2391
- type: z7.literal("file"),
2392
- url: z7.string(),
2393
- mediaType: z7.string(),
2394
- providerMetadata: providerMetadataSchema.optional()
2395
- }),
2396
- z7.strictObject({
2397
- type: z7.string().startsWith("data-"),
2398
- id: z7.string().optional(),
2399
- data: z7.unknown(),
2400
- transient: z7.boolean().optional()
2401
- }),
2402
- z7.strictObject({
2403
- type: z7.literal("start-step")
2404
- }),
2405
- z7.strictObject({
2406
- type: z7.literal("finish-step")
2407
- }),
2408
- z7.strictObject({
2409
- type: z7.literal("start"),
2410
- messageId: z7.string().optional(),
2411
- messageMetadata: z7.unknown().optional()
2412
- }),
2413
- z7.strictObject({
2414
- type: z7.literal("finish"),
2415
- messageMetadata: z7.unknown().optional()
2416
- }),
2417
- z7.strictObject({
2418
- type: z7.literal("abort")
2419
- }),
2420
- z7.strictObject({
2421
- type: z7.literal("message-metadata"),
2422
- messageMetadata: z7.unknown()
2423
- })
2424
- ]);
2425
- function fixJson(input) {
2426
- const stack = ["ROOT"];
2427
- let lastValidIndex = -1;
2428
- let literalStart = null;
2429
- function processValueStart(char, i, swapState) {
2430
- {
2431
- switch (char) {
2432
- case '"': {
2433
- lastValidIndex = i;
2434
- stack.pop();
2435
- stack.push(swapState);
2436
- stack.push("INSIDE_STRING");
2437
- break;
2438
- }
2439
- case "f":
2440
- case "t":
2441
- case "n": {
2442
- lastValidIndex = i;
2443
- literalStart = i;
2444
- stack.pop();
2445
- stack.push(swapState);
2446
- stack.push("INSIDE_LITERAL");
2447
- break;
2448
- }
2449
- case "-": {
2450
- stack.pop();
2451
- stack.push(swapState);
2452
- stack.push("INSIDE_NUMBER");
2453
- break;
2454
- }
2455
- case "0":
2456
- case "1":
2457
- case "2":
2458
- case "3":
2459
- case "4":
2460
- case "5":
2461
- case "6":
2462
- case "7":
2463
- case "8":
2464
- case "9": {
2465
- lastValidIndex = i;
2466
- stack.pop();
2467
- stack.push(swapState);
2468
- stack.push("INSIDE_NUMBER");
2469
- break;
2470
- }
2471
- case "{": {
2472
- lastValidIndex = i;
2473
- stack.pop();
2474
- stack.push(swapState);
2475
- stack.push("INSIDE_OBJECT_START");
2476
- break;
2477
- }
2478
- case "[": {
2479
- lastValidIndex = i;
2480
- stack.pop();
2481
- stack.push(swapState);
2482
- stack.push("INSIDE_ARRAY_START");
2483
- break;
2484
- }
2485
- }
2486
- }
2487
- }
2488
- function processAfterObjectValue(char, i) {
2489
- switch (char) {
2490
- case ",": {
2491
- stack.pop();
2492
- stack.push("INSIDE_OBJECT_AFTER_COMMA");
2493
- break;
2494
- }
2495
- case "}": {
2496
- lastValidIndex = i;
2497
- stack.pop();
2498
- break;
2499
- }
2500
- }
2501
- }
2502
- function processAfterArrayValue(char, i) {
2503
- switch (char) {
2504
- case ",": {
2505
- stack.pop();
2506
- stack.push("INSIDE_ARRAY_AFTER_COMMA");
2507
- break;
2508
- }
2509
- case "]": {
2510
- lastValidIndex = i;
2511
- stack.pop();
2512
- break;
2513
- }
2514
- }
2515
- }
2516
- for (let i = 0; i < input.length; i++) {
2517
- const char = input[i];
2518
- const currentState = stack[stack.length - 1];
2519
- switch (currentState) {
2520
- case "ROOT":
2521
- processValueStart(char, i, "FINISH");
2522
- break;
2523
- case "INSIDE_OBJECT_START": {
2524
- switch (char) {
2525
- case '"': {
2526
- stack.pop();
2527
- stack.push("INSIDE_OBJECT_KEY");
2528
- break;
2529
- }
2530
- case "}": {
2531
- lastValidIndex = i;
2532
- stack.pop();
2533
- break;
2534
- }
2535
- }
2536
- break;
2537
- }
2538
- case "INSIDE_OBJECT_AFTER_COMMA": {
2539
- switch (char) {
2540
- case '"': {
2541
- stack.pop();
2542
- stack.push("INSIDE_OBJECT_KEY");
2543
- break;
2544
- }
2545
- }
2546
- break;
2547
- }
2548
- case "INSIDE_OBJECT_KEY": {
2549
- switch (char) {
2550
- case '"': {
2551
- stack.pop();
2552
- stack.push("INSIDE_OBJECT_AFTER_KEY");
2553
- break;
2554
- }
2555
- }
2556
- break;
2557
- }
2558
- case "INSIDE_OBJECT_AFTER_KEY": {
2559
- switch (char) {
2560
- case ":": {
2561
- stack.pop();
2562
- stack.push("INSIDE_OBJECT_BEFORE_VALUE");
2563
- break;
2564
- }
2565
- }
2566
- break;
2567
- }
2568
- case "INSIDE_OBJECT_BEFORE_VALUE": {
2569
- processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
2570
- break;
2571
- }
2572
- case "INSIDE_OBJECT_AFTER_VALUE": {
2573
- processAfterObjectValue(char, i);
2574
- break;
2575
- }
2576
- case "INSIDE_STRING": {
2577
- switch (char) {
2578
- case '"': {
2579
- stack.pop();
2580
- lastValidIndex = i;
2581
- break;
2582
- }
2583
- case "\\": {
2584
- stack.push("INSIDE_STRING_ESCAPE");
2585
- break;
2586
- }
2587
- default: {
2588
- lastValidIndex = i;
2589
- }
2590
- }
2591
- break;
2592
- }
2593
- case "INSIDE_ARRAY_START": {
2594
- switch (char) {
2595
- case "]": {
2596
- lastValidIndex = i;
2597
- stack.pop();
2598
- break;
2599
- }
2600
- default: {
2601
- lastValidIndex = i;
2602
- processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2603
- break;
2604
- }
2605
- }
2606
- break;
2607
- }
2608
- case "INSIDE_ARRAY_AFTER_VALUE": {
2609
- switch (char) {
2610
- case ",": {
2611
- stack.pop();
2612
- stack.push("INSIDE_ARRAY_AFTER_COMMA");
2613
- break;
2614
- }
2615
- case "]": {
2616
- lastValidIndex = i;
2617
- stack.pop();
2618
- break;
2619
- }
2620
- default: {
2621
- lastValidIndex = i;
2622
- break;
2623
- }
2624
- }
2625
- break;
2626
- }
2627
- case "INSIDE_ARRAY_AFTER_COMMA": {
2628
- processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
2629
- break;
2630
- }
2631
- case "INSIDE_STRING_ESCAPE": {
2632
- stack.pop();
2633
- lastValidIndex = i;
2634
- break;
2635
- }
2636
- case "INSIDE_NUMBER": {
2637
- switch (char) {
2638
- case "0":
2639
- case "1":
2640
- case "2":
2641
- case "3":
2642
- case "4":
2643
- case "5":
2644
- case "6":
2645
- case "7":
2646
- case "8":
2647
- case "9": {
2648
- lastValidIndex = i;
2649
- break;
2650
- }
2651
- case "e":
2652
- case "E":
2653
- case "-":
2654
- case ".": {
2655
- break;
2656
- }
2657
- case ",": {
2658
- stack.pop();
2659
- if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2660
- processAfterArrayValue(char, i);
2661
- }
2662
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2663
- processAfterObjectValue(char, i);
2664
- }
2665
- break;
2666
- }
2667
- case "}": {
2668
- stack.pop();
2669
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2670
- processAfterObjectValue(char, i);
2671
- }
2672
- break;
2673
- }
2674
- case "]": {
2675
- stack.pop();
2676
- if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2677
- processAfterArrayValue(char, i);
2678
- }
2679
- break;
2680
- }
2681
- default: {
2682
- stack.pop();
2683
- break;
2684
- }
2685
- }
2686
- break;
2687
- }
2688
- case "INSIDE_LITERAL": {
2689
- const partialLiteral = input.substring(literalStart, i + 1);
2690
- if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
2691
- stack.pop();
2692
- if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2693
- processAfterObjectValue(char, i);
2694
- } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2695
- processAfterArrayValue(char, i);
2696
- }
2697
- } else {
2698
- lastValidIndex = i;
2699
- }
2700
- break;
2701
- }
2702
- }
2703
- }
2704
- let result = input.slice(0, lastValidIndex + 1);
2705
- for (let i = stack.length - 1; i >= 0; i--) {
2706
- const state = stack[i];
2707
- switch (state) {
2708
- case "INSIDE_STRING": {
2709
- result += '"';
2710
- break;
2711
- }
2712
- case "INSIDE_OBJECT_KEY":
2713
- case "INSIDE_OBJECT_AFTER_KEY":
2714
- case "INSIDE_OBJECT_AFTER_COMMA":
2715
- case "INSIDE_OBJECT_START":
2716
- case "INSIDE_OBJECT_BEFORE_VALUE":
2717
- case "INSIDE_OBJECT_AFTER_VALUE": {
2718
- result += "}";
2719
- break;
2720
- }
2721
- case "INSIDE_ARRAY_START":
2722
- case "INSIDE_ARRAY_AFTER_COMMA":
2723
- case "INSIDE_ARRAY_AFTER_VALUE": {
2724
- result += "]";
2725
- break;
2726
- }
2727
- case "INSIDE_LITERAL": {
2728
- const partialLiteral = input.substring(literalStart, input.length);
2729
- if ("true".startsWith(partialLiteral)) {
2730
- result += "true".slice(partialLiteral.length);
2731
- } else if ("false".startsWith(partialLiteral)) {
2732
- result += "false".slice(partialLiteral.length);
2733
- } else if ("null".startsWith(partialLiteral)) {
2734
- result += "null".slice(partialLiteral.length);
2735
- }
2736
- }
2737
- }
2738
- }
2739
- return result;
2740
- }
2741
- async function parsePartialJson(jsonText) {
2742
- if (jsonText === void 0) {
2743
- return { value: void 0, state: "undefined-input" };
2744
- }
2745
- let result = await safeParseJSON({ text: jsonText });
2746
- if (result.success) {
2747
- return { value: result.value, state: "successful-parse" };
2748
- }
2749
- result = await safeParseJSON({ text: fixJson(jsonText) });
2750
- if (result.success) {
2751
- return { value: result.value, state: "repaired-parse" };
2752
- }
2753
- return { value: void 0, state: "failed-parse" };
2754
- }
2755
- var originalGenerateId2 = createIdGenerator({
2756
- prefix: "aitxt",
2757
- size: 24
2758
- });
2759
- var originalGenerateId3 = createIdGenerator({ prefix: "aiobj", size: 24 });
2760
- var originalGenerateId4 = createIdGenerator({ prefix: "aiobj", size: 24 });
2761
- var output_exports = {};
2762
- __export(output_exports, {
2763
- object: () => object,
2764
- text: () => text
2765
- });
2766
- var text = () => ({
2767
- type: "text",
2768
- responseFormat: { type: "text" },
2769
- async parsePartial({ text: text2 }) {
2770
- return { partial: text2 };
2771
- },
2772
- async parseOutput({ text: text2 }) {
2773
- return text2;
2774
- }
2775
- });
2776
- var object = ({
2777
- schema: inputSchema
2778
- }) => {
2779
- const schema = asSchema(inputSchema);
2780
- return {
2781
- type: "object",
2782
- responseFormat: {
2783
- type: "json",
2784
- schema: schema.jsonSchema
2785
- },
2786
- async parsePartial({ text: text2 }) {
2787
- const result = await parsePartialJson(text2);
2788
- switch (result.state) {
2789
- case "failed-parse":
2790
- case "undefined-input":
2791
- return void 0;
2792
- case "repaired-parse":
2793
- case "successful-parse":
2794
- return {
2795
- // Note: currently no validation of partial results:
2796
- partial: result.value
2797
- };
2798
- default: {
2799
- const _exhaustiveCheck = result.state;
2800
- throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
2801
- }
2802
- }
2803
- },
2804
- async parseOutput({ text: text2 }, context) {
2805
- const parseResult = await safeParseJSON({ text: text2 });
2806
- if (!parseResult.success) {
2807
- throw new NoObjectGeneratedError({
2808
- message: "No object generated: could not parse the response.",
2809
- cause: parseResult.error,
2810
- text: text2,
2811
- response: context.response,
2812
- usage: context.usage,
2813
- finishReason: context.finishReason
2814
- });
2815
- }
2816
- const validationResult = await safeValidateTypes({
2817
- value: parseResult.value,
2818
- schema
2819
- });
2820
- if (!validationResult.success) {
2821
- throw new NoObjectGeneratedError({
2822
- message: "No object generated: response did not match schema.",
2823
- cause: validationResult.error,
2824
- text: text2,
2825
- response: context.response,
2826
- usage: context.usage,
2827
- finishReason: context.finishReason
2828
- });
2829
- }
2830
- return validationResult.value;
2831
- }
2832
- };
2833
- };
2834
- var name16 = "AI_NoSuchProviderError";
2835
- var marker16 = `vercel.ai.error.${name16}`;
2836
- var symbol16 = Symbol.for(marker16);
2837
- var _a16;
2838
- _a16 = symbol16;
2839
- var ClientOrServerImplementationSchema = z8.looseObject({
2840
- name: z8.string(),
2841
- version: z8.string()
2842
- });
2843
- var BaseParamsSchema = z8.looseObject({
2844
- _meta: z8.optional(z8.object({}).loose())
2845
- });
2846
- var ResultSchema = BaseParamsSchema;
2847
- var RequestSchema = z8.object({
2848
- method: z8.string(),
2849
- params: z8.optional(BaseParamsSchema)
2850
- });
2851
- var ServerCapabilitiesSchema = z8.looseObject({
2852
- experimental: z8.optional(z8.object({}).loose()),
2853
- logging: z8.optional(z8.object({}).loose()),
2854
- prompts: z8.optional(
2855
- z8.looseObject({
2856
- listChanged: z8.optional(z8.boolean())
2857
- })
2858
- ),
2859
- resources: z8.optional(
2860
- z8.looseObject({
2861
- subscribe: z8.optional(z8.boolean()),
2862
- listChanged: z8.optional(z8.boolean())
2863
- })
2864
- ),
2865
- tools: z8.optional(
2866
- z8.looseObject({
2867
- listChanged: z8.optional(z8.boolean())
2868
- })
2869
- )
2870
- });
2871
- var InitializeResultSchema = ResultSchema.extend({
2872
- protocolVersion: z8.string(),
2873
- capabilities: ServerCapabilitiesSchema,
2874
- serverInfo: ClientOrServerImplementationSchema,
2875
- instructions: z8.optional(z8.string())
2876
- });
2877
- var PaginatedResultSchema = ResultSchema.extend({
2878
- nextCursor: z8.optional(z8.string())
2879
- });
2880
- var ToolSchema = z8.object({
2881
- name: z8.string(),
2882
- description: z8.optional(z8.string()),
2883
- inputSchema: z8.object({
2884
- type: z8.literal("object"),
2885
- properties: z8.optional(z8.object({}).loose())
2886
- }).loose()
2887
- }).loose();
2888
- var ListToolsResultSchema = PaginatedResultSchema.extend({
2889
- tools: z8.array(ToolSchema)
2890
- });
2891
- var TextContentSchema = z8.object({
2892
- type: z8.literal("text"),
2893
- text: z8.string()
2894
- }).loose();
2895
- var ImageContentSchema = z8.object({
2896
- type: z8.literal("image"),
2897
- data: z8.base64(),
2898
- mimeType: z8.string()
2899
- }).loose();
2900
- var ResourceContentsSchema = z8.object({
2901
- /**
2902
- * The URI of this resource.
2903
- */
2904
- uri: z8.string(),
2905
- /**
2906
- * The MIME type of this resource, if known.
2907
- */
2908
- mimeType: z8.optional(z8.string())
2909
- }).loose();
2910
- var TextResourceContentsSchema = ResourceContentsSchema.extend({
2911
- text: z8.string()
2912
- });
2913
- var BlobResourceContentsSchema = ResourceContentsSchema.extend({
2914
- blob: z8.base64()
2915
- });
2916
- var EmbeddedResourceSchema = z8.object({
2917
- type: z8.literal("resource"),
2918
- resource: z8.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2919
- }).loose();
2920
- var CallToolResultSchema = ResultSchema.extend({
2921
- content: z8.array(
2922
- z8.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
2923
- ),
2924
- isError: z8.boolean().default(false).optional()
2925
- }).or(
2926
- ResultSchema.extend({
2927
- toolResult: z8.unknown()
2928
- })
2929
- );
2930
- var JSONRPC_VERSION = "2.0";
2931
- var JSONRPCRequestSchema = z9.object({
2932
- jsonrpc: z9.literal(JSONRPC_VERSION),
2933
- id: z9.union([z9.string(), z9.number().int()])
2934
- }).merge(RequestSchema).strict();
2935
- var JSONRPCResponseSchema = z9.object({
2936
- jsonrpc: z9.literal(JSONRPC_VERSION),
2937
- id: z9.union([z9.string(), z9.number().int()]),
2938
- result: ResultSchema
2939
- }).strict();
2940
- var JSONRPCErrorSchema = z9.object({
2941
- jsonrpc: z9.literal(JSONRPC_VERSION),
2942
- id: z9.union([z9.string(), z9.number().int()]),
2943
- error: z9.object({
2944
- code: z9.number().int(),
2945
- message: z9.string(),
2946
- data: z9.optional(z9.unknown())
2947
- })
2948
- }).strict();
2949
- var JSONRPCNotificationSchema = z9.object({
2950
- jsonrpc: z9.literal(JSONRPC_VERSION)
2951
- }).merge(
2952
- z9.object({
2953
- method: z9.string(),
2954
- params: z9.optional(BaseParamsSchema)
2955
- })
2956
- ).strict();
2957
- var JSONRPCMessageSchema = z9.union([
2958
- JSONRPCRequestSchema,
2959
- JSONRPCNotificationSchema,
2960
- JSONRPCResponseSchema,
2961
- JSONRPCErrorSchema
2962
- ]);
2963
- var textUIPartSchema = z10.object({
2964
- type: z10.literal("text"),
2965
- text: z10.string(),
2966
- state: z10.enum(["streaming", "done"]).optional(),
2967
- providerMetadata: providerMetadataSchema.optional()
2968
- });
2969
- var reasoningUIPartSchema = z10.object({
2970
- type: z10.literal("reasoning"),
2971
- text: z10.string(),
2972
- state: z10.enum(["streaming", "done"]).optional(),
2973
- providerMetadata: providerMetadataSchema.optional()
2974
- });
2975
- var sourceUrlUIPartSchema = z10.object({
2976
- type: z10.literal("source-url"),
2977
- sourceId: z10.string(),
2978
- url: z10.string(),
2979
- title: z10.string().optional(),
2980
- providerMetadata: providerMetadataSchema.optional()
2981
- });
2982
- var sourceDocumentUIPartSchema = z10.object({
2983
- type: z10.literal("source-document"),
2984
- sourceId: z10.string(),
2985
- mediaType: z10.string(),
2986
- title: z10.string(),
2987
- filename: z10.string().optional(),
2988
- providerMetadata: providerMetadataSchema.optional()
2989
- });
2990
- var fileUIPartSchema = z10.object({
2991
- type: z10.literal("file"),
2992
- mediaType: z10.string(),
2993
- filename: z10.string().optional(),
2994
- url: z10.string(),
2995
- providerMetadata: providerMetadataSchema.optional()
2996
- });
2997
- var stepStartUIPartSchema = z10.object({
2998
- type: z10.literal("step-start")
2999
- });
3000
- var dataUIPartSchema = z10.object({
3001
- type: z10.string().startsWith("data-"),
3002
- id: z10.string().optional(),
3003
- data: z10.unknown()
3004
- });
3005
- var dynamicToolUIPartSchemas = [
3006
- z10.object({
3007
- type: z10.literal("dynamic-tool"),
3008
- toolName: z10.string(),
3009
- toolCallId: z10.string(),
3010
- state: z10.literal("input-streaming"),
3011
- input: z10.unknown().optional(),
3012
- output: z10.never().optional(),
3013
- errorText: z10.never().optional()
3014
- }),
3015
- z10.object({
3016
- type: z10.literal("dynamic-tool"),
3017
- toolName: z10.string(),
3018
- toolCallId: z10.string(),
3019
- state: z10.literal("input-available"),
3020
- input: z10.unknown(),
3021
- output: z10.never().optional(),
3022
- errorText: z10.never().optional(),
3023
- callProviderMetadata: providerMetadataSchema.optional()
3024
- }),
3025
- z10.object({
3026
- type: z10.literal("dynamic-tool"),
3027
- toolName: z10.string(),
3028
- toolCallId: z10.string(),
3029
- state: z10.literal("output-available"),
3030
- input: z10.unknown(),
3031
- output: z10.unknown(),
3032
- errorText: z10.never().optional(),
3033
- callProviderMetadata: providerMetadataSchema.optional(),
3034
- preliminary: z10.boolean().optional()
3035
- }),
3036
- z10.object({
3037
- type: z10.literal("dynamic-tool"),
3038
- toolName: z10.string(),
3039
- toolCallId: z10.string(),
3040
- state: z10.literal("output-error"),
3041
- input: z10.unknown(),
3042
- output: z10.never().optional(),
3043
- errorText: z10.string(),
3044
- callProviderMetadata: providerMetadataSchema.optional()
3045
- })
3046
- ];
3047
- var toolUIPartSchemas = [
3048
- z10.object({
3049
- type: z10.string().startsWith("tool-"),
3050
- toolCallId: z10.string(),
3051
- state: z10.literal("input-streaming"),
3052
- input: z10.unknown().optional(),
3053
- output: z10.never().optional(),
3054
- errorText: z10.never().optional()
3055
- }),
3056
- z10.object({
3057
- type: z10.string().startsWith("tool-"),
3058
- toolCallId: z10.string(),
3059
- state: z10.literal("input-available"),
3060
- input: z10.unknown(),
3061
- output: z10.never().optional(),
3062
- errorText: z10.never().optional(),
3063
- callProviderMetadata: providerMetadataSchema.optional()
3064
- }),
3065
- z10.object({
3066
- type: z10.string().startsWith("tool-"),
3067
- toolCallId: z10.string(),
3068
- state: z10.literal("output-available"),
3069
- input: z10.unknown(),
3070
- output: z10.unknown(),
3071
- errorText: z10.never().optional(),
3072
- callProviderMetadata: providerMetadataSchema.optional(),
3073
- preliminary: z10.boolean().optional()
3074
- }),
3075
- z10.object({
3076
- type: z10.string().startsWith("tool-"),
3077
- toolCallId: z10.string(),
3078
- state: z10.literal("output-error"),
3079
- input: z10.unknown(),
3080
- output: z10.never().optional(),
3081
- errorText: z10.string(),
3082
- callProviderMetadata: providerMetadataSchema.optional()
3083
- })
3084
- ];
3085
- var uiMessageSchema = z10.object({
3086
- id: z10.string(),
3087
- role: z10.enum(["system", "user", "assistant"]),
3088
- metadata: z10.unknown().optional(),
3089
- parts: z10.array(
3090
- z10.union([
3091
- textUIPartSchema,
3092
- reasoningUIPartSchema,
3093
- sourceUrlUIPartSchema,
3094
- sourceDocumentUIPartSchema,
3095
- fileUIPartSchema,
3096
- stepStartUIPartSchema,
3097
- dataUIPartSchema,
3098
- ...dynamicToolUIPartSchemas,
3099
- ...toolUIPartSchemas
3100
- ])
3101
- )
3102
- });
688
+ }
689
+ const fallbackConfig = {
690
+ ...vercelToolConfig,
691
+ inputSchema: fallbackInputSchema
692
+ };
693
+ return tool(fallbackConfig);
694
+ }
695
+ }
696
+ function convertMastraToolsToVercelTools(mastraTools) {
697
+ return Object.fromEntries(
698
+ Object.entries(mastraTools).map(([name, mastraTool]) => {
699
+ const pureToolName = extractPureToolName(name);
700
+ return [
701
+ pureToolName,
702
+ convertMastraToolToVercelTool(pureToolName, mastraTool, {
703
+ originalName: name
704
+ })
705
+ ];
706
+ })
707
+ );
708
+ }
3103
709
 
3104
- // utils/chat-helpers.ts
3105
- import { createAnthropic } from "@ai-sdk/anthropic";
3106
- import { createGoogleGenerativeAI } from "@ai-sdk/google";
3107
- import { createOpenAI } from "@ai-sdk/openai";
3108
- import { createOllama } from "ollama-ai-provider";
3109
- var createLlmModel = (modelDefinition, apiKey, ollamaBaseUrl) => {
3110
- if (!modelDefinition?.id || !modelDefinition?.provider) {
3111
- throw new Error(
3112
- `Invalid model definition: ${JSON.stringify(modelDefinition)}`
3113
- );
710
+ // ../shared/http-tool-calls.ts
711
+ function flattenToolsets(toolsets) {
712
+ const flattened = {};
713
+ for (const serverTools of Object.values(toolsets || {})) {
714
+ if (serverTools && typeof serverTools === "object") {
715
+ Object.assign(flattened, serverTools);
716
+ }
3114
717
  }
3115
- switch (modelDefinition.provider) {
3116
- case "anthropic":
3117
- return createAnthropic({ apiKey })(modelDefinition.id);
3118
- case "openai":
3119
- return createOpenAI({ apiKey })(modelDefinition.id);
3120
- case "deepseek":
3121
- return createOpenAI({ apiKey, baseURL: "https://api.deepseek.com/v1" })(
3122
- modelDefinition.id
3123
- );
3124
- case "google":
3125
- return createGoogleGenerativeAI({ apiKey })(modelDefinition.id);
3126
- case "ollama":
3127
- const baseUrl = ollamaBaseUrl || "http://localhost:11434/api";
3128
- return createOllama({
3129
- baseURL: `${baseUrl}`
3130
- })(modelDefinition.id, {
3131
- simulateStreaming: true
3132
- });
3133
- default:
3134
- throw new Error(
3135
- `Unsupported provider: ${modelDefinition.provider} for model: ${modelDefinition.id}`
3136
- );
718
+ return flattened;
719
+ }
720
+ function buildIndexWithAliases(tools2) {
721
+ const index = {};
722
+ for (const [toolName, tool2] of Object.entries(tools2 || {})) {
723
+ if (!tool2 || typeof tool2 !== "object" || !("execute" in tool2)) continue;
724
+ const idx = toolName.indexOf("_");
725
+ const pure = idx > -1 && idx < toolName.length - 1 ? toolName.slice(idx + 1) : toolName;
726
+ if (!(toolName in index)) index[toolName] = tool2;
727
+ if (!(pure in index)) index[pure] = tool2;
728
+ }
729
+ return index;
730
+ }
731
+ var hasUnresolvedToolCalls = (messages) => {
732
+ const toolCallIds = /* @__PURE__ */ new Set();
733
+ const toolResultIds = /* @__PURE__ */ new Set();
734
+ for (const msg of messages) {
735
+ if (!msg) continue;
736
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
737
+ for (const c of msg.content) {
738
+ if (c?.type === "tool-call") toolCallIds.add(c.toolCallId);
739
+ }
740
+ } else if (msg.role === "tool" && Array.isArray(msg.content)) {
741
+ for (const c of msg.content) {
742
+ if (c?.type === "tool-result") toolResultIds.add(c.toolCallId);
743
+ }
744
+ }
3137
745
  }
746
+ for (const id of toolCallIds) if (!toolResultIds.has(id)) return true;
747
+ return false;
3138
748
  };
749
+ async function executeToolCallsFromMessages(messages, options) {
750
+ let tools2 = {};
751
+ if (options.client) {
752
+ const toolsets = await options.client.getToolsets();
753
+ tools2 = flattenToolsets(toolsets);
754
+ } else if (options.toolsets) {
755
+ tools2 = flattenToolsets(options.toolsets);
756
+ } else {
757
+ tools2 = options.tools;
758
+ }
759
+ const index = buildIndexWithAliases(tools2);
760
+ const existingToolResultIds = /* @__PURE__ */ new Set();
761
+ for (const msg of messages) {
762
+ if (!msg || msg.role !== "tool" || !Array.isArray(msg.content))
763
+ continue;
764
+ for (const c of msg.content) {
765
+ if (c?.type === "tool-result") existingToolResultIds.add(c.toolCallId);
766
+ }
767
+ }
768
+ const toolResultsToAdd = [];
769
+ for (const msg of messages) {
770
+ if (!msg || msg.role !== "assistant" || !Array.isArray(msg.content))
771
+ continue;
772
+ for (const content of msg.content) {
773
+ if (content?.type === "tool-call" && !existingToolResultIds.has(content.toolCallId)) {
774
+ try {
775
+ const toolName = content.toolName;
776
+ const tool2 = index[toolName];
777
+ if (!tool2) throw new Error(`Tool '${toolName}' not found`);
778
+ const input = content.input || {};
779
+ const result = await tool2.execute({ context: input });
780
+ let output;
781
+ if (result && typeof result === "object" && result.content) {
782
+ const rc = result.content;
783
+ if (rc && typeof rc === "object" && "text" in rc && typeof rc.text === "string") {
784
+ output = { type: "text", value: rc.text };
785
+ } else if (rc && typeof rc === "object" && "type" in rc && "value" in rc) {
786
+ output = {
787
+ type: rc.type || "text",
788
+ value: rc.value
789
+ };
790
+ } else {
791
+ output = { type: "text", value: JSON.stringify(rc) };
792
+ }
793
+ } else {
794
+ output = { type: "text", value: String(result) };
795
+ }
796
+ const toolResultMessage = {
797
+ role: "tool",
798
+ content: [
799
+ {
800
+ type: "tool-result",
801
+ toolCallId: content.toolCallId,
802
+ toolName,
803
+ output
804
+ }
805
+ ]
806
+ };
807
+ toolResultsToAdd.push(toolResultMessage);
808
+ } catch (error) {
809
+ const errorOutput = {
810
+ type: "error-text",
811
+ value: error instanceof Error ? error.message : String(error)
812
+ };
813
+ const errorToolResultMessage = {
814
+ role: "tool",
815
+ content: [
816
+ {
817
+ type: "tool-result",
818
+ toolCallId: content.toolCallId,
819
+ toolName: content.toolName,
820
+ output: errorOutput
821
+ }
822
+ ]
823
+ };
824
+ toolResultsToAdd.push(errorToolResultMessage);
825
+ }
826
+ }
827
+ }
828
+ }
829
+ messages.push(...toolResultsToAdd);
830
+ }
3139
831
 
3140
832
  // routes/mcp/chat.ts
3141
- var DEBUG_ENABLED = process.env.MCP_DEBUG !== "false";
833
+ import { zodToJsonSchema as zodToJsonSchema3 } from "@alcyone-labs/zod-to-json-schema";
3142
834
  var ELICITATION_TIMEOUT = 3e5;
3143
835
  var MAX_AGENT_STEPS = 10;
3144
- var dbg = (...args) => {
3145
- if (DEBUG_ENABLED) console.log("[mcp/chat]", ...args);
3146
- };
836
+ var BACKEND_FETCH_ERROR_MESSAGE = "We are having difficulties processing your message right now. Please try again later.";
3147
837
  try {
3148
838
  process.setMaxListeners?.(50);
3149
839
  } catch {
@@ -3155,40 +845,82 @@ var sendSseEvent = (controller, encoder, event) => {
3155
845
 
3156
846
  `));
3157
847
  };
3158
- var handleAgentStepFinish = (streamingContext, text2, toolCalls, toolResults) => {
848
+ var sendBackendErrorText = (streamingContext) => {
849
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
850
+ type: "text",
851
+ content: BACKEND_FETCH_ERROR_MESSAGE
852
+ });
853
+ };
854
+ var sendBackendRequest = async (baseUrl, authHeader, body, streamingContext) => {
3159
855
  try {
3160
- if (toolCalls && Array.isArray(toolCalls)) {
3161
- for (const call of toolCalls) {
3162
- const currentToolCallId = ++streamingContext.toolCallId;
3163
- streamingContext.lastEmittedToolCallId = currentToolCallId;
3164
- if (streamingContext.controller && streamingContext.encoder) {
3165
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3166
- type: "tool_call",
3167
- toolCall: {
3168
- id: currentToolCallId,
3169
- name: call.name || call.toolName,
3170
- parameters: call.params || call.args || {},
3171
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3172
- status: "executing"
3173
- }
3174
- });
856
+ const res = await fetch(`${baseUrl}/streaming`, {
857
+ method: "POST",
858
+ headers: {
859
+ "content-type": "application/json",
860
+ ...authHeader ? { Authorization: authHeader } : {}
861
+ },
862
+ body: JSON.stringify(body)
863
+ });
864
+ if (!res.ok) {
865
+ sendBackendErrorText(streamingContext);
866
+ return null;
867
+ }
868
+ try {
869
+ const data = await res.json();
870
+ return data;
871
+ } catch {
872
+ sendBackendErrorText(streamingContext);
873
+ return null;
874
+ }
875
+ } catch {
876
+ sendBackendErrorText(streamingContext);
877
+ return null;
878
+ }
879
+ };
880
+ var handleAgentStepFinish = (streamingContext, text, toolCalls, toolResults, emitToolEvents = true) => {
881
+ try {
882
+ if (emitToolEvents) {
883
+ if (toolCalls && Array.isArray(toolCalls)) {
884
+ for (const call of toolCalls) {
885
+ const currentToolCallId = ++streamingContext.toolCallId;
886
+ streamingContext.lastEmittedToolCallId = currentToolCallId;
887
+ if (streamingContext.controller && streamingContext.encoder) {
888
+ sendSseEvent(
889
+ streamingContext.controller,
890
+ streamingContext.encoder,
891
+ {
892
+ type: "tool_call",
893
+ toolCall: {
894
+ id: currentToolCallId,
895
+ name: call.name || call.toolName,
896
+ parameters: call.params || call.args || {},
897
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
898
+ status: "executing"
899
+ }
900
+ }
901
+ );
902
+ }
3175
903
  }
3176
904
  }
3177
- }
3178
- if (toolResults && Array.isArray(toolResults)) {
3179
- for (const result of toolResults) {
3180
- const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : ++streamingContext.toolCallId;
3181
- if (streamingContext.controller && streamingContext.encoder) {
3182
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3183
- type: "tool_result",
3184
- toolResult: {
3185
- id: currentToolCallId,
3186
- toolCallId: currentToolCallId,
3187
- result: result.result,
3188
- error: result.error,
3189
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
3190
- }
3191
- });
905
+ if (toolResults && Array.isArray(toolResults)) {
906
+ for (const result of toolResults) {
907
+ const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : ++streamingContext.toolCallId;
908
+ if (streamingContext.controller && streamingContext.encoder) {
909
+ sendSseEvent(
910
+ streamingContext.controller,
911
+ streamingContext.encoder,
912
+ {
913
+ type: "tool_result",
914
+ toolResult: {
915
+ id: currentToolCallId,
916
+ toolCallId: currentToolCallId,
917
+ result: result.result,
918
+ error: result.error,
919
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
920
+ }
921
+ }
922
+ );
923
+ }
3192
924
  }
3193
925
  }
3194
926
  }
@@ -3197,7 +929,7 @@ var handleAgentStepFinish = (streamingContext, text2, toolCalls, toolResults) =>
3197
929
  sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3198
930
  type: "trace_step",
3199
931
  step: streamingContext.stepIndex,
3200
- text: text2,
932
+ text,
3201
933
  toolCalls: (toolCalls || []).map((c) => ({
3202
934
  name: c.name || c.toolName,
3203
935
  params: c.params || c.args || {}
@@ -3209,159 +941,252 @@ var handleAgentStepFinish = (streamingContext, text2, toolCalls, toolResults) =>
3209
941
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
3210
942
  });
3211
943
  }
3212
- } catch (err) {
3213
- dbg("onStepFinish error", err);
944
+ } catch {
3214
945
  }
3215
946
  };
3216
- var streamAgentResponse = async (streamingContext, stream) => {
3217
- let hasContent = false;
3218
- let chunkCount = 0;
3219
- for await (const chunk of stream.fullStream) {
3220
- chunkCount++;
3221
- if (chunk.type === "text-delta" && chunk.textDelta) {
3222
- hasContent = true;
3223
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3224
- type: "text",
3225
- content: chunk.textDelta
3226
- });
947
+ var createStreamingResponse = async (model, aiSdkTools, messages, streamingContext, provider, temperature, systemPrompt) => {
948
+ const messageHistory = (messages || []).map((m) => {
949
+ switch (m.role) {
950
+ case "system":
951
+ return { role: "system", content: m.content };
952
+ case "user":
953
+ return { role: "user", content: m.content };
954
+ case "assistant":
955
+ return { role: "assistant", content: m.content };
956
+ default:
957
+ return { role: "user", content: m.content };
3227
958
  }
3228
- if (chunk.type === "tool-call" && chunk.toolName) {
3229
- const currentToolCallId = ++streamingContext.toolCallId;
3230
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3231
- type: "tool_call",
3232
- toolCall: {
3233
- id: currentToolCallId,
3234
- name: chunk.toolName,
3235
- parameters: chunk.args || {},
3236
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3237
- status: "executing"
3238
- }
3239
- });
3240
- }
3241
- if (chunk.type === "tool-result" && chunk.result !== void 0) {
3242
- const currentToolCallId = streamingContext.toolCallId;
3243
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3244
- type: "tool_result",
3245
- toolResult: {
3246
- id: currentToolCallId,
3247
- toolCallId: currentToolCallId,
3248
- result: chunk.result,
3249
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
959
+ });
960
+ let steps = 0;
961
+ while (steps < MAX_AGENT_STEPS) {
962
+ let accumulatedText = "";
963
+ const iterationToolCalls = [];
964
+ const iterationToolResults = [];
965
+ const streamResult = await streamText({
966
+ model,
967
+ system: systemPrompt || "You are a helpful assistant with access to MCP tools.",
968
+ temperature: temperature ?? getDefaultTemperatureByProvider(provider),
969
+ tools: aiSdkTools,
970
+ messages: messageHistory,
971
+ onChunk: async (chunk) => {
972
+ switch (chunk.chunk.type) {
973
+ case "text-delta":
974
+ case "reasoning-delta": {
975
+ const text = chunk.chunk.text;
976
+ if (text) {
977
+ accumulatedText += text;
978
+ sendSseEvent(
979
+ streamingContext.controller,
980
+ streamingContext.encoder,
981
+ {
982
+ type: "text",
983
+ content: text
984
+ }
985
+ );
986
+ }
987
+ break;
988
+ }
989
+ case "tool-input-start": {
990
+ break;
991
+ }
992
+ case "tool-call": {
993
+ const currentToolCallId = ++streamingContext.toolCallId;
994
+ streamingContext.lastEmittedToolCallId = currentToolCallId;
995
+ const name = chunk.chunk.toolName || chunk.chunk.name;
996
+ const parameters = chunk.chunk.input ?? chunk.chunk.parameters ?? chunk.chunk.args ?? {};
997
+ iterationToolCalls.push({ name, params: parameters });
998
+ sendSseEvent(
999
+ streamingContext.controller,
1000
+ streamingContext.encoder,
1001
+ {
1002
+ type: "tool_call",
1003
+ toolCall: {
1004
+ id: currentToolCallId,
1005
+ name,
1006
+ parameters,
1007
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1008
+ status: "executing"
1009
+ }
1010
+ }
1011
+ );
1012
+ break;
1013
+ }
1014
+ case "tool-result": {
1015
+ const result = chunk.chunk.output ?? chunk.chunk.result ?? chunk.chunk.value;
1016
+ const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : streamingContext.toolCallId;
1017
+ iterationToolResults.push({ result });
1018
+ sendSseEvent(
1019
+ streamingContext.controller,
1020
+ streamingContext.encoder,
1021
+ {
1022
+ type: "tool_result",
1023
+ toolResult: {
1024
+ id: currentToolCallId,
1025
+ toolCallId: currentToolCallId,
1026
+ result,
1027
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1028
+ }
1029
+ }
1030
+ );
1031
+ break;
1032
+ }
1033
+ default:
1034
+ break;
3250
1035
  }
3251
- });
3252
- }
3253
- if (chunk.type === "error" && chunk.error) {
3254
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3255
- type: "error",
3256
- error: chunk.error instanceof Error ? chunk.error.message : String(chunk.error)
3257
- });
3258
- }
3259
- if (chunk.type === "finish") {
3260
- break;
3261
- }
3262
- }
3263
- dbg("Streaming finished", { hasContent, chunkCount });
3264
- return { hasContent, chunkCount };
3265
- };
3266
- var fallbackToCompletion = async (agent, messages, streamingContext, provider, temperature) => {
3267
- try {
3268
- const result = await agent.generate(messages, {
3269
- temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature
3270
- });
3271
- console.log("result", result);
3272
- if (result.text && result.text.trim()) {
3273
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3274
- type: "text",
3275
- content: result.text
3276
- });
3277
- }
3278
- } catch (fallbackErr) {
3279
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3280
- type: "error",
3281
- error: fallbackErr instanceof Error ? fallbackErr.message : "Unknown error"
3282
- });
3283
- }
3284
- };
3285
- var fallbackToStreamV1Method = async (agent, messages, streamingContext, provider, temperature) => {
3286
- try {
3287
- const stream = await agent.stream(messages, {
3288
- maxSteps: MAX_AGENT_STEPS,
3289
- temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature,
3290
- onStepFinish: ({ text: text2, toolCalls, toolResults }) => {
3291
- handleAgentStepFinish(streamingContext, text2, toolCalls, toolResults);
3292
1036
  }
3293
1037
  });
3294
- let hasContent = false;
3295
- let chunkCount = 0;
3296
- for await (const chunk of stream.textStream) {
3297
- if (chunk && chunk.trim()) {
3298
- hasContent = true;
3299
- chunkCount++;
3300
- sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3301
- type: "text",
3302
- content: chunk
3303
- });
3304
- }
3305
- }
3306
- dbg("Stream method finished", { hasContent, chunkCount });
3307
- if (!hasContent) {
3308
- dbg("No content from textStream; falling back to completion");
3309
- await fallbackToCompletion(
3310
- agent,
3311
- messages,
3312
- streamingContext,
3313
- provider,
3314
- temperature
3315
- );
3316
- }
3317
- } catch (streamErr) {
3318
- dbg("Stream method failed", streamErr);
3319
- await fallbackToCompletion(
3320
- agent,
3321
- messages,
1038
+ await streamResult.consumeStream();
1039
+ handleAgentStepFinish(
3322
1040
  streamingContext,
3323
- provider,
3324
- temperature
1041
+ accumulatedText,
1042
+ iterationToolCalls,
1043
+ iterationToolResults,
1044
+ false
3325
1045
  );
1046
+ const resp = await streamResult.response;
1047
+ const responseMessages = resp?.messages || [];
1048
+ if (responseMessages.length) {
1049
+ messageHistory.push(...responseMessages);
1050
+ for (const m of responseMessages) {
1051
+ if (m.role === "tool") {
1052
+ const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : ++streamingContext.toolCallId;
1053
+ const value = m.content;
1054
+ iterationToolResults.push({ result: value });
1055
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
1056
+ type: "tool_result",
1057
+ toolResult: {
1058
+ id: currentToolCallId,
1059
+ toolCallId: currentToolCallId,
1060
+ result: value,
1061
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1062
+ }
1063
+ });
1064
+ }
1065
+ }
1066
+ }
1067
+ steps++;
1068
+ const finishReason = await streamResult.finishReason;
1069
+ const shouldContinue = finishReason === "tool-calls" || accumulatedText.length === 0 && iterationToolResults.length > 0;
1070
+ if (!shouldContinue) break;
3326
1071
  }
1072
+ sendSseEvent(streamingContext.controller, streamingContext.encoder, {
1073
+ type: "elicitation_complete"
1074
+ });
1075
+ sendSseEvent(
1076
+ streamingContext.controller,
1077
+ streamingContext.encoder,
1078
+ "[DONE]"
1079
+ );
3327
1080
  };
3328
- var createStreamingResponse = async (agent, messages, streamingContext, provider, temperature) => {
3329
- try {
3330
- const stream = await agent.streamVNext(messages, {
3331
- stopWhen: stepCountIs(MAX_AGENT_STEPS),
3332
- modelSettings: {
3333
- temperature: temperature == null || void 0 ? getDefaultTemperatureByProvider(provider) : temperature
1081
+ var sendMessagesToBackend = async (messages, streamingContext, mcpClientManager, baseUrl, authHeader, selectedServers) => {
1082
+ const messageHistory = (messages || []).map((m) => {
1083
+ switch (m.role) {
1084
+ case "system":
1085
+ return { role: "system", content: m.content };
1086
+ case "user":
1087
+ return { role: "user", content: m.content };
1088
+ case "assistant":
1089
+ return { role: "assistant", content: m.content };
1090
+ default:
1091
+ return { role: "user", content: m.content };
1092
+ }
1093
+ });
1094
+ const flatTools = await mcpClientManager.getFlattenedToolsetsForEnabledServers(
1095
+ selectedServers
1096
+ );
1097
+ const toolDefs = Object.entries(flatTools).map(([name, tool2]) => ({
1098
+ name,
1099
+ description: tool2?.description,
1100
+ inputSchema: zodToJsonSchema3(tool2?.inputSchema)
1101
+ }));
1102
+ if (!baseUrl) {
1103
+ throw new Error("CONVEX_HTTP_URL is not set");
1104
+ }
1105
+ let steps = 0;
1106
+ while (steps < MAX_AGENT_STEPS) {
1107
+ const data = await sendBackendRequest(
1108
+ baseUrl,
1109
+ authHeader,
1110
+ {
1111
+ tools: toolDefs,
1112
+ messages: JSON.stringify(messageHistory)
3334
1113
  },
3335
- onStepFinish: ({ text: text2, toolCalls, toolResults }) => {
3336
- handleAgentStepFinish(streamingContext, text2, toolCalls, toolResults);
1114
+ streamingContext
1115
+ );
1116
+ if (!data) break;
1117
+ if (data?.ok && Array.isArray(data.messages)) {
1118
+ for (const msg of data.messages) {
1119
+ messageHistory.push(msg);
1120
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
1121
+ for (const c of msg.content) {
1122
+ if (c?.type === "text" && typeof c.text === "string") {
1123
+ sendSseEvent(
1124
+ streamingContext.controller,
1125
+ streamingContext.encoder,
1126
+ {
1127
+ type: "text",
1128
+ content: c.text
1129
+ }
1130
+ );
1131
+ } else if (c?.type === "tool-call") {
1132
+ const currentToolCallId = ++streamingContext.toolCallId;
1133
+ streamingContext.lastEmittedToolCallId = currentToolCallId;
1134
+ sendSseEvent(
1135
+ streamingContext.controller,
1136
+ streamingContext.encoder,
1137
+ {
1138
+ type: "tool_call",
1139
+ toolCall: {
1140
+ id: currentToolCallId,
1141
+ name: c.toolName || c.name,
1142
+ parameters: c.input || c.parameters || c.args || {},
1143
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1144
+ status: "executing"
1145
+ }
1146
+ }
1147
+ );
1148
+ }
1149
+ }
1150
+ }
3337
1151
  }
3338
- });
3339
- const { hasContent } = await streamAgentResponse(streamingContext, stream);
3340
- if (!hasContent) {
3341
- dbg("No content from fullStream; falling back to completion");
3342
- await fallbackToCompletion(
3343
- agent,
3344
- messages,
3345
- streamingContext,
3346
- provider,
3347
- temperature
3348
- );
1152
+ } else {
1153
+ sendBackendErrorText(streamingContext);
1154
+ break;
3349
1155
  }
3350
- } catch (error) {
3351
- if (error instanceof Error && error.message.includes("V1 models are not supported for streamVNext")) {
3352
- dbg(
3353
- "streamVNext not supported for this model, falling back to stream method"
3354
- );
3355
- await fallbackToStreamV1Method(
3356
- agent,
3357
- messages,
3358
- streamingContext,
3359
- provider,
3360
- temperature
3361
- );
1156
+ const beforeLen = messageHistory.length;
1157
+ if (hasUnresolvedToolCalls(messageHistory)) {
1158
+ await executeToolCallsFromMessages(messageHistory, {
1159
+ tools: flatTools
1160
+ });
1161
+ const newMsgs = messageHistory.slice(beforeLen);
1162
+ for (const m of newMsgs) {
1163
+ if (m.role === "tool" && Array.isArray(m.content)) {
1164
+ for (const tc of m.content) {
1165
+ if (tc.type === "tool-result") {
1166
+ const currentToolCallId = streamingContext.lastEmittedToolCallId != null ? streamingContext.lastEmittedToolCallId : ++streamingContext.toolCallId;
1167
+ const out = tc.output;
1168
+ const value = out && typeof out === "object" && "value" in out ? out.value : out;
1169
+ sendSseEvent(
1170
+ streamingContext.controller,
1171
+ streamingContext.encoder,
1172
+ {
1173
+ type: "tool_result",
1174
+ toolResult: {
1175
+ id: currentToolCallId,
1176
+ toolCallId: currentToolCallId,
1177
+ result: value,
1178
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1179
+ }
1180
+ }
1181
+ );
1182
+ }
1183
+ }
1184
+ }
1185
+ }
3362
1186
  } else {
3363
- throw error;
1187
+ break;
3364
1188
  }
1189
+ steps++;
3365
1190
  }
3366
1191
  sendSseEvent(streamingContext.controller, streamingContext.encoder, {
3367
1192
  type: "elicitation_complete"
@@ -3383,7 +1208,7 @@ chat.post("/", async (c) => {
3383
1208
  systemPrompt,
3384
1209
  temperature,
3385
1210
  messages,
3386
- ollamaBaseUrl,
1211
+ ollamaBaseUrl: _ollama_unused,
3387
1212
  action,
3388
1213
  requestId,
3389
1214
  response
@@ -3413,24 +1238,36 @@ chat.post("/", async (c) => {
3413
1238
  }
3414
1239
  return c.json({ success: true });
3415
1240
  }
3416
- if (!model?.id || !apiKey || !messages) {
1241
+ if (!messages) {
3417
1242
  return c.json(
3418
1243
  {
3419
1244
  success: false,
3420
- error: "model (with id), apiKey, and messages are required"
1245
+ error: "messages are required"
3421
1246
  },
3422
1247
  400
3423
1248
  );
3424
1249
  }
3425
- const llmModel = createLlmModel(model, apiKey, ollamaBaseUrl);
3426
- const toolsets = await mcpClientManager.getFlattenedToolsetsForEnabledServers();
3427
- const agent = new Agent({
3428
- name: "MCP Chat Agent",
3429
- instructions: systemPrompt || "You are a helpful assistant with access to MCP tools.",
3430
- model: llmModel,
3431
- tools: toolsets
3432
- });
1250
+ const sendToBackend = provider === "meta" && Boolean(requestData.sendMessagesToBackend);
1251
+ if (!sendToBackend && (!model?.id || !apiKey)) {
1252
+ return c.json(
1253
+ {
1254
+ success: false,
1255
+ error: "model (with id) and apiKey are required"
1256
+ },
1257
+ 400
1258
+ );
1259
+ }
1260
+ if (sendToBackend && !process.env.CONVEX_HTTP_URL) {
1261
+ return c.json(
1262
+ {
1263
+ success: false,
1264
+ error: "Server missing CONVEX_HTTP_URL configuration"
1265
+ },
1266
+ 500
1267
+ );
1268
+ }
3433
1269
  const encoder = new TextEncoder2();
1270
+ const authHeader = c.req.header("authorization") || void 0;
3434
1271
  const readableStream = new ReadableStream({
3435
1272
  async start(controller) {
3436
1273
  const streamingContext = {
@@ -3475,13 +1312,35 @@ chat.post("/", async (c) => {
3475
1312
  });
3476
1313
  });
3477
1314
  try {
3478
- await createStreamingResponse(
3479
- agent,
3480
- messages,
3481
- streamingContext,
3482
- provider,
3483
- temperature
3484
- );
1315
+ if (sendToBackend) {
1316
+ await sendMessagesToBackend(
1317
+ messages,
1318
+ streamingContext,
1319
+ mcpClientManager,
1320
+ process.env.CONVEX_HTTP_URL,
1321
+ authHeader,
1322
+ requestData.selectedServers
1323
+ );
1324
+ } else {
1325
+ const flatTools = await mcpClientManager.getFlattenedToolsetsForEnabledServers(
1326
+ requestData.selectedServers
1327
+ );
1328
+ const aiSdkTools = convertMastraToolsToVercelTools(flatTools);
1329
+ const llmModel = createLlmModel(
1330
+ model,
1331
+ apiKey || "",
1332
+ _ollama_unused
1333
+ );
1334
+ await createStreamingResponse(
1335
+ llmModel,
1336
+ aiSdkTools,
1337
+ messages,
1338
+ streamingContext,
1339
+ provider,
1340
+ temperature,
1341
+ systemPrompt
1342
+ );
1343
+ }
3485
1344
  } catch (error) {
3486
1345
  sendSseEvent(controller, encoder, {
3487
1346
  type: "error",
@@ -3502,7 +1361,11 @@ chat.post("/", async (c) => {
3502
1361
  });
3503
1362
  } catch (error) {
3504
1363
  console.error("[mcp/chat] Error in chat API:", error);
3505
- mcpClientManager.clearElicitationCallback();
1364
+ try {
1365
+ mcpClientManager.clearElicitationCallback();
1366
+ } catch (cleanupError) {
1367
+ console.error("[mcp/chat] Error during cleanup:", cleanupError);
1368
+ }
3506
1369
  return c.json(
3507
1370
  {
3508
1371
  success: false,
@@ -3699,13 +1562,13 @@ function normalizeToolName(toolName, serverIds) {
3699
1562
  }
3700
1563
  return toolName;
3701
1564
  }
3702
- function extractToolSchema(tool) {
3703
- if (!tool?.inputSchema) return {};
3704
- const jsonSchema2 = tool.inputSchema.toJSON?.();
3705
- if (jsonSchema2 && typeof jsonSchema2 === "object") {
3706
- return jsonSchema2;
1565
+ function extractToolSchema(tool2) {
1566
+ if (!tool2?.inputSchema) return {};
1567
+ const jsonSchema = tool2.inputSchema.toJSON?.();
1568
+ if (jsonSchema && typeof jsonSchema === "object") {
1569
+ return jsonSchema;
3707
1570
  }
3708
- const zodDef = tool.inputSchema._def;
1571
+ const zodDef = tool2.inputSchema._def;
3709
1572
  if (zodDef?.typeName === "ZodObject") {
3710
1573
  const baseSchema = {
3711
1574
  type: "object",
@@ -3795,12 +1658,12 @@ tests.post("/run-all", async (c) => {
3795
1658
  try {
3796
1659
  let serverConfigs = {};
3797
1660
  if (test.selectedServers && test.selectedServers.length > 0) {
3798
- for (const name17 of test.selectedServers) {
3799
- if (allServers[name17]) serverConfigs[name17] = allServers[name17];
1661
+ for (const name of test.selectedServers) {
1662
+ if (allServers[name]) serverConfigs[name] = allServers[name];
3800
1663
  }
3801
1664
  } else {
3802
- for (const [name17, cfg] of Object.entries(allServers)) {
3803
- serverConfigs[name17] = cfg;
1665
+ for (const [name, cfg] of Object.entries(allServers)) {
1666
+ serverConfigs[name] = cfg;
3804
1667
  }
3805
1668
  }
3806
1669
  const validation = validateMultipleServerConfigs(serverConfigs);
@@ -3815,9 +1678,9 @@ tests.post("/run-all", async (c) => {
3815
1678
  client = createMCPClientWithMultipleConnections(finalServers);
3816
1679
  const tools2 = await client.getTools();
3817
1680
  const toolsSchemas = Object.entries(tools2).map(
3818
- ([name17, tool]) => ({
3819
- toolName: name17,
3820
- inputSchema: extractToolSchema(tool)
1681
+ ([name, tool2]) => ({
1682
+ toolName: name,
1683
+ inputSchema: extractToolSchema(tool2)
3821
1684
  })
3822
1685
  );
3823
1686
  const runId = `${Date.now()}-${test.id}`;
@@ -3864,12 +1727,12 @@ tests.post("/run-all", async (c) => {
3864
1727
  let state = startJson;
3865
1728
  const serverIds = Object.keys(finalServers);
3866
1729
  while (state.kind === "tool_call") {
3867
- const name17 = state.toolName;
1730
+ const name = state.toolName;
3868
1731
  const args = state.args || {};
3869
- const tool = tools2[name17];
1732
+ const tool2 = tools2[name];
3870
1733
  try {
3871
- const result = await tool?.execute({ context: args });
3872
- calledTools.add(name17);
1734
+ const result = await tool2?.execute({ context: args });
1735
+ calledTools.add(name);
3873
1736
  controller.enqueue(
3874
1737
  encoder.encode(
3875
1738
  `data: ${JSON.stringify({
@@ -3877,7 +1740,7 @@ tests.post("/run-all", async (c) => {
3877
1740
  testId: test.id,
3878
1741
  step: ++step,
3879
1742
  text: "Executed tool",
3880
- toolCalls: [normalizeToolName(name17, serverIds)],
1743
+ toolCalls: [normalizeToolName(name, serverIds)],
3881
1744
  toolResults: [result]
3882
1745
  })}
3883
1746
 
@@ -3906,7 +1769,7 @@ tests.post("/run-all", async (c) => {
3906
1769
  {
3907
1770
  type: "tool-result",
3908
1771
  toolCallId: state.toolCallId,
3909
- toolName: name17,
1772
+ toolName: name,
3910
1773
  output: result
3911
1774
  }
3912
1775
  ]
@@ -3933,7 +1796,7 @@ tests.post("/run-all", async (c) => {
3933
1796
  state = stepJson;
3934
1797
  } catch (err) {
3935
1798
  throw new Error(
3936
- `Tool '${name17}' failed: ${err instanceof Error ? err.message : String(err)}`
1799
+ `Tool '${name}' failed: ${err instanceof Error ? err.message : String(err)}`
3937
1800
  );
3938
1801
  }
3939
1802
  }
@@ -4048,7 +1911,7 @@ var oauth_default = oauth;
4048
1911
 
4049
1912
  // routes/mcp/export.ts
4050
1913
  import { Hono as Hono9 } from "hono";
4051
- import { zodToJsonSchema as zodToJsonSchema3 } from "zod-to-json-schema";
1914
+ import { zodToJsonSchema as zodToJsonSchema4 } from "@alcyone-labs/zod-to-json-schema";
4052
1915
  var exporter = new Hono9();
4053
1916
  exporter.post("/server", async (c) => {
4054
1917
  try {
@@ -4063,17 +1926,17 @@ exporter.post("/server", async (c) => {
4063
1926
  }
4064
1927
  const flattenedTools = await mcp2.getToolsetsForServer(serverId);
4065
1928
  const tools2 = [];
4066
- for (const [name17, tool] of Object.entries(flattenedTools)) {
4067
- let inputSchema = tool.inputSchema;
1929
+ for (const [name, tool2] of Object.entries(flattenedTools)) {
1930
+ let inputSchema = tool2.inputSchema;
4068
1931
  try {
4069
- inputSchema = zodToJsonSchema3(inputSchema);
1932
+ inputSchema = zodToJsonSchema4(inputSchema);
4070
1933
  } catch {
4071
1934
  }
4072
1935
  tools2.push({
4073
- name: name17,
4074
- description: tool.description,
1936
+ name,
1937
+ description: tool2.description,
4075
1938
  inputSchema,
4076
- outputSchema: tool.outputSchema
1939
+ outputSchema: tool2.outputSchema
4077
1940
  });
4078
1941
  }
4079
1942
  const resources2 = mcp2.getResourcesForServer(serverId).map((r) => ({
@@ -4867,8 +2730,8 @@ var interceptor_default = interceptor;
4867
2730
  import { Hono as Hono11 } from "hono";
4868
2731
 
4869
2732
  // services/mcp-http-bridge.ts
4870
- import { z as z11 } from "zod";
4871
- import { zodToJsonSchema as zodToJsonSchema4 } from "zod-to-json-schema";
2733
+ import { z as z2 } from "zod";
2734
+ import { zodToJsonSchema as zodToJsonSchema5 } from "@alcyone-labs/zod-to-json-schema";
4872
2735
  function buildInitializeResult(serverId, mode) {
4873
2736
  if (mode === "adapter") {
4874
2737
  return {
@@ -4899,8 +2762,8 @@ function buildInitializeResult(serverId, mode) {
4899
2762
  function toJsonSchemaMaybe(schema) {
4900
2763
  try {
4901
2764
  if (schema && typeof schema === "object") {
4902
- if (schema instanceof z11.ZodType || "_def" in schema && "parse" in schema) {
4903
- return zodToJsonSchema4(schema);
2765
+ if (schema instanceof z2.ZodType || "_def" in schema && "parse" in schema) {
2766
+ return zodToJsonSchema5(schema);
4904
2767
  }
4905
2768
  }
4906
2769
  } catch {
@@ -4925,11 +2788,11 @@ async function handleJsonRpc(serverId, body, clientManager, mode) {
4925
2788
  }
4926
2789
  case "tools/list": {
4927
2790
  const toolsets = await clientManager.getToolsetsForServer(serverId);
4928
- const tools2 = Object.keys(toolsets).map((name17) => ({
4929
- name: name17,
4930
- description: toolsets[name17].description,
4931
- inputSchema: toJsonSchemaMaybe(toolsets[name17].inputSchema),
4932
- outputSchema: toJsonSchemaMaybe(toolsets[name17].outputSchema)
2791
+ const tools2 = Object.keys(toolsets).map((name) => ({
2792
+ name,
2793
+ description: toolsets[name].description,
2794
+ inputSchema: toJsonSchemaMaybe(toolsets[name].inputSchema),
2795
+ outputSchema: toJsonSchemaMaybe(toolsets[name].outputSchema)
4933
2796
  }));
4934
2797
  return respond({ result: { tools: tools2 } });
4935
2798
  }
@@ -5344,9 +3207,14 @@ var MCPJamClientManager = class {
5344
3207
  });
5345
3208
  return flattenedTools;
5346
3209
  }
5347
- async getFlattenedToolsetsForEnabledServers() {
3210
+ async getFlattenedToolsetsForEnabledServers(serverNameFilter) {
5348
3211
  const allFlattenedTools = {};
3212
+ const allServerIdsFromFilter = serverNameFilter?.map(
3213
+ (serverName) => this.getServerIdForName(serverName)
3214
+ );
5349
3215
  for (const [serverId, client] of this.mcpClients.entries()) {
3216
+ if (serverNameFilter && !allServerIdsFromFilter?.includes(serverId))
3217
+ continue;
5350
3218
  if (this.getConnectionStatus(serverId) !== "connected") continue;
5351
3219
  try {
5352
3220
  const toolsets = await client.getToolsets();
@@ -5471,12 +3339,12 @@ var MCPJamClientManager = class {
5471
3339
  if (!client) return;
5472
3340
  const toolsets = await client.getToolsets();
5473
3341
  const flattenedTools = this.flattenToolsets(toolsets);
5474
- for (const [name17, tool] of Object.entries(flattenedTools)) {
5475
- this.toolRegistry.set(`${serverId}:${name17}`, {
5476
- name: name17,
5477
- description: tool.description,
5478
- inputSchema: tool.inputSchema,
5479
- outputSchema: tool.outputSchema,
3342
+ for (const [name, tool2] of Object.entries(flattenedTools)) {
3343
+ this.toolRegistry.set(`${serverId}:${name}`, {
3344
+ name,
3345
+ description: tool2.description,
3346
+ inputSchema: tool2.inputSchema,
3347
+ outputSchema: tool2.outputSchema,
5480
3348
  serverId
5481
3349
  });
5482
3350
  }
@@ -5535,16 +3403,16 @@ var MCPJamClientManager = class {
5535
3403
  }
5536
3404
  async executeToolDirect(toolName, parameters = {}) {
5537
3405
  let serverId = "";
5538
- let name17 = toolName;
3406
+ let name = toolName;
5539
3407
  if (toolName.includes(":")) {
5540
3408
  const [sid, n] = toolName.split(":", 2);
5541
3409
  serverId = this.resolveServerId(sid) || "";
5542
- name17 = n;
3410
+ name = n;
5543
3411
  } else {
5544
- for (const tool2 of this.toolRegistry.values()) {
5545
- if (tool2.name === toolName) {
5546
- serverId = tool2.serverId;
5547
- name17 = toolName;
3412
+ for (const tool3 of this.toolRegistry.values()) {
3413
+ if (tool3.name === toolName) {
3414
+ serverId = tool3.serverId;
3415
+ name = toolName;
5548
3416
  break;
5549
3417
  }
5550
3418
  }
@@ -5556,7 +3424,7 @@ var MCPJamClientManager = class {
5556
3424
  const flattenedTools2 = this.flattenToolsets(toolsets2);
5557
3425
  if (flattenedTools2[toolName]) {
5558
3426
  serverId = clientServerId;
5559
- name17 = toolName;
3427
+ name = toolName;
5560
3428
  break;
5561
3429
  }
5562
3430
  } catch {
@@ -5571,10 +3439,10 @@ var MCPJamClientManager = class {
5571
3439
  throw new Error(`No MCP client available for server: ${serverId}`);
5572
3440
  const toolsets = await client.getToolsets();
5573
3441
  const flattenedTools = this.flattenToolsets(toolsets);
5574
- const tool = flattenedTools[name17];
5575
- if (!tool)
5576
- throw new Error(`Tool '${name17}' not found in server '${serverId}'`);
5577
- const schema = tool.inputSchema;
3442
+ const tool2 = flattenedTools[name];
3443
+ if (!tool2)
3444
+ throw new Error(`Tool '${name}' not found in server '${serverId}'`);
3445
+ const schema = tool2.inputSchema;
5578
3446
  const hasContextProperty = schema && typeof schema === "object" && schema.properties && Object.prototype.hasOwnProperty.call(
5579
3447
  schema.properties,
5580
3448
  "context"
@@ -5587,7 +3455,7 @@ var MCPJamClientManager = class {
5587
3455
  for (const args of attempts) {
5588
3456
  try {
5589
3457
  console.log("args", args);
5590
- const result = await tool.execute(args);
3458
+ const result = await tool2.execute(args);
5591
3459
  if (result && result.isError) {
5592
3460
  const errorText = result.content && result.content[0] && result.content[0].text ? result.content[0].text : "Unknown error";
5593
3461
  throw new Error(errorText);
@@ -5707,8 +3575,8 @@ function getMCPConfigFromEnv() {
5707
3575
  console.log("Parsed config data:", config);
5708
3576
  if (config.mcpServers && Object.keys(config.mcpServers).length > 0) {
5709
3577
  const servers2 = Object.entries(config.mcpServers).map(
5710
- ([name17, serverConfig]) => ({
5711
- name: name17,
3578
+ ([name, serverConfig]) => ({
3579
+ name,
5712
3580
  type: serverConfig.type || "stdio",
5713
3581
  // Default to stdio if not specified
5714
3582
  command: serverConfig.command,
@@ -5756,17 +3624,26 @@ try {
5756
3624
  } catch {
5757
3625
  }
5758
3626
  var app = new Hono13();
3627
+ try {
3628
+ const envFile = process.env.NODE_ENV === "production" ? ".env.production" : ".env.development";
3629
+ dotenv.config({ path: envFile });
3630
+ if (!process.env.CONVEX_HTTP_URL) {
3631
+ dotenv.config();
3632
+ }
3633
+ } catch (error) {
3634
+ console.warn("[startup] Failed loading env files", error);
3635
+ }
5759
3636
  var mcpJamClientManager = new MCPJamClientManager();
5760
3637
  app.use("*", async (c, next) => {
5761
3638
  c.mcpJamClientManager = mcpJamClientManager;
5762
3639
  await next();
5763
3640
  });
5764
3641
  app.use("*", logger());
5765
- var serverPort = process.env.PORT || "3000";
3642
+ var serverPort = process.env.PORT || "3001";
5766
3643
  var corsOrigins = [
5767
3644
  `http://localhost:${serverPort}`,
5768
3645
  "http://localhost:3000"
5769
- // Keep for development
3646
+ // Keep for frontend development
5770
3647
  ];
5771
3648
  app.use(
5772
3649
  "*",
@@ -5902,7 +3779,7 @@ if (process.env.NODE_ENV === "production") {
5902
3779
  });
5903
3780
  });
5904
3781
  }
5905
- var port = parseInt(process.env.PORT || "3000");
3782
+ var port = parseInt(process.env.PORT || "3001");
5906
3783
  var hostname = process.env.NODE_ENV === "production" ? "127.0.0.1" : "localhost";
5907
3784
  logBox(`http://${hostname}:${port}`, "\u{1F680} Inspector Launched");
5908
3785
  var server = serve({