@composio/core 0.3.4 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SfbczIpV.mjs → chunk-0j-ceAHr.mjs} +3 -4
- package/dist/chunk-CQwRTUmo.cjs +53 -0
- package/dist/fileUtils-CJjp8sBn.cjs +931 -0
- package/dist/fileUtils-XEoNI39Q.mjs +852 -0
- package/dist/files.types-B7P5A1Z5.d.mts +17 -0
- package/dist/files.types-D-RzIOHq.d.cts +17 -0
- package/dist/index.cjs +468 -1758
- package/dist/index.d.cts +560 -382
- package/dist/index.d.mts +559 -382
- package/dist/index.mjs +368 -1621
- package/dist/models/Files.node.cjs +38 -0
- package/dist/models/Files.node.d.cts +41 -0
- package/dist/models/Files.node.d.mts +41 -0
- package/dist/models/Files.node.mjs +39 -0
- package/dist/models/Files.workerd.cjs +29 -0
- package/dist/models/Files.workerd.d.cts +13 -0
- package/dist/models/Files.workerd.d.mts +13 -0
- package/dist/models/Files.workerd.mjs +28 -0
- package/dist/platform/node.cjs +46 -0
- package/dist/platform/node.d.cts +11 -0
- package/dist/platform/node.d.mts +11 -0
- package/dist/platform/node.mjs +42 -0
- package/dist/platform/workerd.cjs +36 -0
- package/dist/platform/workerd.d.cts +12 -0
- package/dist/platform/workerd.d.mts +12 -0
- package/dist/platform/workerd.mjs +35 -0
- package/dist/types-BaUqjuX3.d.mts +56 -0
- package/dist/types-BrsW5suw.d.cts +56 -0
- package/generated/index.d.ts +6 -0
- package/generated/index.js +18 -0
- package/package.json +79 -17
- package/src/platform/index.ts +2 -0
- package/src/platform/node.ts +51 -0
- package/src/platform/types.ts +60 -0
- package/src/platform/workerd.ts +57 -0
package/dist/index.cjs
CHANGED
|
@@ -1,62 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (all, symbols) => {
|
|
9
|
-
let target = {};
|
|
10
|
-
for (var name in all) {
|
|
11
|
-
__defProp(target, name, {
|
|
12
|
-
get: all[name],
|
|
13
|
-
enumerable: true
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
if (symbols) {
|
|
17
|
-
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
18
|
-
}
|
|
19
|
-
return target;
|
|
20
|
-
};
|
|
21
|
-
var __copyProps = (to, from, except, desc) => {
|
|
22
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
-
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
24
|
-
key = keys[i];
|
|
25
|
-
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
26
|
-
__defProp(to, key, {
|
|
27
|
-
get: ((k) => from[k]).bind(null, key),
|
|
28
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return to;
|
|
34
|
-
};
|
|
35
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
36
|
-
value: mod,
|
|
37
|
-
enumerable: true
|
|
38
|
-
}) : target, mod));
|
|
39
|
-
|
|
40
|
-
//#endregion
|
|
41
|
-
let __composio_client = require("@composio/client");
|
|
42
|
-
__composio_client = __toESM(__composio_client);
|
|
1
|
+
const require_chunk = require('./chunk-CQwRTUmo.cjs');
|
|
2
|
+
const require_fileUtils = require('./fileUtils-CJjp8sBn.cjs');
|
|
3
|
+
let _composio_client = require("@composio/client");
|
|
4
|
+
_composio_client = require_chunk.__toESM(_composio_client);
|
|
43
5
|
let zod_v3 = require("zod/v3");
|
|
44
|
-
zod_v3 = __toESM(zod_v3);
|
|
6
|
+
zod_v3 = require_chunk.__toESM(zod_v3);
|
|
45
7
|
let zod_to_json_schema = require("zod-to-json-schema");
|
|
46
|
-
zod_to_json_schema = __toESM(zod_to_json_schema);
|
|
47
|
-
let chalk = require("chalk");
|
|
48
|
-
chalk = __toESM(chalk);
|
|
49
|
-
let uuid = require("uuid");
|
|
50
|
-
let crypto = require("crypto");
|
|
51
|
-
crypto = __toESM(crypto);
|
|
52
|
-
let path = require("path");
|
|
53
|
-
path = __toESM(path);
|
|
54
|
-
let openai = require("openai");
|
|
8
|
+
zod_to_json_schema = require_chunk.__toESM(zod_to_json_schema);
|
|
55
9
|
let node_crypto = require("node:crypto");
|
|
56
|
-
node_crypto = __toESM(node_crypto);
|
|
10
|
+
node_crypto = require_chunk.__toESM(node_crypto);
|
|
11
|
+
let _platform = require("#platform");
|
|
12
|
+
let openai = require("openai");
|
|
57
13
|
let semver = require("semver");
|
|
58
|
-
semver = __toESM(semver);
|
|
59
|
-
let
|
|
14
|
+
semver = require_chunk.__toESM(semver);
|
|
15
|
+
let _files = require("#files");
|
|
16
|
+
let _composio_json_schema_to_zod = require("@composio/json-schema-to-zod");
|
|
60
17
|
|
|
61
18
|
//#region src/types/authConfigs.types.ts
|
|
62
19
|
const AuthConfigTypes = {
|
|
@@ -962,350 +919,6 @@ const ToolProxyParamsSchema = zod_v3.z.object({
|
|
|
962
919
|
customConnectionData: CustomConnectionDataSchema.describe("DEPRECATED: This field is deprecated and will be removed in the future.").optional()
|
|
963
920
|
});
|
|
964
921
|
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region src/utils/env.ts
|
|
967
|
-
const getEnvVariable = (name, defaultValue = void 0) => {
|
|
968
|
-
try {
|
|
969
|
-
return process.env[name] || defaultValue;
|
|
970
|
-
} catch (_e) {
|
|
971
|
-
return defaultValue;
|
|
972
|
-
}
|
|
973
|
-
};
|
|
974
|
-
/**
|
|
975
|
-
* Method to return all the envs based on a specific prefix
|
|
976
|
-
* @param prefix
|
|
977
|
-
* @example
|
|
978
|
-
* COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00
|
|
979
|
-
* COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00
|
|
980
|
-
* COMPOSIO_TOOLKIT_VERSION_GMAIL=latest
|
|
981
|
-
* @returns {Record<string, unknown>}
|
|
982
|
-
* @returns
|
|
983
|
-
*/
|
|
984
|
-
const getEnvsWithPrefix = (prefix) => {
|
|
985
|
-
try {
|
|
986
|
-
if (process && process.env) return Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith(prefix)));
|
|
987
|
-
else return {};
|
|
988
|
-
} catch (error) {
|
|
989
|
-
return {};
|
|
990
|
-
}
|
|
991
|
-
};
|
|
992
|
-
|
|
993
|
-
//#endregion
|
|
994
|
-
//#region src/utils/constants.ts
|
|
995
|
-
var constants_exports = /* @__PURE__ */ __export({
|
|
996
|
-
CLIENT_PUSHER_KEY: () => CLIENT_PUSHER_KEY,
|
|
997
|
-
COMPOSIO_DIR: () => COMPOSIO_DIR,
|
|
998
|
-
COMPOSIO_LOG_LEVEL: () => COMPOSIO_LOG_LEVEL,
|
|
999
|
-
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
1000
|
-
DEFAULT_WEB_URL: () => DEFAULT_WEB_URL,
|
|
1001
|
-
IS_DEVELOPMENT_OR_CI: () => IS_DEVELOPMENT_OR_CI,
|
|
1002
|
-
TELEMETRY_URL: () => TELEMETRY_URL$1,
|
|
1003
|
-
TEMP_FILES_DIRECTORY_NAME: () => TEMP_FILES_DIRECTORY_NAME,
|
|
1004
|
-
USER_DATA_FILE_NAME: () => USER_DATA_FILE_NAME
|
|
1005
|
-
});
|
|
1006
|
-
const COMPOSIO_DIR = ".composio";
|
|
1007
|
-
const USER_DATA_FILE_NAME = "user_data.json";
|
|
1008
|
-
const TEMP_FILES_DIRECTORY_NAME = "files";
|
|
1009
|
-
const DEFAULT_BASE_URL = "https://backend.composio.dev";
|
|
1010
|
-
const DEFAULT_WEB_URL = "https://platform.composio.dev";
|
|
1011
|
-
const TELEMETRY_URL$1 = "https://app.composio.dev";
|
|
1012
|
-
const CLIENT_PUSHER_KEY = getEnvVariable("CLIENT_PUSHER_KEY") || "ff9f18c208855d77a152";
|
|
1013
|
-
const COMPOSIO_LOG_LEVEL = getEnvVariable("COMPOSIO_LOG_LEVEL");
|
|
1014
|
-
const IS_DEVELOPMENT_OR_CI = getEnvVariable("DEVELOPMENT") || getEnvVariable("CI") || false;
|
|
1015
|
-
|
|
1016
|
-
//#endregion
|
|
1017
|
-
//#region src/utils/logger.ts
|
|
1018
|
-
const LOG_LEVELS = {
|
|
1019
|
-
silent: -1,
|
|
1020
|
-
error: 0,
|
|
1021
|
-
warn: 1,
|
|
1022
|
-
info: 2,
|
|
1023
|
-
debug: 3
|
|
1024
|
-
};
|
|
1025
|
-
/**
|
|
1026
|
-
* Get the current log level from environment variables.
|
|
1027
|
-
* Defaults to 'info' if not set or invalid.
|
|
1028
|
-
* @returns {LogLevel} The current log level
|
|
1029
|
-
*/
|
|
1030
|
-
const getLogLevel = () => {
|
|
1031
|
-
const envLevel = (COMPOSIO_LOG_LEVEL ?? "info")?.toLowerCase();
|
|
1032
|
-
return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
|
|
1033
|
-
};
|
|
1034
|
-
var Logger = class {
|
|
1035
|
-
level;
|
|
1036
|
-
includeTimestamp;
|
|
1037
|
-
console;
|
|
1038
|
-
constructor(options = {}) {
|
|
1039
|
-
this.level = options.level ?? getLogLevel();
|
|
1040
|
-
this.includeTimestamp = options.includeTimestamp ?? true;
|
|
1041
|
-
this.console = console;
|
|
1042
|
-
}
|
|
1043
|
-
formatMessage(args) {
|
|
1044
|
-
const formattedArgs = args.map((arg, index) => {
|
|
1045
|
-
if (typeof arg === "object") return JSON.stringify(arg);
|
|
1046
|
-
else {
|
|
1047
|
-
if (index === 0) if (args.length > 1) return chalk.default.yellow(`${arg}`);
|
|
1048
|
-
else return String(arg);
|
|
1049
|
-
return String(arg);
|
|
1050
|
-
}
|
|
1051
|
-
}).join("\n");
|
|
1052
|
-
if (!this.includeTimestamp) return formattedArgs;
|
|
1053
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
1054
|
-
return `${chalk.default.gray(timestamp)} - ${formattedArgs}`;
|
|
1055
|
-
}
|
|
1056
|
-
shouldLog(level) {
|
|
1057
|
-
return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
|
|
1058
|
-
}
|
|
1059
|
-
error(...args) {
|
|
1060
|
-
if (this.shouldLog("error")) this.console.error(this.formatMessage(args));
|
|
1061
|
-
}
|
|
1062
|
-
warn(...args) {
|
|
1063
|
-
if (this.shouldLog("warn")) this.console.warn(this.formatMessage(args));
|
|
1064
|
-
}
|
|
1065
|
-
info(...args) {
|
|
1066
|
-
if (this.shouldLog("info")) this.console.info(this.formatMessage(args));
|
|
1067
|
-
}
|
|
1068
|
-
debug(...args) {
|
|
1069
|
-
if (this.shouldLog("debug")) this.console.debug(this.formatMessage(args));
|
|
1070
|
-
}
|
|
1071
|
-
};
|
|
1072
|
-
const logger = new Logger();
|
|
1073
|
-
var logger_default = logger;
|
|
1074
|
-
|
|
1075
|
-
//#endregion
|
|
1076
|
-
//#region src/errors/ComposioError.ts
|
|
1077
|
-
/**
|
|
1078
|
-
* @fileoverview Error class for Composio.
|
|
1079
|
-
*
|
|
1080
|
-
* This error class is used to create custom errors for Composio.
|
|
1081
|
-
* It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
|
|
1082
|
-
*
|
|
1083
|
-
* @author Musthaq Ahamad <musthaq@composio.dev>
|
|
1084
|
-
* @module errors/ComposioError
|
|
1085
|
-
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
|
|
1086
|
-
*/
|
|
1087
|
-
/**
|
|
1088
|
-
* Base error class for all Composio errors
|
|
1089
|
-
*/
|
|
1090
|
-
var ComposioError = class ComposioError extends Error {
|
|
1091
|
-
/** @readonly Error name */
|
|
1092
|
-
name = "ComposioError";
|
|
1093
|
-
code;
|
|
1094
|
-
possibleFixes;
|
|
1095
|
-
errorId;
|
|
1096
|
-
/**
|
|
1097
|
-
* Creates a new ComposioError
|
|
1098
|
-
* @param message Error message
|
|
1099
|
-
* @param options Additional error options
|
|
1100
|
-
*/
|
|
1101
|
-
constructor(message, options = {}) {
|
|
1102
|
-
super(message);
|
|
1103
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
1104
|
-
const statusCode = options.statusCode || (options.cause instanceof __composio_client.BadRequestError ? options.cause.status : void 0);
|
|
1105
|
-
this.code = `TS-SDK::${options.code}`;
|
|
1106
|
-
this.possibleFixes = options.possibleFixes;
|
|
1107
|
-
this.definePropertyIfExists("statusCode", statusCode);
|
|
1108
|
-
this.definePropertyIfExists("cause", options.cause);
|
|
1109
|
-
const combinedStack = options.cause instanceof Error ? ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
|
|
1110
|
-
this.definePropertyIfExists("stack", combinedStack);
|
|
1111
|
-
if (options.meta && Object.keys(options.meta).length > 0) this.definePropertyIfExists("meta", options.meta);
|
|
1112
|
-
}
|
|
1113
|
-
/**
|
|
1114
|
-
* Helper method to define a property only if it has a value
|
|
1115
|
-
* @param propertyName Name of the property to define
|
|
1116
|
-
* @param value Value to assign to the property
|
|
1117
|
-
* @private
|
|
1118
|
-
*/
|
|
1119
|
-
definePropertyIfExists(propertyName, value) {
|
|
1120
|
-
if (value !== void 0) Object.defineProperty(this, propertyName, {
|
|
1121
|
-
value,
|
|
1122
|
-
enumerable: true,
|
|
1123
|
-
writable: false,
|
|
1124
|
-
configurable: true
|
|
1125
|
-
});
|
|
1126
|
-
}
|
|
1127
|
-
/**
|
|
1128
|
-
* Helper method to combine stack traces when wrapping errors
|
|
1129
|
-
* This ensures the full call chain is preserved
|
|
1130
|
-
* @param originalStack The stack of the error being wrapped
|
|
1131
|
-
* @param currentStack The stack of the wrapper error
|
|
1132
|
-
* @returns Combined stack trace
|
|
1133
|
-
* @private
|
|
1134
|
-
*/
|
|
1135
|
-
static combineStackTraces(originalStack, currentStack) {
|
|
1136
|
-
if (!originalStack) return currentStack;
|
|
1137
|
-
if (!currentStack) return originalStack;
|
|
1138
|
-
const currentHeader = currentStack.split("\n")[0];
|
|
1139
|
-
const originalStackBody = originalStack.split("\n").slice(1).join("\n");
|
|
1140
|
-
return `${currentHeader}\n${currentStack.split("\n").slice(1).join("\n")}\n\nCaused by:\n${originalStackBody}`;
|
|
1141
|
-
}
|
|
1142
|
-
/**
|
|
1143
|
-
* Extract and normalize error data for formatting
|
|
1144
|
-
* @param includeStack Whether to include stack trace information
|
|
1145
|
-
* @returns Structured error data for formatting
|
|
1146
|
-
* @private
|
|
1147
|
-
*/
|
|
1148
|
-
getErrorData(includeStack = false) {
|
|
1149
|
-
const data = {
|
|
1150
|
-
name: this.name,
|
|
1151
|
-
message: this.message
|
|
1152
|
-
};
|
|
1153
|
-
const { cause, code, stack, statusCode, meta, possibleFixes } = this;
|
|
1154
|
-
if (cause !== void 0) {
|
|
1155
|
-
const rawCause = cause;
|
|
1156
|
-
data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
|
|
1157
|
-
}
|
|
1158
|
-
if (code) data.code = code;
|
|
1159
|
-
if (statusCode !== void 0) data.statusCode = statusCode;
|
|
1160
|
-
if (meta) data.meta = meta;
|
|
1161
|
-
if (possibleFixes) data.possibleFixes = possibleFixes;
|
|
1162
|
-
if (includeStack && stack) if (stack.includes("Caused by:")) {
|
|
1163
|
-
const [currentStack, causeStack] = stack.split("Caused by:");
|
|
1164
|
-
data.stack = [
|
|
1165
|
-
...currentStack.split("\n").slice(1),
|
|
1166
|
-
"Caused by:",
|
|
1167
|
-
...causeStack.split("\n")
|
|
1168
|
-
];
|
|
1169
|
-
} else data.stack = stack.split("\n").slice(1);
|
|
1170
|
-
return data;
|
|
1171
|
-
}
|
|
1172
|
-
/**
|
|
1173
|
-
* Prints a user-friendly, colorful representation of the error to the logger
|
|
1174
|
-
* @param includeStack Whether to include the stack trace in the output (default: false)
|
|
1175
|
-
*/
|
|
1176
|
-
prettyPrint(includeStack = false) {
|
|
1177
|
-
const data = this.getErrorData(includeStack);
|
|
1178
|
-
let output = "\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(data.message) + "\n";
|
|
1179
|
-
if (data.code) output += chalk.default.yellow(`Error Code: ${data.code}`) + "\n";
|
|
1180
|
-
if (data.statusCode !== void 0) output += chalk.default.yellow(`Status: ${data.statusCode}`) + "\n";
|
|
1181
|
-
if (data.cause) {
|
|
1182
|
-
output += chalk.default.gray("Reason:") + "\n";
|
|
1183
|
-
output += " " + chalk.default.white(data.cause) + "\n";
|
|
1184
|
-
}
|
|
1185
|
-
if (data.meta) {
|
|
1186
|
-
output += chalk.default.gray("Additional Information:") + "\n";
|
|
1187
|
-
output += " " + chalk.default.white(JSON.stringify(data.meta, null, 2).replace(/\n/g, "\n ")) + "\n";
|
|
1188
|
-
}
|
|
1189
|
-
if (data.possibleFixes?.length) {
|
|
1190
|
-
output += "\n" + chalk.default.cyan.bold("Try the following:") + "\n";
|
|
1191
|
-
const fixes = data.possibleFixes?.map((fix, index) => ` ${index + 1}. ` + chalk.default.white(fix));
|
|
1192
|
-
output += fixes?.join("\n") + "\n";
|
|
1193
|
-
}
|
|
1194
|
-
if (data.stack?.length) {
|
|
1195
|
-
output += "\n" + chalk.default.gray("Stack Trace:") + "\n";
|
|
1196
|
-
output += chalk.default.gray(data.stack.join("\n")) + "\n";
|
|
1197
|
-
}
|
|
1198
|
-
output += "\n";
|
|
1199
|
-
logger_default.error(output);
|
|
1200
|
-
}
|
|
1201
|
-
/**
|
|
1202
|
-
* Static factory method to create and pretty print an error in one step
|
|
1203
|
-
* @param message Error message
|
|
1204
|
-
* @param options Error options
|
|
1205
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1206
|
-
* @returns The created error instance
|
|
1207
|
-
*/
|
|
1208
|
-
static createAndPrint(message, options = {}, includeStack = false) {
|
|
1209
|
-
const error = new ComposioError(message, options);
|
|
1210
|
-
error.prettyPrint(includeStack);
|
|
1211
|
-
return error;
|
|
1212
|
-
}
|
|
1213
|
-
/**
|
|
1214
|
-
* Utility function to handle errors in a consistent way
|
|
1215
|
-
* This properly displays the error without throwing
|
|
1216
|
-
* @param error The error to handle
|
|
1217
|
-
* @param options Options for error handling
|
|
1218
|
-
*/
|
|
1219
|
-
static handle(error, options = {}) {
|
|
1220
|
-
const { includeStack = false, exitProcess = false } = options;
|
|
1221
|
-
if (error instanceof ComposioError) error.prettyPrint(includeStack);
|
|
1222
|
-
else if (error instanceof zod_v3.ZodError) this.handleZodError(error, includeStack);
|
|
1223
|
-
else if (error instanceof Error) this.handleStandardError(error, includeStack);
|
|
1224
|
-
else this.handleUnknownError(error);
|
|
1225
|
-
if (exitProcess) this.throwError(error);
|
|
1226
|
-
}
|
|
1227
|
-
/**
|
|
1228
|
-
* Utility function to handle errors and then throw them
|
|
1229
|
-
* This properly displays the error and then throws it, allowing callers to catch it.
|
|
1230
|
-
* Use this for fatal errors that should stop execution.
|
|
1231
|
-
* @param error The error to handle and throw
|
|
1232
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1233
|
-
* @throws ComposioError - Always throws after displaying the error
|
|
1234
|
-
*/
|
|
1235
|
-
static handleAndThrow(error, includeStack = false) {
|
|
1236
|
-
this.handle(error, { includeStack });
|
|
1237
|
-
this.throwError(error);
|
|
1238
|
-
}
|
|
1239
|
-
/**
|
|
1240
|
-
* Helper method to throw an error as a ComposioError
|
|
1241
|
-
* @param error The error to throw
|
|
1242
|
-
* @private
|
|
1243
|
-
*/
|
|
1244
|
-
static throwError(error) {
|
|
1245
|
-
if (error instanceof ComposioError) throw error;
|
|
1246
|
-
else if (error instanceof Error) throw new ComposioError(error.message, { cause: error });
|
|
1247
|
-
else throw new ComposioError(String(error));
|
|
1248
|
-
}
|
|
1249
|
-
/**
|
|
1250
|
-
* Helper method to handle Zod validation errors
|
|
1251
|
-
* @param error The Zod error to handle
|
|
1252
|
-
* @param includeStack Whether to include the stack trace
|
|
1253
|
-
* @private
|
|
1254
|
-
*/
|
|
1255
|
-
static handleZodError(error, includeStack) {
|
|
1256
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(error.message));
|
|
1257
|
-
logger_default.error(chalk.default.gray("Invalid parameters:"));
|
|
1258
|
-
error.errors.forEach((err) => {
|
|
1259
|
-
logger_default.error(chalk.default.yellow(err.path.join(".")) + " " + chalk.default.white(err.message));
|
|
1260
|
-
});
|
|
1261
|
-
logger_default.error(chalk.default.gray("Expected parameters:"));
|
|
1262
|
-
error.errors.forEach((err) => {
|
|
1263
|
-
logger_default.error(chalk.default.yellow(err.path.join(".")) + " " + chalk.default.white(err.message));
|
|
1264
|
-
});
|
|
1265
|
-
if (includeStack) {
|
|
1266
|
-
logger_default.error("\n" + chalk.default.gray("Validation Errors:"));
|
|
1267
|
-
error.errors.forEach((err) => {
|
|
1268
|
-
const path$1 = err.path.join(".");
|
|
1269
|
-
logger_default.error(chalk.default.gray(" • ") + chalk.default.yellow(path$1 ? `${path$1}: ` : "") + chalk.default.white(err.message));
|
|
1270
|
-
});
|
|
1271
|
-
if (error.stack) {
|
|
1272
|
-
logger_default.error("\n" + chalk.default.gray("Stack Trace:"));
|
|
1273
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1274
|
-
logger_default.error(chalk.default.gray(stackLines.join("\n")));
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
logger_default.error("");
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* Helper method to handle standard Error objects
|
|
1281
|
-
* @param error The standard error to handle
|
|
1282
|
-
* @param includeStack Whether to include the stack trace
|
|
1283
|
-
* @private
|
|
1284
|
-
*/
|
|
1285
|
-
static handleStandardError(error, includeStack) {
|
|
1286
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold(error.message));
|
|
1287
|
-
if (includeStack && error.stack) {
|
|
1288
|
-
logger_default.error("\n" + chalk.default.gray("Stack Trace:"));
|
|
1289
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1290
|
-
logger_default.error(chalk.default.gray(stackLines.join("\n")));
|
|
1291
|
-
}
|
|
1292
|
-
logger_default.error("");
|
|
1293
|
-
}
|
|
1294
|
-
/**
|
|
1295
|
-
* Helper method to handle unknown error types
|
|
1296
|
-
* @param error The unknown error value
|
|
1297
|
-
* @private
|
|
1298
|
-
*/
|
|
1299
|
-
static handleUnknownError(error) {
|
|
1300
|
-
logger_default.error("\n" + chalk.default.bgRed.white.bold(" ERROR ") + " " + chalk.default.white.bold("Unknown error occurred"));
|
|
1301
|
-
if (error !== null && error !== void 0) {
|
|
1302
|
-
logger_default.error(chalk.default.gray("Error details:"));
|
|
1303
|
-
logger_default.error(" " + chalk.default.white(String(error)));
|
|
1304
|
-
}
|
|
1305
|
-
logger_default.error("");
|
|
1306
|
-
}
|
|
1307
|
-
};
|
|
1308
|
-
|
|
1309
922
|
//#endregion
|
|
1310
923
|
//#region src/errors/ConnectedAccountsErrors.ts
|
|
1311
924
|
const ConnectedAccountErrorCodes = {
|
|
@@ -1313,7 +926,7 @@ const ConnectedAccountErrorCodes = {
|
|
|
1313
926
|
MULTIPLE_CONNECTED_ACCOUNTS: "MULTIPLE_CONNECTED_ACCOUNTS",
|
|
1314
927
|
FAILED_TO_CREATE_CONNECTED_ACCOUNT_LINK: "FAILED_TO_CREATE_CONNECTED_ACCOUNT_LINK"
|
|
1315
928
|
};
|
|
1316
|
-
var ComposioConnectedAccountNotFoundError = class extends ComposioError {
|
|
929
|
+
var ComposioConnectedAccountNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1317
930
|
constructor(message = "Connected account not found", options = {}) {
|
|
1318
931
|
super(message, {
|
|
1319
932
|
...options,
|
|
@@ -1324,7 +937,7 @@ var ComposioConnectedAccountNotFoundError = class extends ComposioError {
|
|
|
1324
937
|
this.name = "ComposioConnectedAccountNotFoundError";
|
|
1325
938
|
}
|
|
1326
939
|
};
|
|
1327
|
-
var ComposioMultipleConnectedAccountsError = class extends ComposioError {
|
|
940
|
+
var ComposioMultipleConnectedAccountsError = class extends require_fileUtils.ComposioError {
|
|
1328
941
|
constructor(message = "Multiple connected accounts found", options = {}) {
|
|
1329
942
|
super(message, {
|
|
1330
943
|
...options,
|
|
@@ -1334,7 +947,7 @@ var ComposioMultipleConnectedAccountsError = class extends ComposioError {
|
|
|
1334
947
|
this.name = "ComposioMultipleConnectedAccountsError";
|
|
1335
948
|
}
|
|
1336
949
|
};
|
|
1337
|
-
var ComposioFailedToCreateConnectedAccountLink = class extends ComposioError {
|
|
950
|
+
var ComposioFailedToCreateConnectedAccountLink = class extends require_fileUtils.ComposioError {
|
|
1338
951
|
constructor(message = "Failed to create connected account link", options = {}) {
|
|
1339
952
|
super(message, {
|
|
1340
953
|
...options,
|
|
@@ -1356,7 +969,7 @@ const ToolErrorCodes = {
|
|
|
1356
969
|
GLOBAL_EXECUTE_TOOL_FN_NOT_SET: "GLOBAL_EXECUTE_TOOL_FN_NOT_SET",
|
|
1357
970
|
TOOL_VERSION_REQUIRED: "TOOL_VERSION_REQUIRED"
|
|
1358
971
|
};
|
|
1359
|
-
var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
972
|
+
var ComposioProviderNotDefinedError = class extends require_fileUtils.ComposioError {
|
|
1360
973
|
constructor(message = "Provider not defined", options = {}) {
|
|
1361
974
|
super(message, {
|
|
1362
975
|
...options,
|
|
@@ -1366,7 +979,7 @@ var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
|
1366
979
|
this.name = "ComposioProviderNotDefinedError";
|
|
1367
980
|
}
|
|
1368
981
|
};
|
|
1369
|
-
var ComposioToolNotFoundError = class extends ComposioError {
|
|
982
|
+
var ComposioToolNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1370
983
|
constructor(message = "Tool not found", options = {}) {
|
|
1371
984
|
super(message, {
|
|
1372
985
|
...options,
|
|
@@ -1376,7 +989,7 @@ var ComposioToolNotFoundError = class extends ComposioError {
|
|
|
1376
989
|
this.name = "ComposioToolNotFoundError";
|
|
1377
990
|
}
|
|
1378
991
|
};
|
|
1379
|
-
var ComposioInvalidModifierError = class extends ComposioError {
|
|
992
|
+
var ComposioInvalidModifierError = class extends require_fileUtils.ComposioError {
|
|
1380
993
|
constructor(message = "Invalid modifier", options = {}) {
|
|
1381
994
|
super(message, {
|
|
1382
995
|
...options,
|
|
@@ -1386,7 +999,7 @@ var ComposioInvalidModifierError = class extends ComposioError {
|
|
|
1386
999
|
this.name = "ComposioInvalidModifierError";
|
|
1387
1000
|
}
|
|
1388
1001
|
};
|
|
1389
|
-
var ComposioCustomToolsNotInitializedError = class extends ComposioError {
|
|
1002
|
+
var ComposioCustomToolsNotInitializedError = class extends require_fileUtils.ComposioError {
|
|
1390
1003
|
constructor(message = "Custom tools not initialized", options = {}) {
|
|
1391
1004
|
super(message, {
|
|
1392
1005
|
...options,
|
|
@@ -1396,7 +1009,7 @@ var ComposioCustomToolsNotInitializedError = class extends ComposioError {
|
|
|
1396
1009
|
this.name = "ComposioCustomToolsNotInitializedError";
|
|
1397
1010
|
}
|
|
1398
1011
|
};
|
|
1399
|
-
var ComposioToolExecutionError = class extends ComposioError {
|
|
1012
|
+
var ComposioToolExecutionError = class extends require_fileUtils.ComposioError {
|
|
1400
1013
|
constructor(message = "Tool execution error", options = {}) {
|
|
1401
1014
|
super(message, {
|
|
1402
1015
|
...options,
|
|
@@ -1407,7 +1020,7 @@ var ComposioToolExecutionError = class extends ComposioError {
|
|
|
1407
1020
|
this.name = "ComposioToolExecutionError";
|
|
1408
1021
|
}
|
|
1409
1022
|
};
|
|
1410
|
-
var ComposioInvalidExecuteFunctionError = class extends ComposioError {
|
|
1023
|
+
var ComposioInvalidExecuteFunctionError = class extends require_fileUtils.ComposioError {
|
|
1411
1024
|
constructor(message = "Invalid execute function", options = {}) {
|
|
1412
1025
|
super(message, {
|
|
1413
1026
|
...options,
|
|
@@ -1417,7 +1030,7 @@ var ComposioInvalidExecuteFunctionError = class extends ComposioError {
|
|
|
1417
1030
|
this.name = "ComposioInvalidExecuteFunctionError";
|
|
1418
1031
|
}
|
|
1419
1032
|
};
|
|
1420
|
-
var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
|
|
1033
|
+
var ComposioGlobalExecuteToolFnNotSetError = class extends require_fileUtils.ComposioError {
|
|
1421
1034
|
constructor(message = "Global execute tool function not set", options = {}) {
|
|
1422
1035
|
super(message, {
|
|
1423
1036
|
...options,
|
|
@@ -1490,7 +1103,7 @@ var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
|
|
|
1490
1103
|
* });
|
|
1491
1104
|
* ```
|
|
1492
1105
|
*/
|
|
1493
|
-
var ComposioToolVersionRequiredError = class extends ComposioError {
|
|
1106
|
+
var ComposioToolVersionRequiredError = class extends require_fileUtils.ComposioError {
|
|
1494
1107
|
constructor(message = "Toolkit version not specified. For manual execution of the tool please pass a specific toolkit version", options = {}) {
|
|
1495
1108
|
super(message, {
|
|
1496
1109
|
...options,
|
|
@@ -1506,7 +1119,7 @@ var ComposioToolVersionRequiredError = class extends ComposioError {
|
|
|
1506
1119
|
};
|
|
1507
1120
|
const ERROR_CODE_HANDLERS = new Map([[1803, (msg) => new ComposioConnectedAccountNotFoundError(msg)]]);
|
|
1508
1121
|
const handleToolExecutionError = (tool, actualError) => {
|
|
1509
|
-
if (actualError instanceof
|
|
1122
|
+
if (actualError instanceof _composio_client.APIError && actualError.error) {
|
|
1510
1123
|
const errorBody = actualError.error;
|
|
1511
1124
|
const errorCode = errorBody?.error?.code;
|
|
1512
1125
|
const errorMessage = errorBody?.error?.message;
|
|
@@ -1518,294 +1131,10 @@ const handleToolExecutionError = (tool, actualError) => {
|
|
|
1518
1131
|
});
|
|
1519
1132
|
};
|
|
1520
1133
|
|
|
1521
|
-
//#endregion
|
|
1522
|
-
//#region src/types/telemetry.types.ts
|
|
1523
|
-
const TELEMETRY_EVENTS = {
|
|
1524
|
-
SDK_INITIALIZED: "SDK_INITIALIZED",
|
|
1525
|
-
SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
|
|
1526
|
-
SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
|
|
1527
|
-
CLI_INVOKED: "CLI_INVOKED"
|
|
1528
|
-
};
|
|
1529
|
-
|
|
1530
|
-
//#endregion
|
|
1531
|
-
//#region src/telemetry/BatchProcessor.ts
|
|
1532
|
-
var BatchProcessor = class {
|
|
1533
|
-
batch = [];
|
|
1534
|
-
time;
|
|
1535
|
-
batchSize;
|
|
1536
|
-
processBatchCallback;
|
|
1537
|
-
timer = null;
|
|
1538
|
-
constructor(time = 2e3, batchSize = 100, processBatchCallback) {
|
|
1539
|
-
this.batch = [];
|
|
1540
|
-
this.time = time;
|
|
1541
|
-
this.batchSize = batchSize;
|
|
1542
|
-
this.processBatchCallback = processBatchCallback;
|
|
1543
|
-
}
|
|
1544
|
-
pushItem(item) {
|
|
1545
|
-
this.batch.push(item);
|
|
1546
|
-
if (this.batch.length >= this.batchSize) this.processBatch();
|
|
1547
|
-
else if (!this.timer) this.timer = setTimeout(() => this.processBatch(), this.time);
|
|
1548
|
-
}
|
|
1549
|
-
processBatch() {
|
|
1550
|
-
if (this.batch.length > 0) {
|
|
1551
|
-
this.processBatchCallback(this.batch);
|
|
1552
|
-
this.batch = [];
|
|
1553
|
-
}
|
|
1554
|
-
if (this.timer) {
|
|
1555
|
-
clearTimeout(this.timer);
|
|
1556
|
-
this.timer = null;
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
};
|
|
1560
|
-
|
|
1561
|
-
//#endregion
|
|
1562
|
-
//#region src/utils/uuid.ts
|
|
1563
|
-
function getRandomUUID() {
|
|
1564
|
-
return (0, uuid.v4)();
|
|
1565
|
-
}
|
|
1566
|
-
function getRandomShortId() {
|
|
1567
|
-
return getRandomUUID().slice(0, 8).replace(/-/g, "");
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
//#endregion
|
|
1571
|
-
//#region src/services/telemetry/TelemetryService.ts
|
|
1572
|
-
const TELEMETRY_URL = "https://telemetry.composio.dev/v1";
|
|
1573
|
-
var TelemetryService = class {
|
|
1574
|
-
/**
|
|
1575
|
-
* Sends a metric to the Telemetry API.
|
|
1576
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1577
|
-
* @returns The response from the Telemetry API.
|
|
1578
|
-
*/
|
|
1579
|
-
static async sendMetric(payload) {
|
|
1580
|
-
try {
|
|
1581
|
-
return await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
|
|
1582
|
-
method: "POST",
|
|
1583
|
-
headers: { "Content-Type": "application/json" },
|
|
1584
|
-
body: JSON.stringify(payload)
|
|
1585
|
-
});
|
|
1586
|
-
} catch (error) {
|
|
1587
|
-
logger_default.debug("Error sending metric telemetry", error);
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
/**
|
|
1591
|
-
* Sends an error log to the Telemetry API.
|
|
1592
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1593
|
-
* @returns The response from the Telemetry API.
|
|
1594
|
-
*/
|
|
1595
|
-
static async sendErrorLog(payload) {
|
|
1596
|
-
try {
|
|
1597
|
-
return await fetch(`${TELEMETRY_URL}/errors`, {
|
|
1598
|
-
method: "POST",
|
|
1599
|
-
headers: { "Content-Type": "application/json" },
|
|
1600
|
-
body: JSON.stringify(payload)
|
|
1601
|
-
});
|
|
1602
|
-
} catch (error) {
|
|
1603
|
-
logger_default.debug("Error sending error telemetry", error);
|
|
1604
|
-
}
|
|
1605
|
-
}
|
|
1606
|
-
};
|
|
1607
|
-
|
|
1608
|
-
//#endregion
|
|
1609
|
-
//#region src/telemetry/Telemetry.ts
|
|
1610
|
-
/**
|
|
1611
|
-
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
|
|
1612
|
-
*
|
|
1613
|
-
* This class is used to instrument the telemetry for the given instance and send the telemetry to the server.
|
|
1614
|
-
* This class is also used to create a global error handler for the given instance.
|
|
1615
|
-
*
|
|
1616
|
-
* @example
|
|
1617
|
-
*
|
|
1618
|
-
* const telemetry = new Telemetry({...});
|
|
1619
|
-
* const composio = new Composio({...})
|
|
1620
|
-
*
|
|
1621
|
-
* telemetry.instrument(composio);
|
|
1622
|
-
* telemetry.instrument(composio.tools);
|
|
1623
|
-
* telemetry.instrument(composio.toolkits);
|
|
1624
|
-
* telemetry.instrument(composio.triggers);
|
|
1625
|
-
*
|
|
1626
|
-
*/
|
|
1627
|
-
var TelemetryTransport = class {
|
|
1628
|
-
telemetryMetadata;
|
|
1629
|
-
isTelemetryDisabled = true;
|
|
1630
|
-
telemetrySource;
|
|
1631
|
-
telemetrySourceName = "typescript-sdk";
|
|
1632
|
-
telemetryServiceName = "sdk";
|
|
1633
|
-
telemetryLanguage = "typescript";
|
|
1634
|
-
batchProcessor = new BatchProcessor(200, 10, async (data) => {
|
|
1635
|
-
logger_default.debug("Sending batch of telemetry metrics", data);
|
|
1636
|
-
await TelemetryService.sendMetric(data);
|
|
1637
|
-
});
|
|
1638
|
-
setup(metadata) {
|
|
1639
|
-
this.telemetryMetadata = metadata;
|
|
1640
|
-
this.isTelemetryDisabled = false;
|
|
1641
|
-
this.telemetrySource = {
|
|
1642
|
-
host: this.telemetryMetadata?.host ?? this.telemetrySourceName,
|
|
1643
|
-
service: this.telemetryServiceName,
|
|
1644
|
-
language: this.telemetryLanguage,
|
|
1645
|
-
version: this.telemetryMetadata?.version,
|
|
1646
|
-
platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
|
|
1647
|
-
environment: getEnvVariable("NODE_ENV", "production")
|
|
1648
|
-
};
|
|
1649
|
-
this.sendMetric([{
|
|
1650
|
-
functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
|
|
1651
|
-
durationMs: 0,
|
|
1652
|
-
timestamp: Date.now() / 1e3,
|
|
1653
|
-
props: {},
|
|
1654
|
-
source: this.telemetrySource,
|
|
1655
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1656
|
-
error: void 0
|
|
1657
|
-
}]);
|
|
1658
|
-
}
|
|
1659
|
-
/**
|
|
1660
|
-
* Instrument the telemetry for the given instance.
|
|
1661
|
-
*
|
|
1662
|
-
* You can pass the instance and the file name of the instance to instrument the telemetry.
|
|
1663
|
-
* This will instrument all the methods of the instance and log the telemetry for each method call.
|
|
1664
|
-
* @param instance - any instance that extends InstrumentedInstance
|
|
1665
|
-
* @param fileName - the file name of the instance
|
|
1666
|
-
* @returns
|
|
1667
|
-
*/
|
|
1668
|
-
instrument(instance, fileName) {
|
|
1669
|
-
const proto = Object.getPrototypeOf(instance);
|
|
1670
|
-
const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
|
|
1671
|
-
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
1672
|
-
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
1673
|
-
});
|
|
1674
|
-
const instrumentedClassName = fileName ?? instance.constructor?.name ?? "unknown";
|
|
1675
|
-
for (const name of methodNames) {
|
|
1676
|
-
const originalMethod = instance[name];
|
|
1677
|
-
instance[name] = async (...args) => {
|
|
1678
|
-
const telemetryEnabled = this.shouldSendTelemetry();
|
|
1679
|
-
const startTime = telemetryEnabled ? Date.now() : void 0;
|
|
1680
|
-
try {
|
|
1681
|
-
const result = await originalMethod.apply(instance, args);
|
|
1682
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1683
|
-
const durationMs = Date.now() - startTime;
|
|
1684
|
-
const telemetryPayload = {
|
|
1685
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1686
|
-
durationMs,
|
|
1687
|
-
timestamp: startTime / 1e3,
|
|
1688
|
-
props: {
|
|
1689
|
-
fileName: instrumentedClassName,
|
|
1690
|
-
method: name,
|
|
1691
|
-
params: args
|
|
1692
|
-
},
|
|
1693
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1694
|
-
error: void 0,
|
|
1695
|
-
source: this.telemetrySource
|
|
1696
|
-
};
|
|
1697
|
-
this.batchProcessor.pushItem(telemetryPayload);
|
|
1698
|
-
}
|
|
1699
|
-
return result;
|
|
1700
|
-
} catch (error) {
|
|
1701
|
-
if (error instanceof Error) {
|
|
1702
|
-
if (!error.errorId) {
|
|
1703
|
-
error.errorId = getRandomUUID();
|
|
1704
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1705
|
-
const durationMs = Date.now() - startTime;
|
|
1706
|
-
await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs);
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
throw error;
|
|
1711
|
-
}
|
|
1712
|
-
};
|
|
1713
|
-
}
|
|
1714
|
-
return instance;
|
|
1715
|
-
}
|
|
1716
|
-
/**
|
|
1717
|
-
* Check if the telemetry should be sent.
|
|
1718
|
-
* @returns true if the telemetry should be sent, false otherwise
|
|
1719
|
-
*/
|
|
1720
|
-
shouldSendTelemetry() {
|
|
1721
|
-
const telemetryDisabledEnvironments = ["test", "ci"];
|
|
1722
|
-
const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
|
|
1723
|
-
const isDisabledEnvironment = telemetryDisabledEnvironments.includes(nodeEnv);
|
|
1724
|
-
const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
|
|
1725
|
-
return !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDisabledEnvironment;
|
|
1726
|
-
}
|
|
1727
|
-
/**
|
|
1728
|
-
* Prepare and send the error telemetry.
|
|
1729
|
-
*
|
|
1730
|
-
* @TODO This currently blocks the thread and sends the telemetry to the server.
|
|
1731
|
-
*
|
|
1732
|
-
* @param {unknown} error - The error to send.
|
|
1733
|
-
* @param {string} instrumentedClassName - The class name of the instrumented class.
|
|
1734
|
-
* @param {string} name - The name of the method that threw the error.
|
|
1735
|
-
* @param {unknown[]} args - The arguments passed to the method.
|
|
1736
|
-
* @param {number} startTime - The start time of the method invocation in milliseconds.
|
|
1737
|
-
* @param {number} durationMs - The duration of the method invocation in milliseconds.
|
|
1738
|
-
*/
|
|
1739
|
-
async prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs) {
|
|
1740
|
-
const telemetryPayload = {
|
|
1741
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1742
|
-
durationMs,
|
|
1743
|
-
timestamp: startTime / 1e3,
|
|
1744
|
-
props: {
|
|
1745
|
-
fileName: instrumentedClassName,
|
|
1746
|
-
method: name,
|
|
1747
|
-
params: args
|
|
1748
|
-
},
|
|
1749
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1750
|
-
source: this.telemetrySource
|
|
1751
|
-
};
|
|
1752
|
-
if (error instanceof __composio_client.ComposioError) telemetryPayload.error = {
|
|
1753
|
-
errorId: error.errorId,
|
|
1754
|
-
name: error.name,
|
|
1755
|
-
message: error.message,
|
|
1756
|
-
stack: error.stack
|
|
1757
|
-
};
|
|
1758
|
-
else if (error instanceof ComposioError) telemetryPayload.error = {
|
|
1759
|
-
errorId: error.errorId,
|
|
1760
|
-
name: error.name,
|
|
1761
|
-
code: error.code,
|
|
1762
|
-
message: error.message,
|
|
1763
|
-
stack: error.stack
|
|
1764
|
-
};
|
|
1765
|
-
else if (error instanceof Error) telemetryPayload.error = {
|
|
1766
|
-
errorId: error.errorId,
|
|
1767
|
-
name: error.name ?? "Unknown error",
|
|
1768
|
-
message: error.message,
|
|
1769
|
-
stack: error.stack
|
|
1770
|
-
};
|
|
1771
|
-
await this.sendErrorTelemetry(telemetryPayload);
|
|
1772
|
-
}
|
|
1773
|
-
/**
|
|
1774
|
-
* Send the telemetry payload to the server.
|
|
1775
|
-
* @param payload - the telemetry payload to send
|
|
1776
|
-
* @returns
|
|
1777
|
-
*/
|
|
1778
|
-
async sendMetric(payload) {
|
|
1779
|
-
if (!this.shouldSendTelemetry()) {
|
|
1780
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1781
|
-
return;
|
|
1782
|
-
}
|
|
1783
|
-
try {
|
|
1784
|
-
logger_default.debug("SDK Metric", payload);
|
|
1785
|
-
await TelemetryService.sendMetric(payload);
|
|
1786
|
-
} catch (error) {
|
|
1787
|
-
logger_default.error("Error sending metric telemetry", error);
|
|
1788
|
-
}
|
|
1789
|
-
}
|
|
1790
|
-
async sendErrorTelemetry(payload) {
|
|
1791
|
-
if (!this.shouldSendTelemetry()) {
|
|
1792
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1793
|
-
return;
|
|
1794
|
-
}
|
|
1795
|
-
try {
|
|
1796
|
-
logger_default.debug("SDK Error Telemetry", payload);
|
|
1797
|
-
await TelemetryService.sendErrorLog(payload);
|
|
1798
|
-
} catch (error) {
|
|
1799
|
-
logger_default.error("Error sending error telemetry", error);
|
|
1800
|
-
}
|
|
1801
|
-
}
|
|
1802
|
-
};
|
|
1803
|
-
const telemetry = new TelemetryTransport();
|
|
1804
|
-
|
|
1805
1134
|
//#endregion
|
|
1806
1135
|
//#region src/errors/AuthConfigErrors.ts
|
|
1807
1136
|
const AuthConfigErrorCodes = { AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND" };
|
|
1808
|
-
var ComposioAuthConfigNotFoundError = class extends ComposioError {
|
|
1137
|
+
var ComposioAuthConfigNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1809
1138
|
constructor(message = "Auth config not found", options = {}) {
|
|
1810
1139
|
super(message, {
|
|
1811
1140
|
...options,
|
|
@@ -1826,7 +1155,7 @@ const ConnectionRequestErrorCodes = {
|
|
|
1826
1155
|
CONNECTION_REQUEST_TIMEOUT: "CONNECTION_REQUEST_TIMEOUT",
|
|
1827
1156
|
CONNECTION_REQUEST_FAILED: "CONNECTION_REQUEST_FAILED"
|
|
1828
1157
|
};
|
|
1829
|
-
var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
1158
|
+
var ConnectionRequestTimeoutError = class extends require_fileUtils.ComposioError {
|
|
1830
1159
|
constructor(message = "Connection request timed out", options = {}) {
|
|
1831
1160
|
super(message, {
|
|
1832
1161
|
...options,
|
|
@@ -1835,7 +1164,7 @@ var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
|
1835
1164
|
this.name = "ConnectionRequestTimeoutError";
|
|
1836
1165
|
}
|
|
1837
1166
|
};
|
|
1838
|
-
var ConnectionRequestFailedError = class extends ComposioError {
|
|
1167
|
+
var ConnectionRequestFailedError = class extends require_fileUtils.ComposioError {
|
|
1839
1168
|
constructor(message = "Connection request failed", options = {}) {
|
|
1840
1169
|
super(message, {
|
|
1841
1170
|
...options,
|
|
@@ -1848,7 +1177,7 @@ var ConnectionRequestFailedError = class extends ComposioError {
|
|
|
1848
1177
|
//#endregion
|
|
1849
1178
|
//#region src/errors/ToolkitErrors.ts
|
|
1850
1179
|
const ToolkitErrorCodes = { TOOLKIT_NOT_FOUND: "TOOLKIT_NOT_FOUND" };
|
|
1851
|
-
var ComposioToolkitNotFoundError = class extends ComposioError {
|
|
1180
|
+
var ComposioToolkitNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1852
1181
|
constructor(message = "Toolkit not found", options = {}) {
|
|
1853
1182
|
super(message, {
|
|
1854
1183
|
...options,
|
|
@@ -1858,7 +1187,7 @@ var ComposioToolkitNotFoundError = class extends ComposioError {
|
|
|
1858
1187
|
this.name = "ComposioToolkitNotFoundError";
|
|
1859
1188
|
}
|
|
1860
1189
|
};
|
|
1861
|
-
var ComposioToolkitFetchError = class extends ComposioError {
|
|
1190
|
+
var ComposioToolkitFetchError = class extends require_fileUtils.ComposioError {
|
|
1862
1191
|
constructor(message = "Failed to fetch toolkit", options = {}) {
|
|
1863
1192
|
super(message, {
|
|
1864
1193
|
...options,
|
|
@@ -1882,7 +1211,7 @@ const ValidationErrorCodes = {
|
|
|
1882
1211
|
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
1883
1212
|
JSON_SCHEMA_TO_ZOD_ERROR: "JSON_SCHEMA_TO_ZOD_ERROR"
|
|
1884
1213
|
};
|
|
1885
|
-
var ValidationError = class extends ComposioError {
|
|
1214
|
+
var ValidationError = class extends require_fileUtils.ComposioError {
|
|
1886
1215
|
constructor(message = "Input validation failed", options = {}) {
|
|
1887
1216
|
const { cause: providedZodError, ...restOptions } = options;
|
|
1888
1217
|
let zodErrorInstance;
|
|
@@ -1912,7 +1241,7 @@ var ValidationError = class extends ComposioError {
|
|
|
1912
1241
|
return "Please check your input parameters";
|
|
1913
1242
|
}
|
|
1914
1243
|
};
|
|
1915
|
-
var JsonSchemaToZodError = class extends ComposioError {
|
|
1244
|
+
var JsonSchemaToZodError = class extends require_fileUtils.ComposioError {
|
|
1916
1245
|
constructor(message = "Failed to convert JSON schema to Zod schema", options = {}) {
|
|
1917
1246
|
super(message, {
|
|
1918
1247
|
...options,
|
|
@@ -1924,7 +1253,7 @@ var JsonSchemaToZodError = class extends ComposioError {
|
|
|
1924
1253
|
//#endregion
|
|
1925
1254
|
//#region src/errors/SDKErrors.ts
|
|
1926
1255
|
const SDKErrorCodes = { NO_API_KEY_PROVIDED: "NO_API_KEY_PROVIDED" };
|
|
1927
|
-
var ComposioNoAPIKeyError = class extends ComposioError {
|
|
1256
|
+
var ComposioNoAPIKeyError = class extends require_fileUtils.ComposioError {
|
|
1928
1257
|
constructor(message = "No Composio API key provided", options = {}) {
|
|
1929
1258
|
const defaultCause = "Couldn't find an API key in the params, environment variables or in the user config file";
|
|
1930
1259
|
super(message, {
|
|
@@ -1953,7 +1282,7 @@ const TriggerErrorCodes = {
|
|
|
1953
1282
|
WEBHOOK_SIGNATURE_VERIFICATION_FAILED: "WEBHOOK_SIGNATURE_VERIFICATION_FAILED",
|
|
1954
1283
|
WEBHOOK_PAYLOAD_INVALID: "WEBHOOK_PAYLOAD_INVALID"
|
|
1955
1284
|
};
|
|
1956
|
-
var ComposioFailedToGetSDKRealtimeCredentialsError = class extends ComposioError {
|
|
1285
|
+
var ComposioFailedToGetSDKRealtimeCredentialsError = class extends require_fileUtils.ComposioError {
|
|
1957
1286
|
constructor(message = "Failed to get SDK realtime credentials", options = {}) {
|
|
1958
1287
|
super(message, {
|
|
1959
1288
|
...options,
|
|
@@ -1963,7 +1292,7 @@ var ComposioFailedToGetSDKRealtimeCredentialsError = class extends ComposioError
|
|
|
1963
1292
|
this.name = "ComposioFailedToGetSDKRealtimeCredentialsError";
|
|
1964
1293
|
}
|
|
1965
1294
|
};
|
|
1966
|
-
var ComposioFailedToCreatePusherClientError = class extends ComposioError {
|
|
1295
|
+
var ComposioFailedToCreatePusherClientError = class extends require_fileUtils.ComposioError {
|
|
1967
1296
|
constructor(message = "Failed to create Pusher client", options = {}) {
|
|
1968
1297
|
super(message, {
|
|
1969
1298
|
...options,
|
|
@@ -1973,7 +1302,7 @@ var ComposioFailedToCreatePusherClientError = class extends ComposioError {
|
|
|
1973
1302
|
this.name = "ComposioFailedToCreatePusherClientError";
|
|
1974
1303
|
}
|
|
1975
1304
|
};
|
|
1976
|
-
var ComposioFailedToSubscribeToPusherChannelError = class extends ComposioError {
|
|
1305
|
+
var ComposioFailedToSubscribeToPusherChannelError = class extends require_fileUtils.ComposioError {
|
|
1977
1306
|
constructor(message = "Failed to subscribe to Pusher channel", options = {}) {
|
|
1978
1307
|
super(message, {
|
|
1979
1308
|
...options,
|
|
@@ -1983,7 +1312,7 @@ var ComposioFailedToSubscribeToPusherChannelError = class extends ComposioError
|
|
|
1983
1312
|
this.name = "ComposioFailedToSubscribeToPusherChannelError";
|
|
1984
1313
|
}
|
|
1985
1314
|
};
|
|
1986
|
-
var ComposioFailedToUnsubscribeFromPusherChannelError = class extends ComposioError {
|
|
1315
|
+
var ComposioFailedToUnsubscribeFromPusherChannelError = class extends require_fileUtils.ComposioError {
|
|
1987
1316
|
constructor(message = "Failed to unsubscribe from Pusher channel", options = {}) {
|
|
1988
1317
|
super(message, {
|
|
1989
1318
|
...options,
|
|
@@ -1993,7 +1322,7 @@ var ComposioFailedToUnsubscribeFromPusherChannelError = class extends ComposioEr
|
|
|
1993
1322
|
this.name = "ComposioFailedToUnsubscribeFromPusherChannelError";
|
|
1994
1323
|
}
|
|
1995
1324
|
};
|
|
1996
|
-
var ComposioTriggerTypeNotFoundError = class extends ComposioError {
|
|
1325
|
+
var ComposioTriggerTypeNotFoundError = class extends require_fileUtils.ComposioError {
|
|
1997
1326
|
constructor(message = "Trigger type not found", options = {}) {
|
|
1998
1327
|
super(message, {
|
|
1999
1328
|
...options,
|
|
@@ -2004,7 +1333,7 @@ var ComposioTriggerTypeNotFoundError = class extends ComposioError {
|
|
|
2004
1333
|
this.name = "ComposioTriggerTypeNotFoundError";
|
|
2005
1334
|
}
|
|
2006
1335
|
};
|
|
2007
|
-
var ComposioWebhookSignatureVerificationError = class extends ComposioError {
|
|
1336
|
+
var ComposioWebhookSignatureVerificationError = class extends require_fileUtils.ComposioError {
|
|
2008
1337
|
constructor(message = "Webhook signature verification failed", options = {}) {
|
|
2009
1338
|
super(message, {
|
|
2010
1339
|
...options,
|
|
@@ -2019,7 +1348,7 @@ var ComposioWebhookSignatureVerificationError = class extends ComposioError {
|
|
|
2019
1348
|
this.name = "ComposioWebhookSignatureVerificationError";
|
|
2020
1349
|
}
|
|
2021
1350
|
};
|
|
2022
|
-
var ComposioWebhookPayloadError = class extends ComposioError {
|
|
1351
|
+
var ComposioWebhookPayloadError = class extends require_fileUtils.ComposioError {
|
|
2023
1352
|
constructor(message = "Invalid webhook payload", options = {}) {
|
|
2024
1353
|
super(message, {
|
|
2025
1354
|
...options,
|
|
@@ -2126,7 +1455,7 @@ function transform(raw) {
|
|
|
2126
1455
|
const transformed = transformer(raw);
|
|
2127
1456
|
const result = schema.safeParse(transformed);
|
|
2128
1457
|
if (!result.success) {
|
|
2129
|
-
logger_default.error(result.error);
|
|
1458
|
+
require_fileUtils.logger_default.error(result.error);
|
|
2130
1459
|
return transformed;
|
|
2131
1460
|
}
|
|
2132
1461
|
return result.data;
|
|
@@ -2153,7 +1482,7 @@ function transformConnectedAccountResponse(response) {
|
|
|
2153
1482
|
try {
|
|
2154
1483
|
return state ? ConnectionDataSchema.parse(state) : void 0;
|
|
2155
1484
|
} catch (error) {
|
|
2156
|
-
logger_default.warn("Unsupported auth scheme in connected account state, ignoring state field", { error });
|
|
1485
|
+
require_fileUtils.logger_default.warn("Unsupported auth scheme in connected account state, ignoring state field", { error });
|
|
2157
1486
|
return;
|
|
2158
1487
|
}
|
|
2159
1488
|
};
|
|
@@ -2201,10 +1530,10 @@ var CustomTools = class {
|
|
|
2201
1530
|
client;
|
|
2202
1531
|
customToolsRegistry;
|
|
2203
1532
|
constructor(client) {
|
|
2204
|
-
if (!client) throw new ComposioError("ComposioClient is required");
|
|
1533
|
+
if (!client) throw new require_fileUtils.ComposioError("ComposioClient is required");
|
|
2205
1534
|
this.client = client;
|
|
2206
1535
|
this.customToolsRegistry = /* @__PURE__ */ new Map();
|
|
2207
|
-
telemetry.instrument(this, "CustomTools");
|
|
1536
|
+
require_fileUtils.telemetry.instrument(this, "CustomTools");
|
|
2208
1537
|
}
|
|
2209
1538
|
/**
|
|
2210
1539
|
* Create a custom tool and registers it in the registry.
|
|
@@ -2309,7 +1638,7 @@ var CustomTools = class {
|
|
|
2309
1638
|
try {
|
|
2310
1639
|
return this.customToolsRegistry.get(slug.toLowerCase())?.schema;
|
|
2311
1640
|
} catch (error) {
|
|
2312
|
-
logger_default.error(`Error getting custom tool: ${error}`);
|
|
1641
|
+
require_fileUtils.logger_default.error(`Error getting custom tool: ${error}`);
|
|
2313
1642
|
return;
|
|
2314
1643
|
}
|
|
2315
1644
|
}
|
|
@@ -2355,7 +1684,7 @@ var CustomTools = class {
|
|
|
2355
1684
|
let connectedAccountId = body.connectedAccountId;
|
|
2356
1685
|
if (toolkitSlug && toolkitSlug !== "custom" && body.userId) {
|
|
2357
1686
|
const connectedAccount = await this.getConnectedAccountForToolkit(toolkitSlug, body.userId, body.connectedAccountId);
|
|
2358
|
-
logger_default.debug(`[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`, JSON.stringify(connectedAccount, null, 2));
|
|
1687
|
+
require_fileUtils.logger_default.debug(`[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`, JSON.stringify(connectedAccount, null, 2));
|
|
2359
1688
|
if (!connectedAccount) throw new ComposioConnectedAccountNotFoundError(`Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`, { meta: {
|
|
2360
1689
|
toolkitSlug,
|
|
2361
1690
|
userId: body.userId
|
|
@@ -2395,7 +1724,7 @@ var CustomTools = class {
|
|
|
2395
1724
|
//#endregion
|
|
2396
1725
|
//#region src/errors/FileModifierErrors.ts
|
|
2397
1726
|
const FileModifierErrorCodes = { FILE_UPLOAD_FAILED: "FILE_UPLOAD_FAILED" };
|
|
2398
|
-
var ComposioFileUploadError = class extends ComposioError {
|
|
1727
|
+
var ComposioFileUploadError = class extends require_fileUtils.ComposioError {
|
|
2399
1728
|
constructor(message = "Failed to upload file", options = {}) {
|
|
2400
1729
|
super(message, {
|
|
2401
1730
|
...options,
|
|
@@ -2406,220 +1735,6 @@ var ComposioFileUploadError = class extends ComposioError {
|
|
|
2406
1735
|
}
|
|
2407
1736
|
};
|
|
2408
1737
|
|
|
2409
|
-
//#endregion
|
|
2410
|
-
//#region src/utils/fileUtils.ts
|
|
2411
|
-
const getExtensionFromMimeType = (mimeType) => {
|
|
2412
|
-
const mimeToExt = {
|
|
2413
|
-
"text/plain": "txt",
|
|
2414
|
-
"text/html": "html",
|
|
2415
|
-
"text/css": "css",
|
|
2416
|
-
"text/javascript": "js",
|
|
2417
|
-
"application/json": "json",
|
|
2418
|
-
"application/xml": "xml",
|
|
2419
|
-
"application/pdf": "pdf",
|
|
2420
|
-
"application/zip": "zip",
|
|
2421
|
-
"application/x-zip-compressed": "zip",
|
|
2422
|
-
"application/gzip": "gz",
|
|
2423
|
-
"application/x-tar": "tar",
|
|
2424
|
-
"application/msword": "doc",
|
|
2425
|
-
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
2426
|
-
"application/vnd.ms-excel": "xls",
|
|
2427
|
-
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
2428
|
-
"application/vnd.ms-powerpoint": "ppt",
|
|
2429
|
-
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
|
|
2430
|
-
"image/jpeg": "jpg",
|
|
2431
|
-
"image/jpg": "jpg",
|
|
2432
|
-
"image/png": "png",
|
|
2433
|
-
"image/gif": "gif",
|
|
2434
|
-
"image/svg+xml": "svg",
|
|
2435
|
-
"image/webp": "webp",
|
|
2436
|
-
"image/bmp": "bmp",
|
|
2437
|
-
"image/tiff": "tiff",
|
|
2438
|
-
"audio/mpeg": "mp3",
|
|
2439
|
-
"audio/wav": "wav",
|
|
2440
|
-
"audio/ogg": "ogg",
|
|
2441
|
-
"video/mp4": "mp4",
|
|
2442
|
-
"video/mpeg": "mpeg",
|
|
2443
|
-
"video/quicktime": "mov",
|
|
2444
|
-
"video/x-msvideo": "avi",
|
|
2445
|
-
"video/webm": "webm"
|
|
2446
|
-
};
|
|
2447
|
-
const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
|
|
2448
|
-
if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
|
|
2449
|
-
const parts = cleanMimeType.split("/");
|
|
2450
|
-
if (parts.length === 2) {
|
|
2451
|
-
const cleanSubtype = parts[1].toLowerCase();
|
|
2452
|
-
if (cleanSubtype.includes("+")) {
|
|
2453
|
-
const plusParts = cleanSubtype.split("+");
|
|
2454
|
-
const prefix = plusParts[0];
|
|
2455
|
-
const suffix = plusParts[plusParts.length - 1];
|
|
2456
|
-
if ([
|
|
2457
|
-
"svg",
|
|
2458
|
-
"atom",
|
|
2459
|
-
"rss"
|
|
2460
|
-
].includes(prefix)) return prefix;
|
|
2461
|
-
if ([
|
|
2462
|
-
"json",
|
|
2463
|
-
"xml",
|
|
2464
|
-
"yaml",
|
|
2465
|
-
"zip",
|
|
2466
|
-
"gzip"
|
|
2467
|
-
].includes(suffix)) return suffix;
|
|
2468
|
-
return suffix;
|
|
2469
|
-
}
|
|
2470
|
-
return cleanSubtype || "txt";
|
|
2471
|
-
}
|
|
2472
|
-
return "txt";
|
|
2473
|
-
};
|
|
2474
|
-
const generateTimestampedFilename = (extension, prefix) => {
|
|
2475
|
-
return `${prefix || "file_ts"}${Date.now()}${getRandomShortId()}.${extension}`;
|
|
2476
|
-
};
|
|
2477
|
-
const readFileContent = async (path$1) => {
|
|
2478
|
-
try {
|
|
2479
|
-
const content = require("fs").readFileSync(path$1);
|
|
2480
|
-
return {
|
|
2481
|
-
fileName: generateTimestampedFilename(path$1.split(".").pop() || "txt"),
|
|
2482
|
-
content: content.toString("base64"),
|
|
2483
|
-
mimeType: "application/octet-stream"
|
|
2484
|
-
};
|
|
2485
|
-
} catch (error) {
|
|
2486
|
-
throw new Error(`Error reading file at ${path$1}: ${error}`);
|
|
2487
|
-
}
|
|
2488
|
-
};
|
|
2489
|
-
const readFileContentFromURL = async (path$1) => {
|
|
2490
|
-
const response = await fetch(path$1);
|
|
2491
|
-
if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
|
|
2492
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
2493
|
-
const content = Buffer.from(arrayBuffer);
|
|
2494
|
-
const mimeType = response.headers.get("content-type") || "application/octet-stream";
|
|
2495
|
-
const pathname = new URL(path$1).pathname;
|
|
2496
|
-
let fileName = path.default.basename(pathname);
|
|
2497
|
-
if (!fileName || fileName === "/") fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2498
|
-
else if (!fileName.includes(".")) fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2499
|
-
return {
|
|
2500
|
-
content: content.toString("base64"),
|
|
2501
|
-
mimeType,
|
|
2502
|
-
fileName
|
|
2503
|
-
};
|
|
2504
|
-
};
|
|
2505
|
-
const uploadFileToS3 = async (fileName, content, toolSlug, toolkitSlug, mimeType, client) => {
|
|
2506
|
-
const response = await client.files.createPresignedURL({
|
|
2507
|
-
filename: fileName,
|
|
2508
|
-
mimetype: mimeType,
|
|
2509
|
-
md5: crypto.default.createHash("md5").update(Buffer.from(content, "base64")).digest("hex"),
|
|
2510
|
-
tool_slug: toolSlug,
|
|
2511
|
-
toolkit_slug: toolkitSlug
|
|
2512
|
-
});
|
|
2513
|
-
const { key, type } = response;
|
|
2514
|
-
if (type === "new" || type === "update") {
|
|
2515
|
-
logger_default.debug(`Uploading ${key} file to S3: ${key}`);
|
|
2516
|
-
const buffer = Buffer.from(content, "base64");
|
|
2517
|
-
const signedURL = response.type === "update" ? response.update_presigned_url : response.new_presigned_url;
|
|
2518
|
-
const uploadResponse = await fetch(signedURL, {
|
|
2519
|
-
method: "PUT",
|
|
2520
|
-
body: buffer,
|
|
2521
|
-
headers: {
|
|
2522
|
-
"Content-Type": mimeType,
|
|
2523
|
-
"Content-Length": buffer.length.toString()
|
|
2524
|
-
}
|
|
2525
|
-
});
|
|
2526
|
-
if (!uploadResponse.ok) throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
|
|
2527
|
-
} else logger_default.debug(`File already exists in S3: ${key}`);
|
|
2528
|
-
return key;
|
|
2529
|
-
};
|
|
2530
|
-
const readFile = async (file) => {
|
|
2531
|
-
if (file instanceof File) {
|
|
2532
|
-
const content = await file.arrayBuffer();
|
|
2533
|
-
return {
|
|
2534
|
-
fileName: file.name,
|
|
2535
|
-
content: Buffer.from(content).toString("base64"),
|
|
2536
|
-
mimeType: file.type
|
|
2537
|
-
};
|
|
2538
|
-
} else if (typeof file === "string") if (file.startsWith("http")) return await readFileContentFromURL(file);
|
|
2539
|
-
else return await readFileContent(file);
|
|
2540
|
-
throw new Error("Invalid file type");
|
|
2541
|
-
};
|
|
2542
|
-
const getFileDataAfterUploadingToS3 = async (file, { toolSlug, toolkitSlug, client }) => {
|
|
2543
|
-
if (!file) throw new Error("Either path or blob must be provided");
|
|
2544
|
-
const fileData = await readFile(file);
|
|
2545
|
-
logger_default.debug(`Uploading file to S3...`);
|
|
2546
|
-
const s3key = await uploadFileToS3(path.default.basename(fileData.fileName), fileData.content, toolSlug, toolkitSlug, fileData.mimeType, client);
|
|
2547
|
-
logger_default.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
|
|
2548
|
-
return {
|
|
2549
|
-
name: fileData.fileName,
|
|
2550
|
-
mimetype: fileData.mimeType,
|
|
2551
|
-
s3key
|
|
2552
|
-
};
|
|
2553
|
-
};
|
|
2554
|
-
const downloadFileFromS3 = async ({ toolSlug, s3Url, mimeType }) => {
|
|
2555
|
-
const response = await fetch(s3Url);
|
|
2556
|
-
if (!response.ok) throw new Error(`Failed to download file: ${response.statusText}`);
|
|
2557
|
-
const data = await response.arrayBuffer();
|
|
2558
|
-
const fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType), `${toolSlug}_`);
|
|
2559
|
-
return {
|
|
2560
|
-
name: fileName,
|
|
2561
|
-
mimeType,
|
|
2562
|
-
s3Url,
|
|
2563
|
-
filePath: saveFile(fileName, Buffer.from(data), true)
|
|
2564
|
-
};
|
|
2565
|
-
};
|
|
2566
|
-
/**
|
|
2567
|
-
* Gets the Composio directory.
|
|
2568
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2569
|
-
* @returns The path to the Composio directory.
|
|
2570
|
-
*/
|
|
2571
|
-
const getComposioDir = (createDirIfNotExists = false) => {
|
|
2572
|
-
try {
|
|
2573
|
-
const os = require("os");
|
|
2574
|
-
const path$1 = require("path");
|
|
2575
|
-
const fs = require("fs");
|
|
2576
|
-
const composioDir = path$1.join(os.homedir(), COMPOSIO_DIR);
|
|
2577
|
-
if (createDirIfNotExists && !fs.existsSync(composioDir)) fs.mkdirSync(composioDir, { recursive: true });
|
|
2578
|
-
return composioDir;
|
|
2579
|
-
} catch (_error) {
|
|
2580
|
-
return null;
|
|
2581
|
-
}
|
|
2582
|
-
};
|
|
2583
|
-
/**
|
|
2584
|
-
* Gets the Composio temporary files directory.
|
|
2585
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2586
|
-
* @returns The path to the Composio temporary files directory.
|
|
2587
|
-
*/
|
|
2588
|
-
const getComposioTempFilesDir = (createDirIfNotExists = false) => {
|
|
2589
|
-
try {
|
|
2590
|
-
const os = require("os");
|
|
2591
|
-
const path$1 = require("path");
|
|
2592
|
-
const fs = require("fs");
|
|
2593
|
-
const composioFilesDir = path$1.join(os.homedir(), COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
|
|
2594
|
-
if (createDirIfNotExists && !fs.existsSync(composioFilesDir)) fs.mkdirSync(composioFilesDir, { recursive: true });
|
|
2595
|
-
return composioFilesDir;
|
|
2596
|
-
} catch (_error) {
|
|
2597
|
-
return null;
|
|
2598
|
-
}
|
|
2599
|
-
};
|
|
2600
|
-
/**
|
|
2601
|
-
* Saves a file to the Composio directory.
|
|
2602
|
-
* @param file - The name of the file to save.
|
|
2603
|
-
* @param content - The content of the file to save. Can be a string or Buffer.
|
|
2604
|
-
* @param isTempFile - Whether the file is a temporary file.
|
|
2605
|
-
* @returns The path to the saved file.
|
|
2606
|
-
*/
|
|
2607
|
-
const saveFile = (file, content, isTempFile = false) => {
|
|
2608
|
-
try {
|
|
2609
|
-
const path$1 = require("path");
|
|
2610
|
-
const fs = require("fs");
|
|
2611
|
-
const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
|
|
2612
|
-
const filePath = path$1.join(composioFilesDir, path$1.basename(file));
|
|
2613
|
-
logger_default.info(`Saving file to: ${filePath}`);
|
|
2614
|
-
if (Buffer.isBuffer(content)) fs.writeFileSync(filePath, content);
|
|
2615
|
-
else fs.writeFileSync(filePath, content, "utf8");
|
|
2616
|
-
return filePath;
|
|
2617
|
-
} catch (_error) {
|
|
2618
|
-
logger_default.debug(`Error saving file: ${_error}`);
|
|
2619
|
-
return null;
|
|
2620
|
-
}
|
|
2621
|
-
};
|
|
2622
|
-
|
|
2623
1738
|
//#endregion
|
|
2624
1739
|
//#region src/utils/modifiers/FileToolModifier.ts
|
|
2625
1740
|
/**
|
|
@@ -2655,8 +1770,8 @@ const transformProperties = (properties) => {
|
|
|
2655
1770
|
const hydrateFiles = async (value, schema, ctx) => {
|
|
2656
1771
|
if (schema?.file_uploadable) {
|
|
2657
1772
|
if (typeof value !== "string" && !(value instanceof File)) return value;
|
|
2658
|
-
logger_default.debug(`Uploading file "${value}"`);
|
|
2659
|
-
return getFileDataAfterUploadingToS3(value, {
|
|
1773
|
+
require_fileUtils.logger_default.debug(`Uploading file "${value}"`);
|
|
1774
|
+
return require_fileUtils.getFileDataAfterUploadingToS3(value, {
|
|
2660
1775
|
toolSlug: ctx.toolSlug,
|
|
2661
1776
|
toolkitSlug: ctx.toolkitSlug,
|
|
2662
1777
|
client: ctx.client
|
|
@@ -2701,13 +1816,13 @@ const hydrateDownloads = async (value, ctx) => {
|
|
|
2701
1816
|
if (isPlainObject(value) && typeof value.s3url === "string") {
|
|
2702
1817
|
const { s3url, mimetype } = value;
|
|
2703
1818
|
try {
|
|
2704
|
-
logger_default.debug(`Downloading from S3: ${s3url}`);
|
|
2705
|
-
const dl = await downloadFileFromS3({
|
|
1819
|
+
require_fileUtils.logger_default.debug(`Downloading from S3: ${s3url}`);
|
|
1820
|
+
const dl = await require_fileUtils.downloadFileFromS3({
|
|
2706
1821
|
toolSlug: ctx.toolSlug,
|
|
2707
1822
|
s3Url: s3url,
|
|
2708
1823
|
mimeType: mimetype ?? "application/octet-stream"
|
|
2709
1824
|
});
|
|
2710
|
-
logger_default.debug(`Downloaded → ${dl.filePath}`);
|
|
1825
|
+
require_fileUtils.logger_default.debug(`Downloaded → ${dl.filePath}`);
|
|
2711
1826
|
return {
|
|
2712
1827
|
uri: dl.filePath,
|
|
2713
1828
|
file_downloaded: dl.filePath ? true : false,
|
|
@@ -2715,7 +1830,7 @@ const hydrateDownloads = async (value, ctx) => {
|
|
|
2715
1830
|
mimeType: dl.mimeType
|
|
2716
1831
|
};
|
|
2717
1832
|
} catch (err) {
|
|
2718
|
-
logger_default.error(`Download failed: ${s3url}`, { cause: err });
|
|
1833
|
+
require_fileUtils.logger_default.error(`Download failed: ${s3url}`, { cause: err });
|
|
2719
1834
|
return {
|
|
2720
1835
|
uri: "",
|
|
2721
1836
|
file_downloaded: false,
|
|
@@ -2846,7 +1961,7 @@ var Tools = class {
|
|
|
2846
1961
|
this.provider._setExecuteToolFn(this.createExecuteFnForProviders());
|
|
2847
1962
|
this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
|
|
2848
1963
|
this.getRawComposioTools = this.getRawComposioTools.bind(this);
|
|
2849
|
-
telemetry.instrument(this, "Tools");
|
|
1964
|
+
require_fileUtils.telemetry.instrument(this, "Tools");
|
|
2850
1965
|
}
|
|
2851
1966
|
/**
|
|
2852
1967
|
* Transforms tool data from snake_case API format to camelCase for internal SDK use.
|
|
@@ -3020,7 +2135,7 @@ var Tools = class {
|
|
|
3020
2135
|
..."authConfigIds" in queryParams.data ? { auth_config_ids: queryParams.data.authConfigIds } : {},
|
|
3021
2136
|
toolkit_versions: this.toolkitVersions
|
|
3022
2137
|
};
|
|
3023
|
-
logger_default.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
|
|
2138
|
+
require_fileUtils.logger_default.debug(`Fetching tools with filters: ${JSON.stringify(filters, null, 2)}`);
|
|
3024
2139
|
const tools = await this.client.tools.list(filters);
|
|
3025
2140
|
if (!tools) return [];
|
|
3026
2141
|
const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
|
|
@@ -3040,11 +2155,42 @@ var Tools = class {
|
|
|
3040
2155
|
return modifiedTools;
|
|
3041
2156
|
}
|
|
3042
2157
|
/**
|
|
3043
|
-
*
|
|
2158
|
+
* Fetches the meta tools for a tool router session.
|
|
2159
|
+
* This method fetches the meta tools from the Composio API and transforms them to the expected format.
|
|
2160
|
+
* It provides access to the underlying meta tool data without provider-specific wrapping.
|
|
3044
2161
|
*
|
|
3045
|
-
*
|
|
3046
|
-
*
|
|
3047
|
-
*
|
|
2162
|
+
* @param sessionId {string} The session id to get the meta tools for
|
|
2163
|
+
* @param options {SchemaModifierOptions} Optional configuration for tool retrieval
|
|
2164
|
+
* @param {TransformToolSchemaModifier} [options.modifySchema] - Function to transform the tool schema
|
|
2165
|
+
* @returns {Promise<ToolList>} The list of meta tools
|
|
2166
|
+
*
|
|
2167
|
+
* @example
|
|
2168
|
+
* ```typescript
|
|
2169
|
+
* const metaTools = await composio.tools.getRawToolRouterMetaTools('session_123');
|
|
2170
|
+
* console.log(metaTools);
|
|
2171
|
+
* ```
|
|
2172
|
+
*/
|
|
2173
|
+
async getRawToolRouterMetaTools(sessionId, options) {
|
|
2174
|
+
let modifiedTools = (await this.client.toolRouter.session.tools(sessionId)).items.map((tool) => this.transformToolCases(tool));
|
|
2175
|
+
if (options?.modifySchema) {
|
|
2176
|
+
const modifier = options.modifySchema;
|
|
2177
|
+
if (typeof modifier === "function") {
|
|
2178
|
+
const modifiedPromises = modifiedTools.map((tool) => modifier({
|
|
2179
|
+
toolSlug: tool.slug,
|
|
2180
|
+
toolkitSlug: tool.toolkit?.slug ?? "unknown",
|
|
2181
|
+
schema: tool
|
|
2182
|
+
}));
|
|
2183
|
+
modifiedTools = await Promise.all(modifiedPromises);
|
|
2184
|
+
} else throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
|
|
2185
|
+
}
|
|
2186
|
+
return modifiedTools;
|
|
2187
|
+
}
|
|
2188
|
+
/**
|
|
2189
|
+
* Retrieves a specific tool by its slug from the Composio API.
|
|
2190
|
+
*
|
|
2191
|
+
* This method fetches a single tool in raw format without provider-specific wrapping,
|
|
2192
|
+
* providing direct access to the tool's schema and metadata. Tool versions are controlled
|
|
2193
|
+
* at the Composio SDK initialization level through the `toolkitVersions` configuration.
|
|
3048
2194
|
*
|
|
3049
2195
|
* @param {string} slug - The unique identifier of the tool (e.g., 'GITHUB_GET_REPOS')
|
|
3050
2196
|
* @param {GetRawComposioToolBySlugOptions} [options] - Optional configuration for tool retrieval
|
|
@@ -3092,9 +2238,9 @@ var Tools = class {
|
|
|
3092
2238
|
async getRawComposioToolBySlug(slug, options) {
|
|
3093
2239
|
const customTool = await this.customTools.getCustomToolBySlug(slug);
|
|
3094
2240
|
if (customTool) {
|
|
3095
|
-
logger_default.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
|
|
2241
|
+
require_fileUtils.logger_default.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
|
|
3096
2242
|
return customTool;
|
|
3097
|
-
} else logger_default.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
|
|
2243
|
+
} else require_fileUtils.logger_default.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
|
|
3098
2244
|
let tool;
|
|
3099
2245
|
try {
|
|
3100
2246
|
tool = await this.client.tools.retrieve(slug, { toolkit_versions: this.toolkitVersions });
|
|
@@ -3167,7 +2313,7 @@ var Tools = class {
|
|
|
3167
2313
|
*
|
|
3168
2314
|
* @param {string} sessionId - The session id to execute the tool for
|
|
3169
2315
|
* @param {Tool[]} tools - The tools to wrap
|
|
3170
|
-
* @param {
|
|
2316
|
+
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
|
|
3171
2317
|
* @returns {Tool[]} The wrapped tools
|
|
3172
2318
|
*/
|
|
3173
2319
|
wrapToolsForToolRouter(sessionId, tools, modifiers) {
|
|
@@ -3199,7 +2345,7 @@ var Tools = class {
|
|
|
3199
2345
|
* Creates a function that executes a tool for a tool router session
|
|
3200
2346
|
*
|
|
3201
2347
|
* @param {string} sessionId - The session id to execute the tool for
|
|
3202
|
-
* @param {
|
|
2348
|
+
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
|
|
3203
2349
|
* @returns {ExecuteToolFn} The execute tool function
|
|
3204
2350
|
*/
|
|
3205
2351
|
createExecuteToolFnForToolRouter(sessionId, modifiers) {
|
|
@@ -3337,36 +2483,36 @@ var Tools = class {
|
|
|
3337
2483
|
* @param {ToolExecuteMetaParams} body - The execution parameters
|
|
3338
2484
|
* @param {string} body.sessionId - The session id to execute the tool for
|
|
3339
2485
|
* @param {Record<string, unknown>} body.arguments - The input to pass to the tool
|
|
3340
|
-
* @param {
|
|
2486
|
+
* @param {SessionExecuteMetaModifiers} modifiers - The modifiers to apply to the tool
|
|
3341
2487
|
* @returns {Promise<ToolExecuteResponse>} The response from the tool execution
|
|
3342
2488
|
*/
|
|
3343
2489
|
async executeMetaTool(toolSlug, body, modifiers) {
|
|
3344
2490
|
const executeMetaParams = ToolExecuteMetaParamsSchema.safeParse(body);
|
|
3345
2491
|
if (!executeMetaParams.success) throw new ValidationError("Invalid tool execute meta parameters", { cause: executeMetaParams.error });
|
|
3346
|
-
|
|
3347
|
-
if (
|
|
3348
|
-
slug: toolSlug,
|
|
3349
|
-
sessionId: body.sessionId
|
|
3350
|
-
} });
|
|
3351
|
-
const params = await this.applyBeforeExecuteModifiers(tool, {
|
|
2492
|
+
let modifiedParams = body.arguments ?? {};
|
|
2493
|
+
if (modifiers?.beforeExecute) modifiedParams = await modifiers.beforeExecute({
|
|
3352
2494
|
toolSlug,
|
|
3353
|
-
toolkitSlug:
|
|
3354
|
-
|
|
3355
|
-
|
|
2495
|
+
toolkitSlug: "composio",
|
|
2496
|
+
sessionId: body.sessionId,
|
|
2497
|
+
params: modifiedParams
|
|
2498
|
+
});
|
|
3356
2499
|
const response = await this.client.toolRouter.session.executeMeta(body.sessionId, {
|
|
3357
2500
|
slug: toolSlug,
|
|
3358
|
-
arguments:
|
|
2501
|
+
arguments: modifiedParams
|
|
3359
2502
|
});
|
|
3360
|
-
|
|
2503
|
+
let result = {
|
|
2504
|
+
data: response.data,
|
|
2505
|
+
error: response.error,
|
|
2506
|
+
successful: !response.error,
|
|
2507
|
+
logId: response.log_id
|
|
2508
|
+
};
|
|
2509
|
+
if (modifiers?.afterExecute) result = await modifiers.afterExecute({
|
|
3361
2510
|
toolSlug,
|
|
3362
|
-
toolkitSlug:
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
logId: response.log_id
|
|
3368
|
-
}
|
|
3369
|
-
}, modifiers?.afterExecute);
|
|
2511
|
+
toolkitSlug: "composio",
|
|
2512
|
+
sessionId: body.sessionId,
|
|
2513
|
+
result
|
|
2514
|
+
});
|
|
2515
|
+
return result;
|
|
3370
2516
|
}
|
|
3371
2517
|
/**
|
|
3372
2518
|
* Fetches the list of all available tools in the Composio SDK.
|
|
@@ -3684,7 +2830,7 @@ var AuthConfigs = class {
|
|
|
3684
2830
|
client;
|
|
3685
2831
|
constructor(client) {
|
|
3686
2832
|
this.client = client;
|
|
3687
|
-
telemetry.instrument(this, "AuthConfigs");
|
|
2833
|
+
require_fileUtils.telemetry.instrument(this, "AuthConfigs");
|
|
3688
2834
|
}
|
|
3689
2835
|
/**
|
|
3690
2836
|
* Protected getter for the client instance.
|
|
@@ -3952,7 +3098,7 @@ function createConnectionRequest(client, connectedAccountId, status, redirectUrl
|
|
|
3952
3098
|
status: status || ConnectedAccountStatuses.INITIATED,
|
|
3953
3099
|
redirectUrl
|
|
3954
3100
|
};
|
|
3955
|
-
telemetry.instrument(state, "ConnectionRequest");
|
|
3101
|
+
require_fileUtils.telemetry.instrument(state, "ConnectionRequest");
|
|
3956
3102
|
/**
|
|
3957
3103
|
* Waits for the connection request to complete and become active.
|
|
3958
3104
|
*
|
|
@@ -3987,7 +3133,7 @@ function createConnectionRequest(client, connectedAccountId, status, redirectUrl
|
|
|
3987
3133
|
return transformConnectedAccountResponse(response);
|
|
3988
3134
|
}
|
|
3989
3135
|
} catch (error) {
|
|
3990
|
-
if (error instanceof
|
|
3136
|
+
if (error instanceof _composio_client.default.NotFoundError) throw new ComposioConnectedAccountNotFoundError(`Connected account with id ${state.id} not found`, { meta: { connectedAccountId: state.id } });
|
|
3991
3137
|
else throw error;
|
|
3992
3138
|
}
|
|
3993
3139
|
const terminalErrorStates = [ConnectedAccountStatuses.FAILED, ConnectedAccountStatuses.EXPIRED];
|
|
@@ -4028,7 +3174,7 @@ var ConnectedAccounts = class {
|
|
|
4028
3174
|
client;
|
|
4029
3175
|
constructor(client) {
|
|
4030
3176
|
this.client = client;
|
|
4031
|
-
telemetry.instrument(this, "ConnectedAccounts");
|
|
3177
|
+
require_fileUtils.telemetry.instrument(this, "ConnectedAccounts");
|
|
4032
3178
|
}
|
|
4033
3179
|
/**
|
|
4034
3180
|
* Lists all connected accounts based on provided filter criteria.
|
|
@@ -4128,7 +3274,7 @@ var ConnectedAccounts = class {
|
|
|
4128
3274
|
authConfigIds: [authConfigId]
|
|
4129
3275
|
});
|
|
4130
3276
|
if (connectedAccount.items.length > 0 && !options?.allowMultiple) throw new ComposioMultipleConnectedAccountsError(`Multiple connected accounts found for user ${userId} in auth config ${authConfigId}. Please use the allowMultiple option to allow multiple connected accounts.`);
|
|
4131
|
-
else if (connectedAccount.items.length > 0) logger_default.warn(`[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`);
|
|
3277
|
+
else if (connectedAccount.items.length > 0) require_fileUtils.logger_default.warn(`[Warn:AllowMultiple] Multiple connected accounts found for user ${userId} in auth config ${authConfigId}`);
|
|
4132
3278
|
const state = options?.config ?? void 0;
|
|
4133
3279
|
const response = await this.client.connectedAccounts.create({
|
|
4134
3280
|
auth_config: { id: authConfigId },
|
|
@@ -4416,7 +3562,7 @@ var Toolkits = class {
|
|
|
4416
3562
|
constructor(client) {
|
|
4417
3563
|
this.client = client;
|
|
4418
3564
|
this.authorize = this.authorize.bind(this);
|
|
4419
|
-
telemetry.instrument(this, "Toolkits");
|
|
3565
|
+
require_fileUtils.telemetry.instrument(this, "Toolkits");
|
|
4420
3566
|
}
|
|
4421
3567
|
/**
|
|
4422
3568
|
* Retrieves a list of toolkits based on the provided query parameters.
|
|
@@ -4484,7 +3630,7 @@ var Toolkits = class {
|
|
|
4484
3630
|
async getAuthConfigFields(toolkitSlug, authScheme, authConfigType, requiredOnly) {
|
|
4485
3631
|
const toolkit = await this.getToolkitBySlug(toolkitSlug);
|
|
4486
3632
|
if (!toolkit.authConfigDetails) throw new ComposioAuthConfigNotFoundError("No auth config found for toolkit", { meta: { toolkitSlug } });
|
|
4487
|
-
if (toolkit.authConfigDetails.length > 1 && !authScheme) logger_default.warn(`Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`, { meta: { toolkitSlug } });
|
|
3633
|
+
if (toolkit.authConfigDetails.length > 1 && !authScheme) require_fileUtils.logger_default.warn(`Multiple auth configs found for ${toolkitSlug}, please specify the auth scheme to get details of specific auth scheme. Selecting the first scheme by default.`, { meta: { toolkitSlug } });
|
|
4488
3634
|
const authConfig = authScheme ? toolkit.authConfigDetails.find((authConfig$1) => authConfig$1.mode === authScheme) : toolkit.authConfigDetails[0];
|
|
4489
3635
|
if (!authConfig) throw new ComposioAuthConfigNotFoundError(`Auth schema ${authScheme} not found for toolkit ${toolkitSlug} with auth scheme ${authScheme}`, { meta: {
|
|
4490
3636
|
toolkitSlug,
|
|
@@ -4563,7 +3709,7 @@ var Toolkits = class {
|
|
|
4563
3709
|
name: `${toolkit.name} Auth Config`
|
|
4564
3710
|
})).id;
|
|
4565
3711
|
} catch (error) {
|
|
4566
|
-
if (error instanceof
|
|
3712
|
+
if (error instanceof _composio_client.default.APIError && error.status === 400) throw new ComposioAuthConfigNotFoundError(`No Default auth config found for toolkit ${toolkitSlug}`, {
|
|
4567
3713
|
meta: { toolkitSlug },
|
|
4568
3714
|
cause: error,
|
|
4569
3715
|
possibleFixes: [`Please Create an auth config for the toolkit ${toolkitSlug} via the dashboard`]
|
|
@@ -4674,12 +3820,66 @@ const TriggersTypeListResponseSchema = zod_v3.z.object({
|
|
|
4674
3820
|
totalPages: zod_v3.z.number()
|
|
4675
3821
|
});
|
|
4676
3822
|
/**
|
|
3823
|
+
* Webhook payload schemas for V1, V2, V3 versions
|
|
3824
|
+
* These schemas represent the raw payload structure sent by Composio's webhook system
|
|
3825
|
+
*/
|
|
3826
|
+
/** V1 webhook payload - legacy format */
|
|
3827
|
+
const WebhookPayloadV1Schema = zod_v3.z.object({
|
|
3828
|
+
trigger_name: zod_v3.z.string(),
|
|
3829
|
+
connection_id: zod_v3.z.string(),
|
|
3830
|
+
trigger_id: zod_v3.z.string(),
|
|
3831
|
+
payload: zod_v3.z.record(zod_v3.z.unknown()),
|
|
3832
|
+
log_id: zod_v3.z.string()
|
|
3833
|
+
});
|
|
3834
|
+
/** V2 webhook payload - includes timestamp and nested data */
|
|
3835
|
+
const WebhookPayloadV2Schema = zod_v3.z.object({
|
|
3836
|
+
type: zod_v3.z.string(),
|
|
3837
|
+
timestamp: zod_v3.z.string(),
|
|
3838
|
+
log_id: zod_v3.z.string(),
|
|
3839
|
+
data: zod_v3.z.object({
|
|
3840
|
+
connection_id: zod_v3.z.string(),
|
|
3841
|
+
connection_nano_id: zod_v3.z.string(),
|
|
3842
|
+
trigger_nano_id: zod_v3.z.string(),
|
|
3843
|
+
trigger_id: zod_v3.z.string(),
|
|
3844
|
+
user_id: zod_v3.z.string()
|
|
3845
|
+
}).passthrough()
|
|
3846
|
+
});
|
|
3847
|
+
/** V3 webhook payload - current format with metadata */
|
|
3848
|
+
const WebhookPayloadV3Schema = zod_v3.z.object({
|
|
3849
|
+
id: zod_v3.z.string(),
|
|
3850
|
+
timestamp: zod_v3.z.string(),
|
|
3851
|
+
type: zod_v3.z.literal("composio.trigger.message"),
|
|
3852
|
+
metadata: zod_v3.z.object({
|
|
3853
|
+
log_id: zod_v3.z.string(),
|
|
3854
|
+
trigger_slug: zod_v3.z.string(),
|
|
3855
|
+
trigger_id: zod_v3.z.string(),
|
|
3856
|
+
connected_account_id: zod_v3.z.string(),
|
|
3857
|
+
auth_config_id: zod_v3.z.string(),
|
|
3858
|
+
user_id: zod_v3.z.string()
|
|
3859
|
+
}),
|
|
3860
|
+
data: zod_v3.z.record(zod_v3.z.unknown())
|
|
3861
|
+
});
|
|
3862
|
+
/** Union of all webhook payload versions */
|
|
3863
|
+
const WebhookPayloadSchema = zod_v3.z.union([
|
|
3864
|
+
WebhookPayloadV3Schema,
|
|
3865
|
+
WebhookPayloadV2Schema,
|
|
3866
|
+
WebhookPayloadV1Schema
|
|
3867
|
+
]);
|
|
3868
|
+
/** Webhook version enum */
|
|
3869
|
+
const WebhookVersions = {
|
|
3870
|
+
V1: "V1",
|
|
3871
|
+
V2: "V2",
|
|
3872
|
+
V3: "V3"
|
|
3873
|
+
};
|
|
3874
|
+
/**
|
|
4677
3875
|
* Parameters for verifying a webhook signature
|
|
4678
3876
|
*/
|
|
4679
3877
|
const VerifyWebhookParamsSchema = zod_v3.z.object({
|
|
3878
|
+
id: zod_v3.z.string(),
|
|
4680
3879
|
payload: zod_v3.z.string(),
|
|
4681
|
-
signature: zod_v3.z.string(),
|
|
4682
3880
|
secret: zod_v3.z.string(),
|
|
3881
|
+
signature: zod_v3.z.string(),
|
|
3882
|
+
timestamp: zod_v3.z.string(),
|
|
4683
3883
|
tolerance: zod_v3.z.number().optional().default(300)
|
|
4684
3884
|
});
|
|
4685
3885
|
|
|
@@ -4713,7 +3913,7 @@ var InternalService = class {
|
|
|
4713
3913
|
projectId: response.project_id,
|
|
4714
3914
|
pusherCluster: response.pusher_cluster
|
|
4715
3915
|
});
|
|
4716
|
-
logger_default.debug(`[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`);
|
|
3916
|
+
require_fileUtils.logger_default.debug(`[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`);
|
|
4717
3917
|
if (!parsedResponse.success) throw new ValidationError(`Failed to parse SDK realtime credentials`, { cause: parsedResponse.error });
|
|
4718
3918
|
return parsedResponse.data;
|
|
4719
3919
|
}
|
|
@@ -4734,7 +3934,7 @@ var PusherService = class {
|
|
|
4734
3934
|
this.composioClient = client;
|
|
4735
3935
|
this.pusherBaseURL = client.baseURL;
|
|
4736
3936
|
this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? "";
|
|
4737
|
-
telemetry.instrument(this, "PusherService");
|
|
3937
|
+
require_fileUtils.telemetry.instrument(this, "PusherService");
|
|
4738
3938
|
}
|
|
4739
3939
|
/**
|
|
4740
3940
|
* Creates a Pusher client
|
|
@@ -4755,7 +3955,7 @@ var PusherService = class {
|
|
|
4755
3955
|
this.pusherKey = sdkRealtimeCredentials.pusherKey;
|
|
4756
3956
|
this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
|
|
4757
3957
|
this.pusherChannel = `private-${this.clientId}_triggers`;
|
|
4758
|
-
logger_default.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`);
|
|
3958
|
+
require_fileUtils.logger_default.debug(`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`);
|
|
4759
3959
|
try {
|
|
4760
3960
|
const { default: Pusher } = await import("pusher-js");
|
|
4761
3961
|
this.pusherClient = new Pusher(this.pusherKey, {
|
|
@@ -4799,19 +3999,19 @@ var PusherService = class {
|
|
|
4799
3999
|
callback(JSON.parse(ev.chunks.join("")));
|
|
4800
4000
|
} catch (parseError) {
|
|
4801
4001
|
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
|
|
4802
|
-
logger_default.error("Failed to parse chunked data:", errorMessage);
|
|
4002
|
+
require_fileUtils.logger_default.error("Failed to parse chunked data:", errorMessage);
|
|
4803
4003
|
} finally {
|
|
4804
4004
|
delete events[typedData.id];
|
|
4805
4005
|
}
|
|
4806
4006
|
} catch (error) {
|
|
4807
4007
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4808
|
-
logger_default.error("Error processing chunked trigger data:", errorMessage);
|
|
4008
|
+
require_fileUtils.logger_default.error("Error processing chunked trigger data:", errorMessage);
|
|
4809
4009
|
if (data && typeof data === "object" && "id" in data) delete events[data.id];
|
|
4810
4010
|
}
|
|
4811
4011
|
});
|
|
4812
4012
|
} catch (error) {
|
|
4813
4013
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4814
|
-
logger_default.error("Failed to bind chunked events:", error);
|
|
4014
|
+
require_fileUtils.logger_default.error("Failed to bind chunked events:", error);
|
|
4815
4015
|
throw new Error(`Failed to bind chunked events: ${errorMessage}`);
|
|
4816
4016
|
}
|
|
4817
4017
|
}
|
|
@@ -4827,7 +4027,7 @@ var PusherService = class {
|
|
|
4827
4027
|
*/
|
|
4828
4028
|
async subscribe(fn) {
|
|
4829
4029
|
try {
|
|
4830
|
-
logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
4030
|
+
require_fileUtils.logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
4831
4031
|
const channel = await (await this.getPusherClient()).subscribe(this.pusherChannel);
|
|
4832
4032
|
channel.bind("pusher:subscription_error", (data) => {
|
|
4833
4033
|
const error = data.error ? String(data.error) : "Unknown subscription error";
|
|
@@ -4838,11 +4038,11 @@ var PusherService = class {
|
|
|
4838
4038
|
fn(data);
|
|
4839
4039
|
} catch (error) {
|
|
4840
4040
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4841
|
-
logger_default.error("❌ Error in trigger callback:", errorMessage);
|
|
4041
|
+
require_fileUtils.logger_default.error("❌ Error in trigger callback:", errorMessage);
|
|
4842
4042
|
}
|
|
4843
4043
|
};
|
|
4844
4044
|
this.bindWithChunking(channel, "trigger_to_client", safeCallback);
|
|
4845
|
-
logger_default.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
4045
|
+
require_fileUtils.logger_default.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
4846
4046
|
} catch (error) {
|
|
4847
4047
|
throw new ComposioFailedToSubscribeToPusherChannelError("Failed to subscribe to Pusher channel", { cause: error });
|
|
4848
4048
|
}
|
|
@@ -4857,9 +4057,9 @@ var PusherService = class {
|
|
|
4857
4057
|
*/
|
|
4858
4058
|
async unsubscribe() {
|
|
4859
4059
|
try {
|
|
4860
|
-
logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
|
|
4060
|
+
require_fileUtils.logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
|
|
4861
4061
|
await (await this.getPusherClient()).unsubscribe(this.pusherChannel);
|
|
4862
|
-
logger_default.info(`✅ Unsubscribed from triggers.`);
|
|
4062
|
+
require_fileUtils.logger_default.info(`✅ Unsubscribed from triggers.`);
|
|
4863
4063
|
} catch (error) {
|
|
4864
4064
|
throw new ComposioFailedToSubscribeToPusherChannelError("Failed to unsubscribe from Pusher channel", { cause: error });
|
|
4865
4065
|
}
|
|
@@ -4960,7 +4160,7 @@ var Triggers = class {
|
|
|
4960
4160
|
this.client = client;
|
|
4961
4161
|
this.pusherService = new PusherService(client);
|
|
4962
4162
|
this.toolkitVersions = config?.toolkitVersions ?? "latest";
|
|
4963
|
-
telemetry.instrument(this, "Triggers");
|
|
4163
|
+
require_fileUtils.telemetry.instrument(this, "Triggers");
|
|
4964
4164
|
}
|
|
4965
4165
|
/**
|
|
4966
4166
|
* Fetch list of all the active triggers
|
|
@@ -5010,7 +4210,7 @@ var Triggers = class {
|
|
|
5010
4210
|
triggerType = await this.getType(slug);
|
|
5011
4211
|
toolkitSlug = triggerType.toolkit.slug;
|
|
5012
4212
|
} catch (error) {
|
|
5013
|
-
if (error instanceof
|
|
4213
|
+
if (error instanceof _composio_client.APIError && (error.status === 400 || error.status === 404)) throw new ComposioTriggerTypeNotFoundError(`Trigger type ${slug} not found`, {
|
|
5014
4214
|
cause: error,
|
|
5015
4215
|
possibleFixes: [
|
|
5016
4216
|
`Please check the trigger slug`,
|
|
@@ -5037,10 +4237,10 @@ var Triggers = class {
|
|
|
5037
4237
|
});
|
|
5038
4238
|
if (!connectedAccountId) {
|
|
5039
4239
|
connectedAccountId = connectedAccounts[0].id;
|
|
5040
|
-
logger_default.warn(`[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`);
|
|
4240
|
+
require_fileUtils.logger_default.warn(`[Warn] Multiple connected accounts found for user ${userId}, using the first one. Pass connectedAccountId to select a specific account.`);
|
|
5041
4241
|
}
|
|
5042
4242
|
} catch (error) {
|
|
5043
|
-
if (error instanceof
|
|
4243
|
+
if (error instanceof _composio_client.APIError && [400, 404].includes(error.status)) throw new ComposioConnectedAccountNotFoundError(`No connected account found for user ${userId} for toolkit ${toolkitSlug}`, {
|
|
5044
4244
|
cause: error,
|
|
5045
4245
|
possibleFixes: [`Create a new connected account for user ${userId}`]
|
|
5046
4246
|
});
|
|
@@ -5134,30 +4334,30 @@ var Triggers = class {
|
|
|
5134
4334
|
*/
|
|
5135
4335
|
shouldSendTriggerAfterFilters(filters, data) {
|
|
5136
4336
|
if (filters.toolkits?.length && !filters.toolkits.map((toolkit) => toolkit.toLowerCase()).includes(data.toolkitSlug.toLowerCase())) {
|
|
5137
|
-
logger_default.debug("Trigger does not match toolkits filter", JSON.stringify(filters.toolkits, null, 2));
|
|
4337
|
+
require_fileUtils.logger_default.debug("Trigger does not match toolkits filter", JSON.stringify(filters.toolkits, null, 2));
|
|
5138
4338
|
return false;
|
|
5139
4339
|
}
|
|
5140
4340
|
if (filters.triggerId && filters.triggerId !== data.id) {
|
|
5141
|
-
logger_default.debug("Trigger does not match triggerId filter", JSON.stringify(filters.triggerId, null, 2));
|
|
4341
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerId filter", JSON.stringify(filters.triggerId, null, 2));
|
|
5142
4342
|
return false;
|
|
5143
4343
|
}
|
|
5144
4344
|
if (filters.connectedAccountId && filters.connectedAccountId !== data.metadata.connectedAccount.id) {
|
|
5145
|
-
logger_default.debug("Trigger does not match connectedAccountId filter", JSON.stringify(filters.connectedAccountId, null, 2));
|
|
4345
|
+
require_fileUtils.logger_default.debug("Trigger does not match connectedAccountId filter", JSON.stringify(filters.connectedAccountId, null, 2));
|
|
5146
4346
|
return false;
|
|
5147
4347
|
}
|
|
5148
4348
|
if (filters.triggerSlug?.length && !filters.triggerSlug.map((triggerSlug) => triggerSlug.toLowerCase()).includes(data.triggerSlug.toLowerCase())) {
|
|
5149
|
-
logger_default.debug("Trigger does not match triggerSlug filter", JSON.stringify(filters.triggerSlug, null, 2));
|
|
4349
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerSlug filter", JSON.stringify(filters.triggerSlug, null, 2));
|
|
5150
4350
|
return false;
|
|
5151
4351
|
}
|
|
5152
4352
|
if (filters.triggerData && filters.triggerData !== data.metadata.triggerData) {
|
|
5153
|
-
logger_default.debug("Trigger does not match triggerData filter", JSON.stringify(filters.triggerData, null, 2));
|
|
4353
|
+
require_fileUtils.logger_default.debug("Trigger does not match triggerData filter", JSON.stringify(filters.triggerData, null, 2));
|
|
5154
4354
|
return false;
|
|
5155
4355
|
}
|
|
5156
4356
|
if (filters.userId && filters.userId !== data.metadata.connectedAccount.userId) {
|
|
5157
|
-
logger_default.debug("Trigger does not match userId filter", JSON.stringify(filters.userId, null, 2));
|
|
4357
|
+
require_fileUtils.logger_default.debug("Trigger does not match userId filter", JSON.stringify(filters.userId, null, 2));
|
|
5158
4358
|
return false;
|
|
5159
4359
|
}
|
|
5160
|
-
logger_default.debug("Trigger matches all filters", JSON.stringify(filters, null, 2));
|
|
4360
|
+
require_fileUtils.logger_default.debug("Trigger matches all filters", JSON.stringify(filters, null, 2));
|
|
5161
4361
|
return true;
|
|
5162
4362
|
}
|
|
5163
4363
|
/**
|
|
@@ -5178,16 +4378,16 @@ var Triggers = class {
|
|
|
5178
4378
|
if (!fn) throw new Error("Function is required for trigger subscription");
|
|
5179
4379
|
const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
|
|
5180
4380
|
if (!parsedFilters.success) throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, { cause: parsedFilters.error });
|
|
5181
|
-
logger_default.debug("🔄 Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
|
|
4381
|
+
require_fileUtils.logger_default.debug("🔄 Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
|
|
5182
4382
|
await this.pusherService.subscribe((_data) => {
|
|
5183
|
-
logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
|
|
4383
|
+
require_fileUtils.logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
|
|
5184
4384
|
const parsedData = transformIncomingTriggerPayload(_data);
|
|
5185
4385
|
if (this.shouldSendTriggerAfterFilters(parsedFilters.data, parsedData)) try {
|
|
5186
4386
|
fn(parsedData);
|
|
5187
4387
|
} catch (error) {
|
|
5188
|
-
logger_default.error("❌ Error in trigger callback:", error);
|
|
4388
|
+
require_fileUtils.logger_default.error("❌ Error in trigger callback:", error);
|
|
5189
4389
|
}
|
|
5190
|
-
else logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
4390
|
+
else require_fileUtils.logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
5191
4391
|
});
|
|
5192
4392
|
}
|
|
5193
4393
|
/**
|
|
@@ -5211,15 +4411,20 @@ var Triggers = class {
|
|
|
5211
4411
|
* Verify an incoming webhook payload and signature.
|
|
5212
4412
|
*
|
|
5213
4413
|
* This method validates that the webhook request is authentic by:
|
|
5214
|
-
* 1. Verifying the HMAC-SHA256 signature matches the payload
|
|
4414
|
+
* 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format
|
|
5215
4415
|
* 2. Optionally checking that the webhook timestamp is within the tolerance window
|
|
5216
4416
|
*
|
|
4417
|
+
* The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)`
|
|
4418
|
+
* and is expected in the format: `v1,base64EncodedSignature`
|
|
4419
|
+
*
|
|
5217
4420
|
* @param {VerifyWebhookParams} params - The verification parameters
|
|
5218
4421
|
* @param {string} params.payload - The raw webhook payload as a string (request body)
|
|
5219
|
-
* @param {string} params.signature - The signature from the webhook
|
|
4422
|
+
* @param {string} params.signature - The signature from the 'webhook-signature' header
|
|
5220
4423
|
* @param {string} params.secret - The webhook secret used to sign the payload
|
|
4424
|
+
* @param {string} params.webhookId - The webhook ID from the 'webhook-id' header
|
|
4425
|
+
* @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds)
|
|
5221
4426
|
* @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation.
|
|
5222
|
-
* @returns {VerifyWebhookResult} The verified and parsed webhook payload
|
|
4427
|
+
* @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information
|
|
5223
4428
|
*
|
|
5224
4429
|
* @throws {ValidationError} If the parameters are invalid
|
|
5225
4430
|
* @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
|
|
@@ -5230,14 +4435,17 @@ var Triggers = class {
|
|
|
5230
4435
|
* // In an Express.js webhook handler
|
|
5231
4436
|
* app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
|
|
5232
4437
|
* try {
|
|
5233
|
-
* const
|
|
4438
|
+
* const result = composio.triggers.verifyWebhook({
|
|
5234
4439
|
* payload: req.body.toString(),
|
|
5235
|
-
* signature: req.headers['
|
|
4440
|
+
* signature: req.headers['webhook-signature'] as string,
|
|
4441
|
+
* webhookId: req.headers['webhook-id'] as string,
|
|
4442
|
+
* webhookTimestamp: req.headers['webhook-timestamp'] as string,
|
|
5236
4443
|
* secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
|
|
5237
4444
|
* });
|
|
5238
4445
|
*
|
|
5239
4446
|
* // Process the verified payload
|
|
5240
|
-
* console.log('
|
|
4447
|
+
* console.log('Webhook version:', result.version);
|
|
4448
|
+
* console.log('Received trigger:', result.payload.triggerSlug);
|
|
5241
4449
|
* res.status(200).send('OK');
|
|
5242
4450
|
* } catch (error) {
|
|
5243
4451
|
* console.error('Webhook verification failed:', error);
|
|
@@ -5249,45 +4457,190 @@ var Triggers = class {
|
|
|
5249
4457
|
verifyWebhook(params) {
|
|
5250
4458
|
const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
|
|
5251
4459
|
if (!parsedParams.success) throw new ValidationError("Invalid parameters passed to verifyWebhook", { cause: parsedParams.error });
|
|
5252
|
-
const { payload, signature, secret, tolerance } = parsedParams.data;
|
|
5253
|
-
this.
|
|
5254
|
-
|
|
4460
|
+
const { payload, signature, secret, id: webhookId, timestamp: webhookTimestamp, tolerance } = parsedParams.data;
|
|
4461
|
+
if (tolerance > 0) this.validateWebhookTimestamp(webhookTimestamp, tolerance);
|
|
4462
|
+
this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret);
|
|
4463
|
+
const { version: version$1, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload);
|
|
4464
|
+
return {
|
|
4465
|
+
version: version$1,
|
|
4466
|
+
payload: normalizedPayload,
|
|
4467
|
+
rawPayload
|
|
4468
|
+
};
|
|
4469
|
+
}
|
|
4470
|
+
/**
|
|
4471
|
+
* Parses the webhook payload and detects its version (V1, V2, or V3)
|
|
4472
|
+
* @private
|
|
4473
|
+
*/
|
|
4474
|
+
parseWebhookPayload(payload) {
|
|
4475
|
+
let jsonPayload;
|
|
5255
4476
|
try {
|
|
5256
|
-
|
|
4477
|
+
jsonPayload = JSON.parse(payload);
|
|
5257
4478
|
} catch (error) {
|
|
5258
4479
|
throw new ComposioWebhookPayloadError("Failed to parse webhook payload as JSON", { cause: error });
|
|
5259
4480
|
}
|
|
5260
|
-
const
|
|
5261
|
-
if (
|
|
5262
|
-
|
|
4481
|
+
const v3Result = WebhookPayloadV3Schema.safeParse(jsonPayload);
|
|
4482
|
+
if (v3Result.success) return {
|
|
4483
|
+
version: WebhookVersions.V3,
|
|
4484
|
+
rawPayload: v3Result.data,
|
|
4485
|
+
normalizedPayload: this.normalizeV3Payload(v3Result.data)
|
|
4486
|
+
};
|
|
4487
|
+
const v2Result = WebhookPayloadV2Schema.safeParse(jsonPayload);
|
|
4488
|
+
if (v2Result.success) return {
|
|
4489
|
+
version: WebhookVersions.V2,
|
|
4490
|
+
rawPayload: v2Result.data,
|
|
4491
|
+
normalizedPayload: this.normalizeV2Payload(v2Result.data)
|
|
4492
|
+
};
|
|
4493
|
+
const v1Result = WebhookPayloadV1Schema.safeParse(jsonPayload);
|
|
4494
|
+
if (v1Result.success) return {
|
|
4495
|
+
version: WebhookVersions.V1,
|
|
4496
|
+
rawPayload: v1Result.data,
|
|
4497
|
+
normalizedPayload: this.normalizeV1Payload(v1Result.data)
|
|
4498
|
+
};
|
|
4499
|
+
throw new ComposioWebhookPayloadError("Webhook payload does not match any known version (V1, V2, or V3). Please ensure you are using a supported webhook payload format.", { cause: {
|
|
4500
|
+
v1Error: v1Result.error?.message,
|
|
4501
|
+
v2Error: v2Result.error?.message,
|
|
4502
|
+
v3Error: v3Result.error?.message
|
|
4503
|
+
} });
|
|
5263
4504
|
}
|
|
5264
4505
|
/**
|
|
5265
|
-
*
|
|
4506
|
+
* Normalizes a V1 webhook payload to IncomingTriggerPayload format
|
|
5266
4507
|
* @private
|
|
5267
4508
|
*/
|
|
5268
|
-
|
|
4509
|
+
normalizeV1Payload(payload) {
|
|
4510
|
+
const triggerName = payload.trigger_name;
|
|
4511
|
+
const toolkitSlug = triggerName.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4512
|
+
return {
|
|
4513
|
+
id: payload.trigger_id,
|
|
4514
|
+
uuid: payload.trigger_id,
|
|
4515
|
+
triggerSlug: triggerName,
|
|
4516
|
+
toolkitSlug,
|
|
4517
|
+
userId: "",
|
|
4518
|
+
payload: payload.payload,
|
|
4519
|
+
originalPayload: payload.payload,
|
|
4520
|
+
metadata: {
|
|
4521
|
+
id: payload.trigger_id,
|
|
4522
|
+
uuid: payload.trigger_id,
|
|
4523
|
+
toolkitSlug,
|
|
4524
|
+
triggerSlug: triggerName,
|
|
4525
|
+
triggerConfig: {},
|
|
4526
|
+
connectedAccount: {
|
|
4527
|
+
id: payload.connection_id,
|
|
4528
|
+
uuid: payload.connection_id,
|
|
4529
|
+
authConfigId: "",
|
|
4530
|
+
authConfigUUID: "",
|
|
4531
|
+
userId: "",
|
|
4532
|
+
status: "ACTIVE"
|
|
4533
|
+
}
|
|
4534
|
+
}
|
|
4535
|
+
};
|
|
4536
|
+
}
|
|
4537
|
+
/**
|
|
4538
|
+
* Normalizes a V2 webhook payload to IncomingTriggerPayload format
|
|
4539
|
+
* @private
|
|
4540
|
+
*/
|
|
4541
|
+
normalizeV2Payload(payload) {
|
|
4542
|
+
const triggerSlug = payload.type.toUpperCase();
|
|
4543
|
+
const toolkitSlug = triggerSlug.split("_")[0] || "UNKNOWN";
|
|
4544
|
+
const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } = payload.data;
|
|
4545
|
+
return {
|
|
4546
|
+
id: trigger_nano_id,
|
|
4547
|
+
uuid: trigger_id,
|
|
4548
|
+
triggerSlug,
|
|
4549
|
+
toolkitSlug,
|
|
4550
|
+
userId: user_id,
|
|
4551
|
+
payload: restData,
|
|
4552
|
+
originalPayload: restData,
|
|
4553
|
+
metadata: {
|
|
4554
|
+
id: trigger_nano_id,
|
|
4555
|
+
uuid: trigger_id,
|
|
4556
|
+
toolkitSlug,
|
|
4557
|
+
triggerSlug,
|
|
4558
|
+
triggerConfig: {},
|
|
4559
|
+
connectedAccount: {
|
|
4560
|
+
id: connection_nano_id,
|
|
4561
|
+
uuid: connection_id,
|
|
4562
|
+
authConfigId: "",
|
|
4563
|
+
authConfigUUID: "",
|
|
4564
|
+
userId: user_id,
|
|
4565
|
+
status: "ACTIVE"
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
};
|
|
4569
|
+
}
|
|
4570
|
+
/**
|
|
4571
|
+
* Normalizes a V3 webhook payload to IncomingTriggerPayload format
|
|
4572
|
+
* @private
|
|
4573
|
+
*/
|
|
4574
|
+
normalizeV3Payload(payload) {
|
|
4575
|
+
const triggerSlug = payload.metadata.trigger_slug;
|
|
4576
|
+
const toolkitSlug = triggerSlug.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4577
|
+
return {
|
|
4578
|
+
id: payload.metadata.trigger_id,
|
|
4579
|
+
uuid: payload.metadata.trigger_id,
|
|
4580
|
+
triggerSlug,
|
|
4581
|
+
toolkitSlug,
|
|
4582
|
+
userId: payload.metadata.user_id,
|
|
4583
|
+
payload: payload.data,
|
|
4584
|
+
originalPayload: payload.data,
|
|
4585
|
+
metadata: {
|
|
4586
|
+
id: payload.metadata.trigger_id,
|
|
4587
|
+
uuid: payload.metadata.trigger_id,
|
|
4588
|
+
toolkitSlug,
|
|
4589
|
+
triggerSlug,
|
|
4590
|
+
triggerConfig: {},
|
|
4591
|
+
connectedAccount: {
|
|
4592
|
+
id: payload.metadata.connected_account_id,
|
|
4593
|
+
uuid: payload.metadata.connected_account_id,
|
|
4594
|
+
authConfigId: payload.metadata.auth_config_id,
|
|
4595
|
+
authConfigUUID: payload.metadata.auth_config_id,
|
|
4596
|
+
userId: payload.metadata.user_id,
|
|
4597
|
+
status: "ACTIVE"
|
|
4598
|
+
}
|
|
4599
|
+
}
|
|
4600
|
+
};
|
|
4601
|
+
}
|
|
4602
|
+
/**
|
|
4603
|
+
* Verifies the HMAC-SHA256 signature of a webhook payload.
|
|
4604
|
+
* The signature format used by Composio is: `v1,base64EncodedSignature`
|
|
4605
|
+
* The signing input is: `${msgId}.${timestamp}.${payload}`
|
|
4606
|
+
* @private
|
|
4607
|
+
*/
|
|
4608
|
+
verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret) {
|
|
5269
4609
|
if (payload.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook payload was provided.");
|
|
5270
|
-
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the webhook
|
|
4610
|
+
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the 'webhook-signature' header.");
|
|
5271
4611
|
if (secret.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook secret was provided. You can find your webhook secret in your Composio dashboard.");
|
|
5272
|
-
|
|
5273
|
-
|
|
5274
|
-
const
|
|
5275
|
-
|
|
4612
|
+
if (webhookId.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook ID was provided. Please pass the value of the 'webhook-id' header.");
|
|
4613
|
+
if (webhookTimestamp.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header.");
|
|
4614
|
+
const signatures = signature.split(" ");
|
|
4615
|
+
const v1Signatures = [];
|
|
4616
|
+
for (const sig of signatures) {
|
|
4617
|
+
const [version$1, value] = sig.split(",");
|
|
4618
|
+
if (version$1 === "v1" && value) v1Signatures.push(value);
|
|
4619
|
+
}
|
|
4620
|
+
if (v1Signatures.length === 0) throw new ComposioWebhookSignatureVerificationError("No valid v1 signature found in the webhook-signature header. Expected format: 'v1,base64EncodedSignature'");
|
|
4621
|
+
const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
|
|
4622
|
+
const expectedSignature = node_crypto.createHmac("sha256", secret).update(toSign, "utf8").digest("base64");
|
|
4623
|
+
let isValid = false;
|
|
4624
|
+
for (const providedSignature of v1Signatures) {
|
|
4625
|
+
const signatureBuffer = Buffer.from(providedSignature);
|
|
4626
|
+
const expectedBuffer = Buffer.from(expectedSignature);
|
|
4627
|
+
if (signatureBuffer.length === expectedBuffer.length && node_crypto.timingSafeEqual(signatureBuffer, expectedBuffer)) {
|
|
4628
|
+
isValid = true;
|
|
4629
|
+
break;
|
|
4630
|
+
}
|
|
4631
|
+
}
|
|
4632
|
+
if (!isValid) throw new ComposioWebhookSignatureVerificationError("The signature provided is invalid. Please ensure you are using the correct webhook secret.");
|
|
5276
4633
|
}
|
|
5277
4634
|
/**
|
|
5278
4635
|
* Validates that the webhook timestamp is within the allowed tolerance
|
|
5279
4636
|
* @private
|
|
5280
4637
|
*/
|
|
5281
|
-
validateWebhookTimestamp(
|
|
5282
|
-
const
|
|
5283
|
-
if (
|
|
5284
|
-
|
|
5285
|
-
return;
|
|
5286
|
-
}
|
|
5287
|
-
const webhookTime = Date.parse(timestamp);
|
|
5288
|
-
if (Number.isNaN(webhookTime)) throw new ComposioWebhookPayloadError(`Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`);
|
|
4638
|
+
validateWebhookTimestamp(webhookTimestamp, tolerance) {
|
|
4639
|
+
const timestampSeconds = parseInt(webhookTimestamp, 10);
|
|
4640
|
+
if (Number.isNaN(timestampSeconds)) throw new ComposioWebhookPayloadError(`Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.`);
|
|
4641
|
+
const webhookTimeMs = timestampSeconds * 1e3;
|
|
5289
4642
|
const currentTime = Date.now();
|
|
5290
|
-
const timeDifference = Math.abs(currentTime -
|
|
4643
|
+
const timeDifference = Math.abs(currentTime - webhookTimeMs);
|
|
5291
4644
|
if (timeDifference > tolerance * 1e3) throw new ComposioWebhookSignatureVerificationError(`The webhook timestamp is outside the allowed tolerance. The webhook was sent ${Math.round(timeDifference / 1e3)} seconds ago, but the maximum allowed age is ${tolerance} seconds.`);
|
|
5292
4645
|
}
|
|
5293
4646
|
};
|
|
@@ -5369,7 +4722,7 @@ const MCPServerConnectedAccountsSchema = zod_v3.default.record(zod_v3.default.st
|
|
|
5369
4722
|
})));
|
|
5370
4723
|
|
|
5371
4724
|
//#endregion
|
|
5372
|
-
//#region src/models/MCP.
|
|
4725
|
+
//#region src/models/MCP.ts
|
|
5373
4726
|
function transformMCPItemResponse(response) {
|
|
5374
4727
|
return transform(response).with(MCPItemSchema).using((raw) => ({
|
|
5375
4728
|
name: raw.name,
|
|
@@ -5388,11 +4741,11 @@ function transformMCPItemResponse(response) {
|
|
|
5388
4741
|
* Handles MCP server operations.
|
|
5389
4742
|
* When `config.experimental.mcp` is enabled, this class augments the features of `composio.mcp`.
|
|
5390
4743
|
*/
|
|
5391
|
-
var MCP
|
|
4744
|
+
var MCP = class {
|
|
5392
4745
|
client;
|
|
5393
4746
|
constructor(client) {
|
|
5394
4747
|
this.client = client;
|
|
5395
|
-
telemetry.instrument(this, "MCP");
|
|
4748
|
+
require_fileUtils.telemetry.instrument(this, "MCP");
|
|
5396
4749
|
}
|
|
5397
4750
|
/**
|
|
5398
4751
|
* Create a new MCP configuration.
|
|
@@ -5706,11 +5059,11 @@ var MCP$1 = class {
|
|
|
5706
5059
|
//#region src/utils/sdk.ts
|
|
5707
5060
|
const userDataPath = () => {
|
|
5708
5061
|
try {
|
|
5709
|
-
const
|
|
5710
|
-
|
|
5711
|
-
return
|
|
5062
|
+
const homeDir = _platform.platform.homedir();
|
|
5063
|
+
if (!homeDir) return null;
|
|
5064
|
+
return _platform.platform.joinPath(homeDir, require_fileUtils.COMPOSIO_DIR, require_fileUtils.USER_DATA_FILE_NAME);
|
|
5712
5065
|
} catch (_error) {
|
|
5713
|
-
logger_default.debug("Environment", `Unable to get user data path`);
|
|
5066
|
+
require_fileUtils.logger_default.debug("Environment", `Unable to get user data path`);
|
|
5714
5067
|
return null;
|
|
5715
5068
|
}
|
|
5716
5069
|
};
|
|
@@ -5721,20 +5074,22 @@ const userDataPath = () => {
|
|
|
5721
5074
|
*/
|
|
5722
5075
|
const getUserDataJson = () => {
|
|
5723
5076
|
try {
|
|
5724
|
-
const
|
|
5077
|
+
const dataPath = userDataPath();
|
|
5078
|
+
if (!dataPath || !_platform.platform.supportsFileSystem) return {};
|
|
5079
|
+
const data = _platform.platform.readFileSync(dataPath, "utf8");
|
|
5725
5080
|
return JSON.parse(data);
|
|
5726
5081
|
} catch (_error) {
|
|
5727
|
-
logger_default.debug("Environment", "No user data file found");
|
|
5082
|
+
require_fileUtils.logger_default.debug("Environment", "No user data file found");
|
|
5728
5083
|
return {};
|
|
5729
5084
|
}
|
|
5730
5085
|
};
|
|
5731
5086
|
function getSDKConfig(baseUrl, apiKey) {
|
|
5732
5087
|
const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = getUserDataJson();
|
|
5733
|
-
const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
|
|
5734
|
-
const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
5735
|
-
if (!apiKeyParsed) ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
5736
|
-
logger_default.debug("Environment", `API Key: ${apiKeyParsed}`);
|
|
5737
|
-
logger_default.debug("Environment", `Base URL: ${baseURLParsed}`);
|
|
5088
|
+
const baseURLParsed = baseUrl || require_fileUtils.getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || require_fileUtils.DEFAULT_BASE_URL;
|
|
5089
|
+
const apiKeyParsed = apiKey || require_fileUtils.getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
5090
|
+
if (!apiKeyParsed) require_fileUtils.ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
5091
|
+
require_fileUtils.logger_default.debug("Environment", `API Key: ${apiKeyParsed}`);
|
|
5092
|
+
require_fileUtils.logger_default.debug("Environment", `Base URL: ${baseURLParsed}`);
|
|
5738
5093
|
return {
|
|
5739
5094
|
baseURL: baseURLParsed,
|
|
5740
5095
|
apiKey: apiKeyParsed
|
|
@@ -5754,7 +5109,7 @@ function getSDKConfig(baseUrl, apiKey) {
|
|
|
5754
5109
|
*/
|
|
5755
5110
|
function getToolkitVersionsFromEnv(defaultVersions) {
|
|
5756
5111
|
if (defaultVersions && typeof defaultVersions === "string") return defaultVersions;
|
|
5757
|
-
const envPrefixedVersions = getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
|
|
5112
|
+
const envPrefixedVersions = require_fileUtils.getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`);
|
|
5758
5113
|
const toolkitVersionsFromEnv = Object.entries(envPrefixedVersions).reduce((acc, [key, value]) => {
|
|
5759
5114
|
const toolkitName = key.replace("COMPOSIO_TOOLKIT_VERSION_", "");
|
|
5760
5115
|
acc[toolkitName.toLowerCase()] = value;
|
|
@@ -5784,7 +5139,7 @@ async function checkForLatestVersionFromNPM(currentVersion) {
|
|
|
5784
5139
|
const prerelease = semver.default.prerelease(currentVersionFromPackageJson);
|
|
5785
5140
|
if (prerelease && (String(prerelease[0]).includes("alpha") || String(prerelease[0]).includes("beta"))) return;
|
|
5786
5141
|
const latestVersion = (await (await fetch(`https://registry.npmjs.org/${packageName}/latest`)).json()).version;
|
|
5787
|
-
if (semver.default.gt(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) logger_default.info(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`);
|
|
5142
|
+
if (semver.default.gt(latestVersion, currentVersionFromPackageJson) && !require_fileUtils.IS_DEVELOPMENT_OR_CI) require_fileUtils.logger_default.info(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`);
|
|
5788
5143
|
} catch (_error) {}
|
|
5789
5144
|
}
|
|
5790
5145
|
|
|
@@ -6110,9 +5465,9 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
6110
5465
|
async handleAssistantMessage(userId, run, options, modifiers) {
|
|
6111
5466
|
const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
|
|
6112
5467
|
return await Promise.all(tool_calls.map(async (tool_call) => {
|
|
6113
|
-
logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
5468
|
+
require_fileUtils.logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
6114
5469
|
const tool_response = await this.executeToolCall(userId, tool_call, options, modifiers);
|
|
6115
|
-
logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
5470
|
+
require_fileUtils.logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
6116
5471
|
return {
|
|
6117
5472
|
tool_call_id: tool_call.id,
|
|
6118
5473
|
output: JSON.stringify(tool_response)
|
|
@@ -6271,42 +5626,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
6271
5626
|
|
|
6272
5627
|
//#endregion
|
|
6273
5628
|
//#region package.json
|
|
6274
|
-
var version = "0.
|
|
6275
|
-
|
|
6276
|
-
//#endregion
|
|
6277
|
-
//#region src/models/Files.ts
|
|
6278
|
-
var Files = class {
|
|
6279
|
-
constructor(client) {
|
|
6280
|
-
this.client = client;
|
|
6281
|
-
telemetry.instrument(this, "Files");
|
|
6282
|
-
}
|
|
6283
|
-
/**
|
|
6284
|
-
* Upload a file to S3 and return the file data.
|
|
6285
|
-
* @param filePath - The path to the file to upload or a URL of the file to upload.
|
|
6286
|
-
* @param toolSlug - The slug of the tool that is uploading the file.
|
|
6287
|
-
* @param toolkitSlug - The slug of the toolkit that is uploading the file.
|
|
6288
|
-
* @returns The file data.
|
|
6289
|
-
*/
|
|
6290
|
-
async upload({ file, toolSlug, toolkitSlug }) {
|
|
6291
|
-
return await getFileDataAfterUploadingToS3(file, {
|
|
6292
|
-
toolSlug,
|
|
6293
|
-
toolkitSlug,
|
|
6294
|
-
client: this.client
|
|
6295
|
-
});
|
|
6296
|
-
}
|
|
6297
|
-
/**
|
|
6298
|
-
* Download a file from S3 and return the file data.
|
|
6299
|
-
* @param s3key - The S3 key of the file to download.
|
|
6300
|
-
* @returns The file data.
|
|
6301
|
-
*/
|
|
6302
|
-
async download({ toolSlug, s3Url, mimeType }) {
|
|
6303
|
-
return await downloadFileFromS3({
|
|
6304
|
-
toolSlug,
|
|
6305
|
-
s3Url,
|
|
6306
|
-
mimeType
|
|
6307
|
-
});
|
|
6308
|
-
}
|
|
6309
|
-
};
|
|
5629
|
+
var version = "0.5.0";
|
|
6310
5630
|
|
|
6311
5631
|
//#endregion
|
|
6312
5632
|
//#region src/utils/session.ts
|
|
@@ -6352,7 +5672,8 @@ const getDefaultHeaders = (headers, provider) => {
|
|
|
6352
5672
|
const MCPServerTypeSchema = zod_v3.default.enum(["http", "sse"]);
|
|
6353
5673
|
const ToolRouterConfigManageConnectionsSchema = zod_v3.default.object({
|
|
6354
5674
|
enable: zod_v3.default.boolean().default(true).optional().describe("Whether to use tools to manage connections in the tool router session. Defaults to true, if set to false, you need to manage connections manually"),
|
|
6355
|
-
callbackUrl: zod_v3.default.string().optional().describe("The callback uri to use in the tool router session")
|
|
5675
|
+
callbackUrl: zod_v3.default.string().optional().describe("The callback uri to use in the tool router session"),
|
|
5676
|
+
waitForConnections: zod_v3.default.boolean().optional().describe("Whether to wait for users to finish authenticating connections before proceeding to the next step. Defaults to false, if set to true, a wait for connections tool call will happen and finish when the connections are ready")
|
|
6356
5677
|
}).strict();
|
|
6357
5678
|
const ToolRouterToolkitsParamSchema = zod_v3.default.array(zod_v3.default.string()).describe("List of toolkits to enable in the tool router session");
|
|
6358
5679
|
const ToolRouterToolkitsDisabledConfigSchema = zod_v3.default.object({ disable: ToolRouterToolkitsParamSchema.describe("List of toolkits to disable in the tool router session") }).strict();
|
|
@@ -6492,6 +5813,30 @@ const transformToolRouterTagsParams = (params) => {
|
|
|
6492
5813
|
disable: params.disable
|
|
6493
5814
|
};
|
|
6494
5815
|
};
|
|
5816
|
+
const transformToolRouterManageConnectionsParams = (params) => {
|
|
5817
|
+
if (params === void 0) return { enable: true };
|
|
5818
|
+
if (typeof params === "boolean") return { enable: params };
|
|
5819
|
+
const parsedResult = ToolRouterConfigManageConnectionsSchema.safeParse(params);
|
|
5820
|
+
if (!parsedResult.success) throw new ValidationError("Failed to parse manage connections config", { cause: parsedResult.error });
|
|
5821
|
+
const config = parsedResult.data;
|
|
5822
|
+
return {
|
|
5823
|
+
enable: config.enable ?? true,
|
|
5824
|
+
callback_url: config.callbackUrl,
|
|
5825
|
+
enable_wait_for_connections: config.waitForConnections
|
|
5826
|
+
};
|
|
5827
|
+
};
|
|
5828
|
+
const transformToolRouterWorkbenchParams = (params) => {
|
|
5829
|
+
if (!params) return;
|
|
5830
|
+
return {
|
|
5831
|
+
enable_proxy_execution: params.enableProxyExecution,
|
|
5832
|
+
auto_offload_threshold: params.autoOffloadThreshold
|
|
5833
|
+
};
|
|
5834
|
+
};
|
|
5835
|
+
const transformToolRouterToolkitsParams = (params) => {
|
|
5836
|
+
if (!params) return;
|
|
5837
|
+
if (Array.isArray(params)) return { enable: params };
|
|
5838
|
+
return params;
|
|
5839
|
+
};
|
|
6495
5840
|
|
|
6496
5841
|
//#endregion
|
|
6497
5842
|
//#region src/models/ToolRouter.ts
|
|
@@ -6499,7 +5844,7 @@ var ToolRouter = class {
|
|
|
6499
5844
|
constructor(client, config) {
|
|
6500
5845
|
this.client = client;
|
|
6501
5846
|
this.config = config;
|
|
6502
|
-
telemetry.instrument(this, "ToolRouter");
|
|
5847
|
+
require_fileUtils.telemetry.instrument(this, "ToolRouter");
|
|
6503
5848
|
}
|
|
6504
5849
|
/**
|
|
6505
5850
|
* Creates a function that authorizes a toolkit for a user.
|
|
@@ -6576,14 +5921,13 @@ var ToolRouter = class {
|
|
|
6576
5921
|
* Creates a function that wraps the tools based on the provider.
|
|
6577
5922
|
* The returned tools will be of the type the frameworks expects.
|
|
6578
5923
|
*
|
|
6579
|
-
* @param
|
|
6580
|
-
* @
|
|
6581
|
-
* @returns A function that wraps the tools based on the provider.
|
|
5924
|
+
* @param sessionId - The session id to get the tools for
|
|
5925
|
+
* @returns A function that wraps the tools based on the provider with session-specific modifiers.
|
|
6582
5926
|
*/
|
|
6583
|
-
createToolsFn = (sessionId
|
|
5927
|
+
createToolsFn = (sessionId) => {
|
|
6584
5928
|
return async (modifiers) => {
|
|
6585
5929
|
const ToolsModel = new Tools(this.client, this.config);
|
|
6586
|
-
const tools = await ToolsModel.
|
|
5930
|
+
const tools = await ToolsModel.getRawToolRouterMetaTools(sessionId, modifiers?.modifySchema ? { modifySchema: modifiers?.modifySchema } : void 0);
|
|
6587
5931
|
return ToolsModel.wrapToolsForToolRouter(sessionId, tools, modifiers);
|
|
6588
5932
|
};
|
|
6589
5933
|
};
|
|
@@ -6637,31 +5981,21 @@ var ToolRouter = class {
|
|
|
6637
5981
|
*/
|
|
6638
5982
|
async create(userId, config) {
|
|
6639
5983
|
const routerConfig = ToolRouterCreateSessionConfigSchema.parse(config ?? {});
|
|
6640
|
-
const manageConnectedAccounts = typeof routerConfig.manageConnections === "boolean" ? routerConfig.manageConnections : routerConfig.manageConnections?.enable ?? true;
|
|
6641
|
-
const toolkits = Array.isArray(routerConfig.toolkits) ? { enable: routerConfig.toolkits } : routerConfig.toolkits;
|
|
6642
|
-
const tags = transformToolRouterTagsParams(routerConfig.tags);
|
|
6643
|
-
const tools = transformToolRouterToolsParams(routerConfig.tools);
|
|
6644
5984
|
const payload = {
|
|
6645
5985
|
user_id: userId,
|
|
6646
|
-
toolkits,
|
|
6647
5986
|
auth_configs: routerConfig.authConfigs,
|
|
6648
5987
|
connected_accounts: routerConfig.connectedAccounts,
|
|
6649
|
-
|
|
6650
|
-
|
|
6651
|
-
|
|
6652
|
-
|
|
6653
|
-
|
|
6654
|
-
},
|
|
6655
|
-
workbench: routerConfig.workbench ? {
|
|
6656
|
-
enable_proxy_execution: routerConfig.workbench?.enableProxyExecution,
|
|
6657
|
-
auto_offload_threshold: routerConfig.workbench?.autoOffloadThreshold
|
|
6658
|
-
} : void 0
|
|
5988
|
+
toolkits: transformToolRouterToolkitsParams(routerConfig.toolkits),
|
|
5989
|
+
tools: transformToolRouterToolsParams(routerConfig.tools),
|
|
5990
|
+
tags: transformToolRouterTagsParams(routerConfig.tags),
|
|
5991
|
+
manage_connections: transformToolRouterManageConnectionsParams(routerConfig.manageConnections),
|
|
5992
|
+
workbench: transformToolRouterWorkbenchParams(routerConfig.workbench)
|
|
6659
5993
|
};
|
|
6660
5994
|
const session = await this.client.toolRouter.session.create(payload);
|
|
6661
5995
|
return {
|
|
6662
5996
|
sessionId: session.session_id,
|
|
6663
5997
|
mcp: this.createMCPServerConfig(session.mcp),
|
|
6664
|
-
tools: this.createToolsFn(session.session_id
|
|
5998
|
+
tools: this.createToolsFn(session.session_id),
|
|
6665
5999
|
authorize: this.createAuthorizeFn(session.session_id),
|
|
6666
6000
|
toolkits: this.createToolkitsFn(session.session_id)
|
|
6667
6001
|
};
|
|
@@ -6688,7 +6022,7 @@ var ToolRouter = class {
|
|
|
6688
6022
|
return {
|
|
6689
6023
|
sessionId: session.session_id,
|
|
6690
6024
|
mcp: this.createMCPServerConfig(session.mcp),
|
|
6691
|
-
tools: this.createToolsFn(session.session_id
|
|
6025
|
+
tools: this.createToolsFn(session.session_id),
|
|
6692
6026
|
authorize: this.createAuthorizeFn(session.session_id),
|
|
6693
6027
|
toolkits: this.createToolkitsFn(session.session_id)
|
|
6694
6028
|
};
|
|
@@ -6715,13 +6049,21 @@ var Composio = class Composio {
|
|
|
6715
6049
|
/**
|
|
6716
6050
|
* Core models for Composio.
|
|
6717
6051
|
*/
|
|
6052
|
+
/** List, retrieve, and execute tools */
|
|
6718
6053
|
tools;
|
|
6054
|
+
/** Retrieve toolkit metadata and authorize user connections */
|
|
6719
6055
|
toolkits;
|
|
6056
|
+
/** Manage webhook triggers and event subscriptions */
|
|
6720
6057
|
triggers;
|
|
6058
|
+
/** The tool provider instance used for wrapping tools in framework-specific formats */
|
|
6721
6059
|
provider;
|
|
6060
|
+
/** Upload and download files */
|
|
6722
6061
|
files;
|
|
6062
|
+
/** Manage authentication configurations for toolkits */
|
|
6723
6063
|
authConfigs;
|
|
6064
|
+
/** Manage authenticated connections */
|
|
6724
6065
|
connectedAccounts;
|
|
6066
|
+
/** Model Context Protocol server management */
|
|
6725
6067
|
mcp;
|
|
6726
6068
|
/**
|
|
6727
6069
|
* Experimental feature, use with caution
|
|
@@ -6760,10 +6102,6 @@ var Composio = class Composio {
|
|
|
6760
6102
|
*/
|
|
6761
6103
|
use;
|
|
6762
6104
|
/**
|
|
6763
|
-
* Experimental features
|
|
6764
|
-
*/
|
|
6765
|
-
experimental;
|
|
6766
|
-
/**
|
|
6767
6105
|
* Creates a new instance of the Composio SDK.
|
|
6768
6106
|
*
|
|
6769
6107
|
* The constructor initializes the SDK with the provided configuration options,
|
|
@@ -6795,7 +6133,7 @@ var Composio = class Composio {
|
|
|
6795
6133
|
*/
|
|
6796
6134
|
constructor(config) {
|
|
6797
6135
|
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(config?.baseURL, config?.apiKey);
|
|
6798
|
-
if (IS_DEVELOPMENT_OR_CI) logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
6136
|
+
if (require_fileUtils.IS_DEVELOPMENT_OR_CI) require_fileUtils.logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
6799
6137
|
/**
|
|
6800
6138
|
* Set the default provider, if not provided by the user.
|
|
6801
6139
|
*/
|
|
@@ -6817,18 +6155,18 @@ var Composio = class Composio {
|
|
|
6817
6155
|
* Initialize the Composio SDK client.
|
|
6818
6156
|
* The client is used to make API calls to the Composio API.
|
|
6819
6157
|
*/
|
|
6820
|
-
this.client = new
|
|
6158
|
+
this.client = new _composio_client.default({
|
|
6821
6159
|
apiKey: apiKeyParsed,
|
|
6822
6160
|
baseURL: baseURLParsed,
|
|
6823
6161
|
defaultHeaders: getDefaultHeaders(this.config.defaultHeaders, this.provider),
|
|
6824
|
-
logLevel: COMPOSIO_LOG_LEVEL
|
|
6162
|
+
logLevel: require_fileUtils.COMPOSIO_LOG_LEVEL
|
|
6825
6163
|
});
|
|
6826
6164
|
this.tools = new Tools(this.client, this.config);
|
|
6827
|
-
this.mcp = new MCP
|
|
6165
|
+
this.mcp = new MCP(this.client);
|
|
6828
6166
|
this.toolkits = new Toolkits(this.client);
|
|
6829
6167
|
this.triggers = new Triggers(this.client, this.config);
|
|
6830
6168
|
this.authConfigs = new AuthConfigs(this.client);
|
|
6831
|
-
this.files = new Files(this.client);
|
|
6169
|
+
this.files = new _files.Files(this.client);
|
|
6832
6170
|
this.connectedAccounts = new ConnectedAccounts(this.client);
|
|
6833
6171
|
this.toolRouter = new ToolRouter(this.client, this.config);
|
|
6834
6172
|
/**
|
|
@@ -6838,20 +6176,9 @@ var Composio = class Composio {
|
|
|
6838
6176
|
this.create = this.toolRouter.create.bind(this.toolRouter);
|
|
6839
6177
|
this.use = this.toolRouter.use.bind(this.toolRouter);
|
|
6840
6178
|
/**
|
|
6841
|
-
* Initialize Experimental features
|
|
6842
|
-
*/
|
|
6843
|
-
this.experimental = {
|
|
6844
|
-
create: async (userId, routerConfig) => {
|
|
6845
|
-
return this.toolRouter.create(userId, routerConfig);
|
|
6846
|
-
},
|
|
6847
|
-
use: async (id) => {
|
|
6848
|
-
return this.toolRouter.use(id);
|
|
6849
|
-
}
|
|
6850
|
-
};
|
|
6851
|
-
/**
|
|
6852
6179
|
* Initialize the client telemetry.
|
|
6853
6180
|
*/
|
|
6854
|
-
if (this.config.allowTracking) telemetry.setup({
|
|
6181
|
+
if (this.config.allowTracking) require_fileUtils.telemetry.setup({
|
|
6855
6182
|
apiKey: apiKeyParsed ?? "",
|
|
6856
6183
|
baseUrl: baseURLParsed ?? "",
|
|
6857
6184
|
isAgentic: this.provider?._isAgentic || false,
|
|
@@ -6860,8 +6187,8 @@ var Composio = class Composio {
|
|
|
6860
6187
|
provider: this.provider?.name ?? "openai",
|
|
6861
6188
|
host: this.config.host
|
|
6862
6189
|
});
|
|
6863
|
-
telemetry.instrument(this, "Composio");
|
|
6864
|
-
telemetry.instrument(this.provider, this.provider.name ?? this.provider.constructor.name ?? "unknown");
|
|
6190
|
+
require_fileUtils.telemetry.instrument(this, "Composio");
|
|
6191
|
+
require_fileUtils.telemetry.instrument(this.provider, this.provider.name ?? this.provider.constructor.name ?? "unknown");
|
|
6865
6192
|
if (!this.config.disableVersionCheck) checkForLatestVersionFromNPM(version);
|
|
6866
6193
|
}
|
|
6867
6194
|
/**
|
|
@@ -6994,7 +6321,7 @@ function jsonSchemaToZodSchema(jsonSchema, { strict } = { strict: false }) {
|
|
|
6994
6321
|
try {
|
|
6995
6322
|
let schema = jsonSchema;
|
|
6996
6323
|
if (strict && schema) schema = removeNonRequiredProperties(schema);
|
|
6997
|
-
return (0,
|
|
6324
|
+
return (0, _composio_json_schema_to_zod.jsonSchemaToZod)(schema);
|
|
6998
6325
|
} catch (error) {
|
|
6999
6326
|
throw new JsonSchemaToZodError("Failed to convert JSON Schema to Zod Schema", { cause: error });
|
|
7000
6327
|
}
|
|
@@ -7338,628 +6665,6 @@ const ComposioMcpUpdateResponseSchema = zod_v3.z.object({
|
|
|
7338
6665
|
tools: zod_v3.z.array(zod_v3.z.string()).optional()
|
|
7339
6666
|
});
|
|
7340
6667
|
|
|
7341
|
-
//#endregion
|
|
7342
|
-
//#region src/utils/transformers/mcp.ts
|
|
7343
|
-
/**
|
|
7344
|
-
* Transform MCP create response from snake_case to camelCase
|
|
7345
|
-
*/
|
|
7346
|
-
function transformMcpCreateResponse(response) {
|
|
7347
|
-
const result = CustomCreateResponseSchema.safeParse({
|
|
7348
|
-
id: response.id,
|
|
7349
|
-
name: response.name,
|
|
7350
|
-
createdAt: response.created_at,
|
|
7351
|
-
updatedAt: response.updated_at,
|
|
7352
|
-
status: response.status
|
|
7353
|
-
});
|
|
7354
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP create response", { cause: result.error });
|
|
7355
|
-
return result.data;
|
|
7356
|
-
}
|
|
7357
|
-
/**
|
|
7358
|
-
* Transform MCP list response from snake_case to camelCase
|
|
7359
|
-
*/
|
|
7360
|
-
function transformMcpListResponse(response) {
|
|
7361
|
-
const transformedItems = response.items?.map((item) => ({
|
|
7362
|
-
id: item.id,
|
|
7363
|
-
name: item.name,
|
|
7364
|
-
createdAt: item.created_at,
|
|
7365
|
-
updatedAt: item.updated_at,
|
|
7366
|
-
status: item.status
|
|
7367
|
-
}));
|
|
7368
|
-
const result = McpListResponseSchema.safeParse({ items: transformedItems });
|
|
7369
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP list response", { cause: result.error });
|
|
7370
|
-
return result.data;
|
|
7371
|
-
}
|
|
7372
|
-
/**
|
|
7373
|
-
* Transform MCP retrieve response from snake_case to camelCase
|
|
7374
|
-
*/
|
|
7375
|
-
function transformMcpRetrieveResponse(response) {
|
|
7376
|
-
const result = McpRetrieveResponseSchema.safeParse({
|
|
7377
|
-
id: response.id,
|
|
7378
|
-
name: response.name,
|
|
7379
|
-
createdAt: response.created_at,
|
|
7380
|
-
updatedAt: response.updated_at,
|
|
7381
|
-
status: response.status,
|
|
7382
|
-
toolkits: response.toolkits,
|
|
7383
|
-
tools: response.allowed_tools,
|
|
7384
|
-
managedAuthViaComposio: response.managed_auth_via_composio,
|
|
7385
|
-
authConfigIds: response.auth_config_ids,
|
|
7386
|
-
mcpUrl: response.mcp_url,
|
|
7387
|
-
commands: response.commands
|
|
7388
|
-
});
|
|
7389
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP retrieve response", { cause: result.error });
|
|
7390
|
-
return result.data;
|
|
7391
|
-
}
|
|
7392
|
-
/**
|
|
7393
|
-
* Transform MCP delete response from snake_case to camelCase
|
|
7394
|
-
*/
|
|
7395
|
-
function transformMcpDeleteResponse(response) {
|
|
7396
|
-
const result = McpDeleteResponseSchema.safeParse({
|
|
7397
|
-
id: response.id,
|
|
7398
|
-
deleted: response.deleted,
|
|
7399
|
-
message: response.message
|
|
7400
|
-
});
|
|
7401
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP delete response", { cause: result.error });
|
|
7402
|
-
return result.data;
|
|
7403
|
-
}
|
|
7404
|
-
/**
|
|
7405
|
-
* Transform MCP update response from snake_case to camelCase
|
|
7406
|
-
*/
|
|
7407
|
-
function transformMcpUpdateResponse(response) {
|
|
7408
|
-
const result = McpUpdateResponseSchema.safeParse({
|
|
7409
|
-
id: response.id,
|
|
7410
|
-
name: response.name,
|
|
7411
|
-
createdAt: response.created_at,
|
|
7412
|
-
updatedAt: response.updated_at,
|
|
7413
|
-
status: response.status,
|
|
7414
|
-
toolkits: response.toolkits,
|
|
7415
|
-
tools: response.tools
|
|
7416
|
-
});
|
|
7417
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP update response", { cause: result.error });
|
|
7418
|
-
return result.data;
|
|
7419
|
-
}
|
|
7420
|
-
/**
|
|
7421
|
-
* Transform MCP generate URL response from snake_case to camelCase
|
|
7422
|
-
*/
|
|
7423
|
-
function transformMcpGenerateUrlResponse(response) {
|
|
7424
|
-
const result = GenerateURLResponseSchema.safeParse({
|
|
7425
|
-
connectedAccountUrls: response.connected_account_urls,
|
|
7426
|
-
userIdsUrl: response.user_ids_url,
|
|
7427
|
-
mcpUrl: response.mcp_url
|
|
7428
|
-
});
|
|
7429
|
-
if (!result.success) throw new ValidationError("Failed to parse MCP generate URL response", { cause: result.error });
|
|
7430
|
-
return result.data;
|
|
7431
|
-
}
|
|
7432
|
-
|
|
7433
|
-
//#endregion
|
|
7434
|
-
//#region src/models/MCP.ts
|
|
7435
|
-
/**
|
|
7436
|
-
* MCP (Model Control Protocol) class
|
|
7437
|
-
* Handles MCP server operations
|
|
7438
|
-
*/
|
|
7439
|
-
var MCP = class {
|
|
7440
|
-
client;
|
|
7441
|
-
toolkits;
|
|
7442
|
-
provider;
|
|
7443
|
-
constructor(client, provider) {
|
|
7444
|
-
this.client = client;
|
|
7445
|
-
this.provider = provider;
|
|
7446
|
-
this.toolkits = new Toolkits(client);
|
|
7447
|
-
telemetry.instrument(this, "MCP");
|
|
7448
|
-
}
|
|
7449
|
-
/**
|
|
7450
|
-
* Validates toolkit configurations using Zod schema
|
|
7451
|
-
* @private
|
|
7452
|
-
* @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations to validate
|
|
7453
|
-
* @param {MCPAuthOptions} [authOptions] - Authentication options to validate
|
|
7454
|
-
* @throws {ValidationError} If validation fails
|
|
7455
|
-
*/
|
|
7456
|
-
validateInputs(toolkitConfigs, authOptions) {
|
|
7457
|
-
const toolkitConfigsResult = MCPToolkitConfigsArraySchema.safeParse(toolkitConfigs);
|
|
7458
|
-
if (toolkitConfigsResult.error) throw new ValidationError("Failed to parse toolkit configurations", { cause: toolkitConfigsResult.error });
|
|
7459
|
-
if (authOptions !== void 0) {
|
|
7460
|
-
const authOptionsResult = MCPAuthOptionsSchema.safeParse(authOptions);
|
|
7461
|
-
if (authOptionsResult.error) throw new ValidationError("Failed to parse auth options", { cause: authOptionsResult.error });
|
|
7462
|
-
}
|
|
7463
|
-
}
|
|
7464
|
-
/**
|
|
7465
|
-
* Create a new MCP server
|
|
7466
|
-
* @param {Object} params - Parameters for creating the MCP server
|
|
7467
|
-
* @param {Array} params.authConfig - Array of auth configurations with id and allowed tools
|
|
7468
|
-
* @param {Object} params.options - Server creation options
|
|
7469
|
-
* @param {string} params.options.name - Unique name for the MCP server
|
|
7470
|
-
* @param {boolean} [params.options.isChatAuth] - Whether to use chat-based authentication
|
|
7471
|
-
* @returns {Promise<McpServerCreateResponse<TMcpResponse>>} Created server details with instance getter
|
|
7472
|
-
*
|
|
7473
|
-
* @example
|
|
7474
|
-
* ```typescript
|
|
7475
|
-
* const server = await composio.mcp.create("personal-mcp-server", [
|
|
7476
|
-
* {
|
|
7477
|
-
* authConfigId: "ac_xyz",
|
|
7478
|
-
* allowedTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"]
|
|
7479
|
-
* }
|
|
7480
|
-
* ],
|
|
7481
|
-
* {
|
|
7482
|
-
* isChatAuth: true
|
|
7483
|
-
* }
|
|
7484
|
-
* });
|
|
7485
|
-
*
|
|
7486
|
-
* // Use convenience method on response
|
|
7487
|
-
* const urls = await server.getServer({
|
|
7488
|
-
* userId: "user123"
|
|
7489
|
-
* });
|
|
7490
|
-
* ```
|
|
7491
|
-
*/
|
|
7492
|
-
async create(name, serverConfig, options) {
|
|
7493
|
-
if (!serverConfig || serverConfig.length === 0) throw new ValidationError("At least one auth config is required", {});
|
|
7494
|
-
if (!name) throw new ValidationError("Server name is required", {});
|
|
7495
|
-
try {
|
|
7496
|
-
const mcpServer = await this.getByName(name);
|
|
7497
|
-
const authConfigs = mcpServer.authConfigIds?.sort();
|
|
7498
|
-
const sortedCurrentAuthConfigs = serverConfig.map((config) => config.authConfigId).sort();
|
|
7499
|
-
if (authConfigs.length > 0 && !authConfigs.every((config, index) => config === sortedCurrentAuthConfigs[index])) throw new ValidationError("MCP server with this name already exists with different auth configs", { meta: { serverName: name } });
|
|
7500
|
-
const tools = mcpServer.tools?.sort();
|
|
7501
|
-
const sortedCurrentTools = serverConfig.flatMap((config) => config.allowedTools).sort();
|
|
7502
|
-
if (tools?.length > 0 && !tools.every((tool, index) => tool === sortedCurrentTools[index])) throw new ValidationError("MCP server with this name already exists with different tools", { meta: { serverName: name } });
|
|
7503
|
-
const toolkits$1 = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
|
|
7504
|
-
const camelCaseResponse$1 = transformMcpCreateResponse({
|
|
7505
|
-
id: mcpServer.id,
|
|
7506
|
-
name: mcpServer.name,
|
|
7507
|
-
auth_config_ids: serverConfig.map((config) => config.authConfigId),
|
|
7508
|
-
allowed_tools: serverConfig.flatMap((config) => config.allowedTools),
|
|
7509
|
-
managed_auth_via_composio: options.isChatAuth || false,
|
|
7510
|
-
commands: mcpServer.commands,
|
|
7511
|
-
created_at: mcpServer.createdAt,
|
|
7512
|
-
updated_at: mcpServer.updatedAt,
|
|
7513
|
-
mcp_url: mcpServer.mcpUrl
|
|
7514
|
-
});
|
|
7515
|
-
return {
|
|
7516
|
-
...camelCaseResponse$1,
|
|
7517
|
-
toolkits: toolkits$1,
|
|
7518
|
-
getServer: async (params) => {
|
|
7519
|
-
return this.getServer(camelCaseResponse$1.id, params.userId || "", { isChatAuth: options.isChatAuth });
|
|
7520
|
-
}
|
|
7521
|
-
};
|
|
7522
|
-
} catch (error) {
|
|
7523
|
-
if (error instanceof ValidationError && !error.message.includes("not found")) throw error;
|
|
7524
|
-
}
|
|
7525
|
-
const toolkits = (await Promise.all(serverConfig.map((config) => this.client.authConfigs.retrieve(config.authConfigId)))).map((config) => config.toolkit.slug);
|
|
7526
|
-
let mcpServerCreatedResponse;
|
|
7527
|
-
try {
|
|
7528
|
-
mcpServerCreatedResponse = await this.client.mcp.custom.create({
|
|
7529
|
-
name,
|
|
7530
|
-
toolkits,
|
|
7531
|
-
custom_tools: serverConfig.flatMap((config) => config.allowedTools),
|
|
7532
|
-
managed_auth_via_composio: options.isChatAuth || false,
|
|
7533
|
-
auth_config_ids: serverConfig.map((config) => config.authConfigId)
|
|
7534
|
-
});
|
|
7535
|
-
} catch (error) {
|
|
7536
|
-
throw new ValidationError("Failed to create MCP server", { cause: error });
|
|
7537
|
-
}
|
|
7538
|
-
const serverResponseResult = ComposioCustomCreateResponseSchema.safeParse(mcpServerCreatedResponse);
|
|
7539
|
-
if (serverResponseResult.error) throw new ValidationError("Failed to parse MCP server creation response", { cause: serverResponseResult.error });
|
|
7540
|
-
const camelCaseResponse = transformMcpCreateResponse(mcpServerCreatedResponse);
|
|
7541
|
-
return {
|
|
7542
|
-
...camelCaseResponse,
|
|
7543
|
-
toolkits,
|
|
7544
|
-
getServer: async (params) => {
|
|
7545
|
-
return this.getServer(camelCaseResponse.id, params.userId || "", { isChatAuth: options.isChatAuth });
|
|
7546
|
-
}
|
|
7547
|
-
};
|
|
7548
|
-
}
|
|
7549
|
-
/**
|
|
7550
|
-
* Get the connection status of a user for an MCP server
|
|
7551
|
-
*
|
|
7552
|
-
* Checks whether a user has the necessary connected accounts to use all toolkits
|
|
7553
|
-
* configured in the specified MCP server. Returns both overall connection status
|
|
7554
|
-
* and individual status for each toolkit.
|
|
7555
|
-
*
|
|
7556
|
-
* @param {Object} params - Parameters for checking connection status
|
|
7557
|
-
* @param {string} params.id - The UUID of the MCP server to check
|
|
7558
|
-
* @param {string} params.userId - The ID of the user to check connection status for
|
|
7559
|
-
* @returns {Promise<McpUserConnectionStatus>} Complete connection status including:
|
|
7560
|
-
* - `type`: Overall status (CONNECTED if all toolkits are connected, DISCONNECTED otherwise)
|
|
7561
|
-
* - `connected`: Boolean indicating if user can use the MCP server
|
|
7562
|
-
* - `connectedToolkits`: Record mapping each toolkit name to its individual connection status
|
|
7563
|
-
*
|
|
7564
|
-
* @throws {ValidationError} When MCP server has no toolkits configured
|
|
7565
|
-
* @throws {ValidationError} When MCP server retrieval fails
|
|
7566
|
-
*
|
|
7567
|
-
* @example
|
|
7568
|
-
* ```typescript
|
|
7569
|
-
* // Check if user can access an MCP server with Gmail and Slack toolkits
|
|
7570
|
-
* const connectionStatus = await composio.mcp.getUserConnectionStatus('user123', 'mcp-server-uuid');
|
|
7571
|
-
*
|
|
7572
|
-
* if (connectionStatus.connected) {
|
|
7573
|
-
* console.log('User can access all required toolkits');
|
|
7574
|
-
* // connectionStatus.type === ConnectionStatus.CONNECTED
|
|
7575
|
-
* } else {
|
|
7576
|
-
* console.log('User is missing some toolkit connections');
|
|
7577
|
-
* // Check individual toolkit statuses
|
|
7578
|
-
* Object.entries(connectionStatus.connectedToolkits).forEach(([toolkit, status]) => {
|
|
7579
|
-
* if (!status.connected) {
|
|
7580
|
-
* console.log(`Missing connection for toolkit: ${toolkit}`);
|
|
7581
|
-
* }
|
|
7582
|
-
* });
|
|
7583
|
-
* }
|
|
7584
|
-
* ```
|
|
7585
|
-
*
|
|
7586
|
-
* @example
|
|
7587
|
-
* ```typescript
|
|
7588
|
-
* // Example response when user has Gmail connected but missing Slack
|
|
7589
|
-
* {
|
|
7590
|
-
* type: ConnectionStatus.DISCONNECTED,
|
|
7591
|
-
* connected: false,
|
|
7592
|
-
* connectedToolkits: {
|
|
7593
|
-
* GMAIL: {
|
|
7594
|
-
* type: ConnectionStatus.CONNECTED,
|
|
7595
|
-
* connected: true,
|
|
7596
|
-
* toolkit: 'GMAIL',
|
|
7597
|
-
* connectedAccountId: 'conn_gmail_123'
|
|
7598
|
-
* },
|
|
7599
|
-
* SLACK: {
|
|
7600
|
-
* type: ConnectionStatus.DISCONNECTED,
|
|
7601
|
-
* connected: false,
|
|
7602
|
-
* toolkit: 'SLACK'
|
|
7603
|
-
* }
|
|
7604
|
-
* }
|
|
7605
|
-
* }
|
|
7606
|
-
* ```
|
|
7607
|
-
*/
|
|
7608
|
-
async getUserConnectionStatus(userId, serverId) {
|
|
7609
|
-
const serverDetails = await this.get(serverId);
|
|
7610
|
-
if (!serverDetails.toolkits || serverDetails.toolkits.length === 0) throw new ValidationError("MCP server has no toolkits configured", { meta: { serverId } });
|
|
7611
|
-
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
7612
|
-
user_ids: [userId],
|
|
7613
|
-
toolkit_slugs: serverDetails.toolkits.map((toolkit) => toolkit.toLowerCase()),
|
|
7614
|
-
statuses: ["ACTIVE"]
|
|
7615
|
-
});
|
|
7616
|
-
const connectedAccountsByToolkit = /* @__PURE__ */ new Map();
|
|
7617
|
-
connectedAccounts.items?.forEach((account) => {
|
|
7618
|
-
connectedAccountsByToolkit.set(account.toolkit.slug.toLowerCase(), account.id);
|
|
7619
|
-
});
|
|
7620
|
-
const connectedToolkits = {};
|
|
7621
|
-
let allToolkitsConnected = true;
|
|
7622
|
-
for (const toolkit of serverDetails.toolkits) {
|
|
7623
|
-
const connectedAccountId = connectedAccountsByToolkit.get(toolkit.toLowerCase());
|
|
7624
|
-
if (connectedAccountId) connectedToolkits[toolkit] = {
|
|
7625
|
-
type: ConnectionStatus.CONNECTED,
|
|
7626
|
-
connected: true,
|
|
7627
|
-
toolkit,
|
|
7628
|
-
connectedAccountId
|
|
7629
|
-
};
|
|
7630
|
-
else {
|
|
7631
|
-
connectedToolkits[toolkit] = {
|
|
7632
|
-
type: ConnectionStatus.DISCONNECTED,
|
|
7633
|
-
connected: false,
|
|
7634
|
-
toolkit
|
|
7635
|
-
};
|
|
7636
|
-
allToolkitsConnected = false;
|
|
7637
|
-
}
|
|
7638
|
-
}
|
|
7639
|
-
if (allToolkitsConnected) return {
|
|
7640
|
-
type: ConnectionStatus.CONNECTED,
|
|
7641
|
-
connected: true,
|
|
7642
|
-
connectedToolkits
|
|
7643
|
-
};
|
|
7644
|
-
else return {
|
|
7645
|
-
type: ConnectionStatus.DISCONNECTED,
|
|
7646
|
-
connected: false,
|
|
7647
|
-
connectedToolkits
|
|
7648
|
-
};
|
|
7649
|
-
}
|
|
7650
|
-
/**
|
|
7651
|
-
* Get the connection parameters for a toolkit
|
|
7652
|
-
* @param {string} serverId - The UUID of the MCP server
|
|
7653
|
-
* @param {string} toolkit - The toolkit to get connection parameters for
|
|
7654
|
-
* @returns {Promise<ToolkitAuthFieldsResponse>} Connection parameters for the toolkit
|
|
7655
|
-
*/
|
|
7656
|
-
async getConnectionParams(serverId, toolkit) {
|
|
7657
|
-
const mcpServerDetails = await this.get(serverId);
|
|
7658
|
-
const authConfig = (mcpServerDetails.authConfigIds ? await Promise.all(mcpServerDetails.authConfigIds.map((id) => this.client.authConfigs.retrieve(id))) : []).find((config) => config.toolkit.slug === toolkit);
|
|
7659
|
-
if (!authConfig) throw new ValidationError("Auth config not found", { meta: {
|
|
7660
|
-
serverId,
|
|
7661
|
-
toolkit
|
|
7662
|
-
} });
|
|
7663
|
-
return await this.toolkits.getConnectedAccountInitiationFields(toolkit, authConfig.auth_scheme);
|
|
7664
|
-
}
|
|
7665
|
-
/**
|
|
7666
|
-
* Authorize a user for a toolkit
|
|
7667
|
-
* @param {string} serverId - The UUID of the MCP server
|
|
7668
|
-
* @param {string} userId - The ID of the user to authorize
|
|
7669
|
-
* @param {string} toolkit - The toolkit to authorize
|
|
7670
|
-
* @returns {Promise<ConnectionRequest>} Connection request for the toolkit
|
|
7671
|
-
*/
|
|
7672
|
-
async authorize(userId, serverId, toolkit) {
|
|
7673
|
-
const authConfigId = (await this.get(serverId)).authConfigIds?.[0];
|
|
7674
|
-
return this.toolkits.authorize(userId, toolkit, authConfigId);
|
|
7675
|
-
}
|
|
7676
|
-
/**
|
|
7677
|
-
* Get server URLs for an existing MCP server
|
|
7678
|
-
* @param {string} serverId - Server UUID
|
|
7679
|
-
* @param {string} userId - User ID to get server URLs for
|
|
7680
|
-
* @param {Object} [options] - Additional options for server configuration
|
|
7681
|
-
* @param {string[]} [options.limitTools] - Subset of tools to limit (from MCP config)
|
|
7682
|
-
* @param {boolean} [options.isChatAuth] - Whether to use chat-based authentication
|
|
7683
|
-
* @returns {Promise<TMcpResponse>} Transformed server URLs in provider-specific format
|
|
7684
|
-
*
|
|
7685
|
-
* @example
|
|
7686
|
-
* ```typescript
|
|
7687
|
-
* // Get URLs for an existing server with basic user ID
|
|
7688
|
-
* const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com");
|
|
7689
|
-
*
|
|
7690
|
-
* // Get URLs with additional options
|
|
7691
|
-
* const urls = await composio.mcp.getServer("mcp_xyz", "hey@example.com", {
|
|
7692
|
-
* limitTools: ["GMAIL_FETCH_EMAILS", "SLACK_SEND_MESSAGE"],
|
|
7693
|
-
* isChatAuth: true
|
|
7694
|
-
* });
|
|
7695
|
-
* ```
|
|
7696
|
-
*
|
|
7697
|
-
*/
|
|
7698
|
-
async getServer(serverId, userId, options) {
|
|
7699
|
-
const serverDetails = await this.get(serverId);
|
|
7700
|
-
if (!userId) throw new ValidationError("User ID is required", {});
|
|
7701
|
-
const toolkits = serverDetails.toolkits || [];
|
|
7702
|
-
const connectedAccountIds = (await Promise.all(toolkits.map((toolkit) => this.client.connectedAccounts.list({
|
|
7703
|
-
user_ids: [userId],
|
|
7704
|
-
toolkit_slugs: [toolkit],
|
|
7705
|
-
statuses: ["ACTIVE"]
|
|
7706
|
-
}).then((res) => res.items?.[0]?.id)))).filter(Boolean);
|
|
7707
|
-
let data;
|
|
7708
|
-
try {
|
|
7709
|
-
data = await this.client.mcp.generate.url({
|
|
7710
|
-
user_ids: [userId],
|
|
7711
|
-
connected_account_ids: [],
|
|
7712
|
-
mcp_server_id: serverId,
|
|
7713
|
-
managed_auth_by_composio: options?.isChatAuth ?? serverDetails.managedAuthViaComposio ?? false
|
|
7714
|
-
});
|
|
7715
|
-
} catch (error) {
|
|
7716
|
-
throw new ValidationError("Failed to generate MCP server URL", { cause: error });
|
|
7717
|
-
}
|
|
7718
|
-
const urlResponseResult = ComposioGenerateURLResponseSchema.safeParse(data);
|
|
7719
|
-
if (urlResponseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: urlResponseResult.error });
|
|
7720
|
-
const camelCaseData = transformMcpGenerateUrlResponse(data);
|
|
7721
|
-
return this.wrapMcpServerResponse(camelCaseData, serverDetails.name, connectedAccountIds, [userId], toolkits);
|
|
7722
|
-
}
|
|
7723
|
-
/**
|
|
7724
|
-
* List MCP server configurations with filtering options
|
|
7725
|
-
* @param {Object} options - Filtering and pagination options
|
|
7726
|
-
* @param {number} [options.page] - Page number for pagination
|
|
7727
|
-
* @param {number} [options.limit] - Number of items per page
|
|
7728
|
-
* @param {string[]} [options.toolkits] - Filter servers by toolkit names
|
|
7729
|
-
* @param {string[]} [options.authConfigs] - Filter servers by auth config IDs
|
|
7730
|
-
* @param {string} [options.name] - Filter servers by name
|
|
7731
|
-
* @param {string} [options.user] - Filter servers by user ID
|
|
7732
|
-
* @returns {Promise<McpListResponse>} List of MCP servers matching the filters
|
|
7733
|
-
*
|
|
7734
|
-
* @example
|
|
7735
|
-
* ```typescript
|
|
7736
|
-
* // List all servers with pagination
|
|
7737
|
-
* const servers = await composio.mcp.list({
|
|
7738
|
-
* page: 1,
|
|
7739
|
-
* limit: 10
|
|
7740
|
-
* });
|
|
7741
|
-
*
|
|
7742
|
-
* // List Gmail and Supabase servers
|
|
7743
|
-
* const filteredServers = await composio.mcp.list({
|
|
7744
|
-
* toolkits: ['GMAIL', 'SUPABASE'],
|
|
7745
|
-
* authConfigIds: ['auth_123', 'auth_456']
|
|
7746
|
-
* });
|
|
7747
|
-
* ```
|
|
7748
|
-
*/
|
|
7749
|
-
async list(options) {
|
|
7750
|
-
let listResponse;
|
|
7751
|
-
try {
|
|
7752
|
-
listResponse = await this.client.mcp.list({
|
|
7753
|
-
page_no: options.page || 1,
|
|
7754
|
-
limit: options.limit || 10,
|
|
7755
|
-
toolkits: options?.toolkits?.join(",") || void 0,
|
|
7756
|
-
auth_config_ids: options?.authConfigs?.join(",") || void 0,
|
|
7757
|
-
name: options?.name
|
|
7758
|
-
});
|
|
7759
|
-
} catch (error) {
|
|
7760
|
-
throw new ValidationError("Failed to list MCP servers", { cause: error });
|
|
7761
|
-
}
|
|
7762
|
-
const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
|
|
7763
|
-
if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
|
|
7764
|
-
return transformMcpListResponse(listResponse);
|
|
7765
|
-
}
|
|
7766
|
-
/**
|
|
7767
|
-
* Get details of a specific MCP server
|
|
7768
|
-
* @param {string} serverId - Server UUID
|
|
7769
|
-
* @returns {Promise<McpRetrieveResponse>} Server details
|
|
7770
|
-
*
|
|
7771
|
-
* @example
|
|
7772
|
-
* ```typescript
|
|
7773
|
-
* const serverDetails = await composio.mcp.get('server-uuid');
|
|
7774
|
-
* ```
|
|
7775
|
-
*/
|
|
7776
|
-
async get(serverId) {
|
|
7777
|
-
let retrieveResponse;
|
|
7778
|
-
try {
|
|
7779
|
-
retrieveResponse = await this.client.mcp.retrieve(serverId);
|
|
7780
|
-
} catch (error) {
|
|
7781
|
-
throw new ValidationError("Failed to retrieve MCP server", { cause: error });
|
|
7782
|
-
}
|
|
7783
|
-
const retrieveResponseResult = McpRetrieveResponseSchema.safeParse({
|
|
7784
|
-
...retrieveResponse,
|
|
7785
|
-
mcpUrl: retrieveResponse.mcp_url
|
|
7786
|
-
});
|
|
7787
|
-
if (retrieveResponseResult.error) throw new ValidationError("Failed to parse MCP server retrieve response", { cause: retrieveResponseResult.error });
|
|
7788
|
-
return transformMcpRetrieveResponse(retrieveResponse);
|
|
7789
|
-
}
|
|
7790
|
-
/**
|
|
7791
|
-
* Delete an MCP server
|
|
7792
|
-
* @param {string} serverId - Server UUID
|
|
7793
|
-
* @returns {Promise<McpDeleteResponse>} Deletion response
|
|
7794
|
-
*
|
|
7795
|
-
* @example
|
|
7796
|
-
* ```typescript
|
|
7797
|
-
* const result = await composio.mcp.delete('server-uuid');
|
|
7798
|
-
* ```
|
|
7799
|
-
*/
|
|
7800
|
-
async delete(serverId) {
|
|
7801
|
-
let deleteResponse;
|
|
7802
|
-
try {
|
|
7803
|
-
deleteResponse = await this.client.mcp.delete(serverId);
|
|
7804
|
-
} catch (error) {
|
|
7805
|
-
throw new ValidationError("Failed to delete MCP server", { cause: error });
|
|
7806
|
-
}
|
|
7807
|
-
const deleteResponseResult = ComposioMcpDeleteResponseSchema.safeParse(deleteResponse);
|
|
7808
|
-
if (deleteResponseResult.error) throw new ValidationError("Failed to parse MCP server delete response", { cause: deleteResponseResult.error });
|
|
7809
|
-
return transformMcpDeleteResponse(deleteResponse);
|
|
7810
|
-
}
|
|
7811
|
-
/**
|
|
7812
|
-
* Update an MCP server configuration
|
|
7813
|
-
* @param {string} id - Server UUID
|
|
7814
|
-
* @param {string} name - New unique name for the server
|
|
7815
|
-
* @param {MCPToolkitConfig[]} toolkitConfigs - Array of toolkit configurations
|
|
7816
|
-
* @param {MCPAuthOptions} [authOptions] - Updated authentication options
|
|
7817
|
-
* @returns {Promise<McpUpdateResponse>} Updated server details
|
|
7818
|
-
*
|
|
7819
|
-
* @example
|
|
7820
|
-
* ```typescript
|
|
7821
|
-
* const updatedServer = await composio.mcp.update(
|
|
7822
|
-
* "server-uuid",
|
|
7823
|
-
* "my-updated-server",
|
|
7824
|
-
* [
|
|
7825
|
-
* {
|
|
7826
|
-
* toolkit: "GMAIL",
|
|
7827
|
-
* authConfigId: "ac_sdhkjfhjksdk",
|
|
7828
|
-
* allowedTools: ["GMAIL_FETCH_EMAILS"],
|
|
7829
|
-
* },
|
|
7830
|
-
* ],
|
|
7831
|
-
* {
|
|
7832
|
-
* isChatAuth: true,
|
|
7833
|
-
* }
|
|
7834
|
-
* );
|
|
7835
|
-
* ```
|
|
7836
|
-
*/
|
|
7837
|
-
async update(serverId, name, toolkitConfigs, authOptions) {
|
|
7838
|
-
this.validateInputs(toolkitConfigs, authOptions);
|
|
7839
|
-
const toolkits = toolkitConfigs.map((config) => config.toolkit);
|
|
7840
|
-
let updateResponse;
|
|
7841
|
-
try {
|
|
7842
|
-
updateResponse = await this.client.mcp.update(serverId, {
|
|
7843
|
-
name,
|
|
7844
|
-
toolkits,
|
|
7845
|
-
allowed_tools: toolkitConfigs.flatMap((config) => config.allowedTools),
|
|
7846
|
-
managed_auth_via_composio: authOptions?.isChatAuth || false
|
|
7847
|
-
});
|
|
7848
|
-
} catch (error) {
|
|
7849
|
-
throw new ValidationError("Failed to update MCP server", { cause: error });
|
|
7850
|
-
}
|
|
7851
|
-
const updateResponseResult = ComposioMcpUpdateResponseSchema.safeParse(updateResponse);
|
|
7852
|
-
if (updateResponseResult.error) throw new ValidationError("Failed to parse MCP server update response", { cause: updateResponseResult.error });
|
|
7853
|
-
return transformMcpUpdateResponse(updateResponse);
|
|
7854
|
-
}
|
|
7855
|
-
/**
|
|
7856
|
-
* Generate URL for an MCP server
|
|
7857
|
-
* @param {string} serverId - Server UUID
|
|
7858
|
-
* @param {GenerateURLParams} params - Parameters for URL generation
|
|
7859
|
-
* @returns {Promise<GenerateURLResponse>} Generated URL response
|
|
7860
|
-
*
|
|
7861
|
-
* @example
|
|
7862
|
-
* ```typescript
|
|
7863
|
-
* const urlResponse = await composio.mcp.generateUrl('server-uuid', {
|
|
7864
|
-
* userIds: ['user123'],
|
|
7865
|
-
* connectedAccountIds: ['account456'],
|
|
7866
|
-
* isChatAuth: true
|
|
7867
|
-
* });
|
|
7868
|
-
* ```
|
|
7869
|
-
*/
|
|
7870
|
-
async generateUrl(serverId, params) {
|
|
7871
|
-
const paramsResult = GenerateURLParamsSchema.safeParse(params);
|
|
7872
|
-
if (paramsResult.error) throw new ValidationError("Failed to parse generateUrl parameters", { cause: paramsResult.error });
|
|
7873
|
-
let urlResponse;
|
|
7874
|
-
try {
|
|
7875
|
-
urlResponse = await this.client.mcp.generate.url({
|
|
7876
|
-
mcp_server_id: serverId,
|
|
7877
|
-
user_ids: params.userIds,
|
|
7878
|
-
connected_account_ids: params.connectedAccountIds,
|
|
7879
|
-
managed_auth_by_composio: params.composioManagedAuth
|
|
7880
|
-
});
|
|
7881
|
-
} catch (error) {
|
|
7882
|
-
throw new ValidationError("Failed to generate MCP URL", { cause: error });
|
|
7883
|
-
}
|
|
7884
|
-
const responseResult = ComposioGenerateURLResponseSchema.safeParse(urlResponse);
|
|
7885
|
-
if (responseResult.error) throw new ValidationError("Failed to parse MCP URL generation response", { cause: responseResult.error });
|
|
7886
|
-
return transformMcpGenerateUrlResponse(urlResponse);
|
|
7887
|
-
}
|
|
7888
|
-
/**
|
|
7889
|
-
* Transform MCP URL response into the appropriate format.
|
|
7890
|
-
* If the provider has a custom transform method, use it.
|
|
7891
|
-
* Otherwise, use the default transformation.
|
|
7892
|
-
*
|
|
7893
|
-
* @param data - The MCP URL response data (in camelCase)
|
|
7894
|
-
* @param serverName - Name of the MCP server
|
|
7895
|
-
|
|
7896
|
-
* @returns Transformed response in appropriate format
|
|
7897
|
-
* @deprecated
|
|
7898
|
-
*/
|
|
7899
|
-
wrapMcpServerResponse(data, serverName, connectedAccountIds, userIds, toolkits) {
|
|
7900
|
-
if (this.provider && typeof this.provider.wrapMcpServerResponse === "function") {
|
|
7901
|
-
let snakeCaseData;
|
|
7902
|
-
if (data.connectedAccountUrls?.length) snakeCaseData = data.connectedAccountUrls.map((url, index) => ({
|
|
7903
|
-
name: serverName + "-" + connectedAccountIds?.[index],
|
|
7904
|
-
url
|
|
7905
|
-
}));
|
|
7906
|
-
else if (data.userIdsUrl?.length) snakeCaseData = data.userIdsUrl.map((url, index) => ({
|
|
7907
|
-
name: serverName + "-" + userIds?.[index],
|
|
7908
|
-
url
|
|
7909
|
-
}));
|
|
7910
|
-
else snakeCaseData = [{
|
|
7911
|
-
name: serverName,
|
|
7912
|
-
url: data.mcpUrl
|
|
7913
|
-
}];
|
|
7914
|
-
return this.provider.wrapMcpServerResponse(snakeCaseData);
|
|
7915
|
-
}
|
|
7916
|
-
if (connectedAccountIds?.length && data.connectedAccountUrls) return data.connectedAccountUrls.map((url, index) => ({
|
|
7917
|
-
url: new URL(url),
|
|
7918
|
-
name: `${serverName}-${connectedAccountIds[index]}`,
|
|
7919
|
-
toolkit: toolkits?.[index]
|
|
7920
|
-
}));
|
|
7921
|
-
else if (userIds?.length && data.userIdsUrl) return data.userIdsUrl.map((url, index) => ({
|
|
7922
|
-
url: new URL(url),
|
|
7923
|
-
name: `${serverName}-${userIds[index]}`,
|
|
7924
|
-
toolkit: toolkits?.[index]
|
|
7925
|
-
}));
|
|
7926
|
-
return {
|
|
7927
|
-
url: new URL(data.mcpUrl),
|
|
7928
|
-
name: serverName
|
|
7929
|
-
};
|
|
7930
|
-
}
|
|
7931
|
-
/**
|
|
7932
|
-
* Get details of a specific MCP server by name
|
|
7933
|
-
* @param {string} name - Server name
|
|
7934
|
-
* @returns {Promise<McpRetrieveResponse>} Server details
|
|
7935
|
-
* @throws {ValidationError} If no server found with the given name
|
|
7936
|
-
* @throws {ValidationError} If multiple servers found with the same name
|
|
7937
|
-
*
|
|
7938
|
-
* @example
|
|
7939
|
-
* ```typescript
|
|
7940
|
-
* const serverDetails = await composio.mcp.getByName('my-gmail-server');
|
|
7941
|
-
* ```
|
|
7942
|
-
*/
|
|
7943
|
-
async getByName(serverName) {
|
|
7944
|
-
if (!serverName) throw new ValidationError("Server name is required", {});
|
|
7945
|
-
let listResponse;
|
|
7946
|
-
try {
|
|
7947
|
-
listResponse = await this.client.mcp.list({
|
|
7948
|
-
name: serverName,
|
|
7949
|
-
limit: 10
|
|
7950
|
-
});
|
|
7951
|
-
} catch (error) {
|
|
7952
|
-
logger_default.error(error);
|
|
7953
|
-
throw new ValidationError("Failed to search MCP servers by name", { cause: error });
|
|
7954
|
-
}
|
|
7955
|
-
const listResponseResult = ComposioMcpListResponseSchema.safeParse(listResponse);
|
|
7956
|
-
if (listResponseResult.error) throw new ValidationError("Failed to parse MCP server list response", { cause: listResponseResult.error });
|
|
7957
|
-
const servers = listResponse.items || [];
|
|
7958
|
-
if (servers.length === 0) throw new ValidationError(`MCP server with name '${serverName}' not found`, { meta: { serverName } });
|
|
7959
|
-
return this.get(servers[0].id);
|
|
7960
|
-
}
|
|
7961
|
-
};
|
|
7962
|
-
|
|
7963
6668
|
//#endregion
|
|
7964
6669
|
exports.AuthConfigCreationToolAccessConfigSchema = AuthConfigCreationToolAccessConfigSchema;
|
|
7965
6670
|
exports.AuthConfigErrorCodes = AuthConfigErrorCodes;
|
|
@@ -7982,7 +6687,7 @@ exports.ComposioAuthConfigNotFoundError = ComposioAuthConfigNotFoundError;
|
|
|
7982
6687
|
exports.ComposioConnectedAccountNotFoundError = ComposioConnectedAccountNotFoundError;
|
|
7983
6688
|
exports.ComposioCustomCreateResponseSchema = ComposioCustomCreateResponseSchema;
|
|
7984
6689
|
exports.ComposioCustomToolsNotInitializedError = ComposioCustomToolsNotInitializedError;
|
|
7985
|
-
exports.ComposioError = ComposioError;
|
|
6690
|
+
exports.ComposioError = require_fileUtils.ComposioError;
|
|
7986
6691
|
exports.ComposioFailedToCreateConnectedAccountLink = ComposioFailedToCreateConnectedAccountLink;
|
|
7987
6692
|
exports.ComposioFailedToCreatePusherClientError = ComposioFailedToCreatePusherClientError;
|
|
7988
6693
|
exports.ComposioFailedToGetSDKRealtimeCredentialsError = ComposioFailedToGetSDKRealtimeCredentialsError;
|
|
@@ -8135,14 +6840,19 @@ exports.TriggersTypeListResponseSchema = TriggersTypeListResponseSchema;
|
|
|
8135
6840
|
exports.ValidationError = ValidationError;
|
|
8136
6841
|
exports.ValidationErrorCodes = ValidationErrorCodes;
|
|
8137
6842
|
exports.VerifyWebhookParamsSchema = VerifyWebhookParamsSchema;
|
|
6843
|
+
exports.WebhookPayloadSchema = WebhookPayloadSchema;
|
|
6844
|
+
exports.WebhookPayloadV1Schema = WebhookPayloadV1Schema;
|
|
6845
|
+
exports.WebhookPayloadV2Schema = WebhookPayloadV2Schema;
|
|
6846
|
+
exports.WebhookPayloadV3Schema = WebhookPayloadV3Schema;
|
|
6847
|
+
exports.WebhookVersions = WebhookVersions;
|
|
8138
6848
|
Object.defineProperty(exports, 'constants', {
|
|
8139
6849
|
enumerable: true,
|
|
8140
6850
|
get: function () {
|
|
8141
|
-
return constants_exports;
|
|
6851
|
+
return require_fileUtils.constants_exports;
|
|
8142
6852
|
}
|
|
8143
6853
|
});
|
|
8144
6854
|
exports.createConnectionRequest = createConnectionRequest;
|
|
8145
6855
|
exports.handleToolExecutionError = handleToolExecutionError;
|
|
8146
6856
|
exports.jsonSchemaToZodSchema = jsonSchemaToZodSchema;
|
|
8147
|
-
exports.logger = logger_default;
|
|
6857
|
+
exports.logger = require_fileUtils.logger_default;
|
|
8148
6858
|
exports.removeNonRequiredProperties = removeNonRequiredProperties;
|