@devries-cameron20 / composio Mirror · read-only / commits / 150378635
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 17:15 UTC

refactor(core): forbid explicit any and type JSON Schema recursively (#3968)

This PR: - is refreshed directly onto the current next branch now that #3966 and #3967 have merged; the PR contains only its intended type-safety work - enforces no explicit any through the standard .oxlintrc.json, pnpm lint, and plain oxlint --fix in lint-staged; docs remain covered by their nested configuration - replaces the loose JSONSchemaProperty in @composio/core with a concrete recursive interface, removing explicit any reachable through Tool.inputParameters and Tool.outputParameters - includes a minor changeset documenting the type narrowing for properties, default, and enum consumers - adds a compile-only public-contract test for recursive schemas, known-key validation, extension keywords, and Tool reachability - removes explicit any from FileToolModifier, ts-builders, core and CLI tests, provider tests, and json-schema-to-zod tests - keeps TypeScript ESLint-parity rules enabled and closes the tool-router example lint/typecheck gap - makes no lockfile changes and no runtime behavior changes ## Context Final PR from the original #3958 split. The migration foundations are already on next via #3966 and #3967, so this branch no longer carries a stacked base commit.

Alberto Schiabel committed Aug 3, 2026 at 22:24 UTC 15037863582000857d297c9fef502aa29577bd85
66 files changed +873 -528
.changeset/forbid-explicit-any.md new
+14
@@ -0,0 +1,14 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Replace the loose JSON Schema property type with a recursive, type-safe definition.
6 +
7 +`JSONSchemaProperty` (re-exported from `@composio/core` and reachable through
8 +`Tool.input_parameters` / `Tool.output_parameters`) is now a concrete recursive
9 +interface instead of effectively `any`. Runtime behavior is unchanged, but
10 +consumer code that indexed into it without narrowing (for example
11 +`schema.properties.foo.type` or `schema.default.someField`) may see new type
12 +errors: `properties` entries are now possibly `undefined` and `default` /
13 +`enum` values are `unknown`. Narrow with optional chaining or explicit type
14 +guards when upgrading.
.changeset/type-json-schema-extensions.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/json-schema-to-zod': patch
3 +---
4 +
5 +Model the parser-supported `min`, `max`, and `example` JSON Schema extensions in the exported recursive schema type.
.oxlintrc.json
+39 -21
@@ -16,40 +16,31 @@
16 "**/.next/**",
17 "**/dist/**",
18 "**/site-packages/**",
19 - "**/__fixtures__/**",
20 - "**/fixtures/**",
21 - // New exclusion vs eslint.config.mjs: mock modules are test scaffolding,
22 - // same as fixtures; the CI gate (pnpm lint → ts/packages) never reached them.
23 - "**/__mocks__/**",
19 // The docs site has its own Bun dependency tree and nested oxlint config.
20 "docs/**",
21 "ts/vendor/**",
22 "ts/packages/cli-local-tools/vendor/**",
23 + "ts/packages/core/generated/**",
24 + "ts/packages/core/pack/generated/**",
25 + "ts/packages/slim/generated/**",
26 "ts/packages/**/.generated/**",
27 "ts/packages/**/acp-adapters/**",
28 "node_modules/**",
29 "ts/examples/**/dist-worker/**",
32 - "scripts/**",
33 - "test/**",
34 - "ts/packages/*/test/**",
35 - "ts/packages/providers/*/test/**",
36 - "!ts/packages/cli/test/**",
37 - "ts/packages/cli/test/__utils__/**",
38 - // New exclusions vs eslint.config.mjs: the CI gate (pnpm lint) only ever
39 - // targeted ts/packages, so e2e suites and repo scripts were lint:fix-only
40 - // surface. Excluded explicitly now that oxlint also runs from the repo root.
41 - "ts/e2e-tests/**",
42 - "ts/scripts/**",
30 + "ts/examples/cloudflare-wrangler/worker-configuration.d.ts",
31 // ESLint only linted .ts/.tsx (--ext .ts,.tsx); keep that scope.
32 "**/*.js",
33 "**/*.mjs",
34 "**/*.cjs",
47 - "**/*.jsx",
48 - // New exclusion vs eslint.config.mjs (which matched .d.ts via --ext .ts):
49 - // ambient declarations are type-only surface covered by typecheck.
50 - "**/*.d.ts"
35 + "**/*.jsx"
36 ],
37 "rules": {
38 + // tseslint.configs.recommended rules that oxlint's correctness category
39 + // does not enable by default; re-enabled explicitly to keep the migration
40 + // behavior-preserving in this direction too.
41 + "typescript/no-namespace": "error",
42 + "no-array-constructor": "error",
43 + "typescript/no-unnecessary-type-constraint": "error",
44 // Rules oxlint enables by default that the previous ESLint setup did not
45 // enforce. Turned off to keep the migration behavior-preserving; each is a
46 // candidate to enable (and burn down) in a follow-up.
@@ -99,6 +90,34 @@
90 ]
91 },
92 "overrides": [
93 + {
94 + // These files still enforce the repository-wide no-any rule, but are
95 + // exempt from source-only policies that do not fit test helpers, large
96 + // suites, scripts, fixtures, or ambient declarations.
97 + "files": [
98 + "**/__fixtures__/**/*.{ts,tsx,mts,cts}",
99 + "**/__mocks__/**/*.{ts,tsx,mts,cts}",
100 + "**/fixtures/**/*.{ts,tsx,mts,cts}",
101 + "scripts/**/*.{ts,tsx,mts,cts}",
102 + "test/**/*.{ts,tsx,mts,cts}",
103 + "ts/e2e-tests/**/*.{ts,tsx,mts,cts}",
104 + "ts/packages/**/test/**/*.{ts,tsx,mts,cts}",
105 + "ts/packages/**/*.d.ts",
106 + "ts/scripts/**/*.{ts,tsx,mts,cts}"
107 + ],
108 + "rules": {
109 + "max-lines-per-function": "off",
110 + "no-console": "off",
111 + "no-restricted-globals": "off",
112 + "no-restricted-imports": "off",
113 + "no-unused-vars": "off",
114 + "prefer-const": "off",
115 + "require-yield": "off",
116 + "typescript/ban-ts-comment": "off",
117 + "typescript/no-empty-object-type": "off",
118 + "typescript/no-namespace": "off"
119 + }
120 + },
121 {
122 "files": ["ts/packages/cli/src/**/*.{ts,tsx}"],
123 "rules": {
@@ -206,7 +225,6 @@
225 "files": ["ts/packages/cli/test/src/**/*.{ts,tsx}"],
226 "rules": {
227 "max-lines-per-function": "off",
209 - "typescript/no-explicit-any": "off",
228 "eslint-js/no-restricted-syntax": [
229 "error",
230 {
package.json
+5 -2
@@ -39,7 +39,7 @@
39 "typecheck": "turbo typecheck --filter=./ts/packages/**",
40 "typecheck:examples": "turbo typecheck --filter='./ts/examples/*'",
41 "lint:examples": "turbo lint --filter='./ts/examples/*'",
42 - "lint": "oxlint ts/packages",
42 + "lint": "oxlint ts test tsdown.config.base.ts",
43 "lint:packages": "oxlint ts/packages",
44 "lint:fix": "oxlint --fix .",
45 "lint:fix:packages": "oxlint --fix ts/packages",
@@ -96,7 +96,10 @@
96 "zod": "catalog:"
97 },
98 "lint-staged": {
99 - "ts/packages/**/*.{ts,tsx}": [
99 + "{test,ts}/**/*.{ts,tsx,mts,cts}": [
100 + "oxlint --fix"
101 + ],
102 + "tsdown.config.base.ts": [
103 "oxlint --fix"
104 ],
105 "ts/packages/**/*.{ts,tsx,js,jsx,json,md}": [
ts/examples/tool-router/package.json
+2
@@ -9,6 +9,8 @@
9 "dev": "bun --watch src/index.ts",
10 "preload": "bun src/preload.ts",
11 "direct-tools": "bun src/direct-tools-preset.ts",
12 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
13 + "lint": "oxlint -c ../../../.oxlintrc.json src",
14 "test": "echo \"Error: no test specified\" && exit 1"
15 },
16 "keywords": [
ts/examples/tool-router/src/custom-tools-agent.ts
+4 -3
@@ -201,12 +201,13 @@ function trunc(obj: unknown): string {
201 return json.length > MAX ? json.slice(0, MAX) + "\n ... (truncated)" : json;
202 }
203
204 -agent.on("agent_tool_start", (_ctx, tool, details: any) => {
205 - const input = details.toolCall?.arguments ?? {};
204 +agent.on("agent_tool_start", (_ctx, tool, details) => {
205 + const toolCall = details.toolCall;
206 + const input = toolCall && "arguments" in toolCall ? (toolCall.arguments ?? {}) : {};
207 console.log(`\n ┌─ ${tool.name}`);
208 console.log(` │ INPUT:\n${trunc(input)}`);
209 });
209 -agent.on("agent_tool_end", (_ctx, tool, result: any) => {
210 +agent.on("agent_tool_end", (_ctx, tool, result: unknown) => {
211 let output: unknown;
212 try { output = typeof result === "string" ? JSON.parse(result) : result; } catch { output = result; }
213 console.log(` │ OUTPUT:\n${trunc(output)}`);
ts/examples/tool-router/src/openai-agents.ts
+6 -3
@@ -1,5 +1,5 @@
1 import { Composio } from '@composio/core';
2 -import { Agent, hostedMcpTool, run } from '@openai/agents';
2 +import { Agent, hostedMcpTool, run, type AgentInputItem } from '@openai/agents';
3 import { createInterface } from 'node:readline/promises';
4
5 const composio = new Composio();
@@ -22,10 +22,13 @@ const agent = new Agent({
22
23 const rl = createInterface({ input: process.stdin, output: process.stdout });
24
25 -for (let input: any = await rl.question('You: '); input !== 'exit';) {
25 +for (let input: string | AgentInputItem[] = await rl.question('You: '); input !== 'exit';) {
26 const result = await run(agent, input);
27 console.log(`Agent: ${result.finalOutput}\n`);
28 - input = [...result.history, { role: 'user' as const, content: await rl.question('You: ') }];
28 + input = [
29 + ...result.history,
30 + { role: 'user' as const, content: await rl.question('You: ') },
31 + ] as AgentInputItem[];
32 }
33
34 rl.close();
ts/packages/cli/test/__utils__/cli.ts
+1 -1
@@ -2,5 +2,5 @@ import { Effect } from 'effect';
2 import * as Cli from 'src/commands';
3
4 // Run CLI in test environment
5 -export const cli = (args: ReadonlyArray<string>): Effect.Effect<void, unknown, any> =>
5 +export const cli = (args: ReadonlyArray<string>) =>
6 Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args]));
ts/packages/cli/test/__utils__/services/test-layer.ts
+6 -10
@@ -1,4 +1,5 @@
1 import * as tempy from 'tempy';
2 +import { Composio as RawComposioClient } from '@composio/client';
3 import { CliApp, CliConfig } from '@effect/cli';
4 import { Command, FetchHttpClient, FileSystem, Path } from '@effect/platform';
5 import { BunFileSystem, BunContext, BunPath } from '@effect/platform-bun';
@@ -218,7 +219,7 @@ export interface TestLiveInput {
219 * Layer<RequirementsOut, Error, RequirementsIn>
220 */
221
221 -type RequiredLayer = Layer.Layer<any, any, never>;
222 +type RequiredLayer = Layer.Layer<CliApp.CliApp.Environment, unknown, never>;
223
224 const ConsumerProjectResolveFetchMock = Layer.scopedDiscard(
225 Effect.acquireRelease(
@@ -989,7 +990,7 @@ export const TestLayer = (input?: TestLiveInput) =>
990 };
991 };
992
992 - const mockComposioClient = {
993 + const mockComposioClient = Object.assign(new RawComposioClient({ apiKey: 'test' }), {
994 link: {
995 create: async (params: { auth_config_id: string; user_id: string }) => {
996 const response = connectedAccountsData.linkResponse ?? {
@@ -1186,21 +1187,16 @@ export const TestLayer = (input?: TestLiveInput) =>
1187 }),
1188 },
1189 },
1189 - };
1190 + });
1191
1192 const ComposioClientSingletonTest = Layer.succeed(
1193 ComposioClientSingleton,
1194 new ComposioClientSingleton({
1195 get: Effect.fn(function* () {
1195 - // Partial mock: only implements `toolRouter.session.*` methods used by
1196 - // CLI commands under test. The full Composio client interface is too
1197 - // large to mock completely for unit tests.
1198 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
1199 - return mockComposioClient as any;
1196 + return mockComposioClient;
1197 }),
1198 getFor: Effect.fn(function* () {
1202 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
1203 - return mockComposioClient as any;
1199 + return mockComposioClient;
1200 }),
1201 })
1202 );
ts/packages/cli/test/src/commands/run.cmd.test.ts
+10 -10
@@ -42,7 +42,7 @@ describe('CLI: composio run', () => {
42 '[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',
43 () =>
44 Effect.gen(function* () {
45 - const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
45 + const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(7) }));
46 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
47 vi.stubGlobal('Bun', { spawn });
48
@@ -50,7 +50,7 @@ describe('CLI: composio run', () => {
50 const output = yield* MockConsole.getLines();
51
52 expect(spawn).toHaveBeenCalledTimes(1);
53 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
53 + const spawnConfig = spawn.mock.calls[0][0] as {
54 cmd: string[];
55 env: unknown;
56 stdio: string[];
@@ -81,14 +81,14 @@ describe('CLI: composio run', () => {
81 '[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
82 () =>
83 Effect.gen(function* () {
84 - const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
84 + const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
85 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
86 vi.stubGlobal('Bun', { spawn });
87
88 yield* cli(['run', '--acp-only', 'console.log("hi")']);
89
90 expect(spawn).toHaveBeenCalledTimes(1);
91 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
91 + const spawnConfig = spawn.mock.calls[0][0] as {
92 cmd: string[];
93 };
94 expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -102,14 +102,14 @@ describe('CLI: composio run', () => {
102 '[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
103 () =>
104 Effect.gen(function* () {
105 - const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
105 + const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
106 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
107 vi.stubGlobal('Bun', { spawn });
108
109 yield* cli(['run', '--logs-off', 'console.log("hi")']);
110
111 expect(spawn).toHaveBeenCalledTimes(1);
112 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
112 + const spawnConfig = spawn.mock.calls[0][0] as {
113 cmd: string[];
114 };
115 expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -140,14 +140,14 @@ describe('CLI: composio run', () => {
140 console.log(JSON.stringify(brief));
141 console.log(JSON.stringify(brief.structuredOutput));
142 `;
143 - const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
143 + const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
144 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
145 vi.stubGlobal('Bun', { spawn });
146
147 yield* cli(['run', '--logs-off', script]);
148
149 expect(spawn).toHaveBeenCalledTimes(1);
150 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
150 + const spawnConfig = spawn.mock.calls[0][0] as {
151 cmd: string[];
152 };
153 expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -171,7 +171,7 @@ describe('CLI: composio run', () => {
171 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
172 const scriptPath = path.join(tempDir, 'script.ts');
173 fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
174 - const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
174 + const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
175 const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
176 vi.stubGlobal('Bun', { spawn });
177
@@ -179,7 +179,7 @@ describe('CLI: composio run', () => {
179 yield* cli(['run', '--file', scriptPath, '--', 'hello']);
180
181 expect(spawn).toHaveBeenCalledTimes(1);
182 - const spawnConfig = (spawn as any).mock.calls[0][0] as {
182 + const spawnConfig = spawn.mock.calls[0][0] as {
183 cmd: string[];
184 env: unknown;
185 stdio: string[];
ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+9 -9
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
2 +import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
20 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
19 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250101', '20250601', '20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Execute code in a sandboxed environment',
35 categories: [],
36 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
37 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
36 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 1,
40 triggers_count: 0,
@@ -52,8 +52,8 @@ const detailedToolkits: ToolkitDetailed[] = [
52 meta: {
53 description: 'Email service to send and receive emails',
54 categories: [],
55 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
56 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
55 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
56 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
57 available_versions: ['20250101', '20250601', '20250909'],
58 tools_count: 36,
59 triggers_count: 2,
@@ -110,8 +110,8 @@ const detailedToolkits: ToolkitDetailed[] = [
110 meta: {
111 description: 'Execute code snippets',
112 categories: [],
113 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
114 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
113 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
114 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
115 available_versions: [],
116 tools_count: 5,
117 triggers_count: 0,
ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+7 -7
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
2 +import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
20 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
19 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250101', '20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Messaging platform for teams',
35 categories: [],
36 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
37 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
36 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 42,
40 triggers_count: 5,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
50 meta: {
51 description: 'Code hosting and collaboration platform',
52 categories: [],
53 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
54 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
53 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
54 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
55 available_versions: ['20260101'],
56 tools_count: 50,
57 triggers_count: 10,
ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
+7 -7
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
2 +import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
16 meta: {
17 description: 'Email service to send and receive emails',
18 categories: [],
19 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
20 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
19 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
21 available_versions: ['20250909'],
22 tools_count: 36,
23 triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
33 meta: {
34 description: 'Microsoft email service',
35 categories: [],
36 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
37 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
36 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
37 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
38 available_versions: [],
39 tools_count: 28,
40 triggers_count: 1,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
50 meta: {
51 description: 'Messaging platform for teams',
52 categories: [],
53 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
54 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
53 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
54 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
55 available_versions: ['20250101', '20260101'],
56 tools_count: 42,
57 triggers_count: 5,
ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
+5 -5
@@ -1,5 +1,5 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 -import { ConfigProvider, Effect } from 'effect';
2 +import { ConfigProvider, DateTime, Effect } from 'effect';
3 import { extendConfigProvider } from 'src/services/config';
4 import { cli, TestLive, MockConsole } from 'test/__utils__';
5 import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -21,8 +21,8 @@ const testToolkits: Toolkits = [
21 meta: {
22 description: 'Email service to send and receive emails',
23 categories: [],
24 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
25 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
24 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
25 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
26 available_versions: versionHistory,
27 tools_count: 36,
28 triggers_count: 2,
@@ -40,8 +40,8 @@ const detailedToolkits: ToolkitDetailed[] = [
40 meta: {
41 description: 'Email service to send and receive emails',
42 categories: [],
43 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
44 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
43 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
44 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
45 available_versions: versionHistory,
46 tools_count: 36,
47 triggers_count: 2,
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+9 -9
@@ -4,7 +4,7 @@ import * as path from 'node:path';
4 import { HelpDoc, ValidationError } from '@effect/cli';
5 import { describe, expect, it, layer } from '@effect/vitest';
6 import { vi, beforeEach, afterEach } from 'vitest';
7 -import { Config, ConfigProvider, Effect, Option, Predicate } from 'effect';
7 +import { Config, ConfigProvider, DateTime, Effect, Option, Predicate } from 'effect';
8 import { extendConfigProvider } from 'src/services/config';
9 import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
10 import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -675,8 +675,8 @@ describe('CLI: composio execute', () => {
675 meta: {
676 description: 'Email service',
677 categories: [],
678 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
679 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
678 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
679 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
680 available_versions: ['20260115_00', '20260101_00'],
681 tools_count: 36,
682 triggers_count: 2,
@@ -745,8 +745,8 @@ describe('CLI: composio execute', () => {
745 meta: {
746 description: 'Email service',
747 categories: [],
748 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
749 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
748 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
749 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
750 available_versions: ['20260316_00'],
751 tools_count: 36,
752 triggers_count: 2,
@@ -823,8 +823,8 @@ describe('CLI: composio execute', () => {
823 meta: {
824 description: 'Email service',
825 categories: [],
826 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
827 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
826 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
827 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
828 available_versions: ['20260115_00', '20260101_00'],
829 tools_count: 36,
830 triggers_count: 2,
@@ -1706,8 +1706,8 @@ describe('CLI: composio execute', () => {
1706 meta: {
1707 description: 'Email service',
1708 categories: [],
1709 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
1710 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
1709 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
1710 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
1711 available_versions: ['20260316_00'],
1712 tools_count: 36,
1713 triggers_count: 2,
ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+9 -9
@@ -1,7 +1,7 @@
1 import { describe, expect, layer } from '@effect/vitest';
2 import { vi, beforeEach, afterEach } from 'vitest';
3 import { FileSystem } from '@effect/platform';
4 -import { ConfigProvider, Effect, Option } from 'effect';
4 +import { ConfigProvider, DateTime, Effect, Option } from 'effect';
5 import path from 'node:path';
6 import { setupCacheDir } from 'src/effects/setup-cache-dir';
7 import { extendConfigProvider } from 'src/services/config';
@@ -83,8 +83,8 @@ describe('consumer short-term cache', () => {
83 meta: {
84 description: 'GitHub toolkit',
85 categories: [],
86 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
87 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
86 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
87 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
88 available_versions: [],
89 tools_count: 0,
90 triggers_count: 0,
@@ -100,8 +100,8 @@ describe('consumer short-term cache', () => {
100 meta: {
101 description: 'No-auth toolkit',
102 categories: [],
103 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
104 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
103 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
104 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
105 available_versions: [],
106 tools_count: 0,
107 triggers_count: 0,
@@ -147,8 +147,8 @@ describe('consumer short-term cache', () => {
147 meta: {
148 description: 'GitHub toolkit',
149 categories: [],
150 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
151 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
150 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
151 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
152 available_versions: [],
153 tools_count: 0,
154 triggers_count: 0,
@@ -164,8 +164,8 @@ describe('consumer short-term cache', () => {
164 meta: {
165 description: 'No-auth toolkit',
166 categories: [],
167 - created_at: new Date('2024-05-03T11:44:32.061Z') as any,
168 - updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
167 + created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
168 + updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
169 available_versions: [],
170 tools_count: 0,
171 triggers_count: 0,
ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+4 -2
@@ -5,7 +5,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5 import { FileSystem, Path } from '@effect/platform';
6 import { BunFileSystem, BunPath } from '@effect/platform-bun';
7 import { Effect, Layer } from 'effect';
8 -import type { Composio as RawComposioClient } from '@composio/client';
8 +import { Composio as RawComposioClient } from '@composio/client';
9 import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
10 import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
11
@@ -19,7 +19,9 @@ const inputSchema = {
19 };
20
21 const makeClient = (createPresignedURL = vi.fn()) =>
22 - ({ files: { createPresignedURL } }) as unknown as RawComposioClient;
22 + Object.assign(new RawComposioClient({ apiKey: 'test' }), {
23 + files: { createPresignedURL },
24 + });
25
26 describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
27 afterEach(() => {
ts/packages/core/src/types/tool.types.ts
+52 -8
@@ -26,10 +26,55 @@ const JSONSchemaType = z.enum([
26 'array',
27 'null',
28 ]);
29 +type JSONSchemaTypeName = z.infer<typeof JSONSchemaType>;
30
31 // JSON Schema property definition
31 -// eslint-disable-next-line @typescript-eslint/no-explicit-any
32 -export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
32 +export interface JSONSchemaProperty {
33 + [key: string]: unknown;
34 + type?: JSONSchemaTypeName | JSONSchemaTypeName[];
35 + description?: string;
36 + anyOf?: JSONSchemaProperty[];
37 + oneOf?: JSONSchemaProperty[];
38 + allOf?: JSONSchemaProperty[];
39 + not?: JSONSchemaProperty;
40 + title?: string;
41 + default?: unknown;
42 + nullable?: boolean;
43 + properties?: Record<string, JSONSchemaProperty>;
44 + required?: string[];
45 + file_uploadable?: boolean;
46 + file_downloadable?: boolean;
47 + items?: JSONSchemaProperty | JSONSchemaProperty[];
48 + enum?: unknown[];
49 + const?: unknown;
50 + minimum?: number;
51 + maximum?: number;
52 + exclusiveMinimum?: number;
53 + exclusiveMaximum?: number;
54 + multipleOf?: number;
55 + minLength?: number;
56 + maxLength?: number;
57 + pattern?: string;
58 + format?: string;
59 + minItems?: number;
60 + maxItems?: number;
61 + uniqueItems?: boolean;
62 + minProperties?: number;
63 + maxProperties?: number;
64 + patternProperties?: Record<string, JSONSchemaProperty>;
65 + additionalProperties?: boolean | JSONSchemaProperty;
66 + examples?: unknown[];
67 + readOnly?: boolean;
68 + writeOnly?: boolean;
69 + if?: JSONSchemaProperty;
70 + then?: JSONSchemaProperty;
71 + else?: JSONSchemaProperty;
72 + $ref?: string;
73 + definitions?: Record<string, JSONSchemaProperty>;
74 + $defs?: Record<string, JSONSchemaProperty>;
75 +}
76 +
77 +export const JSONSchemaPropertySchema: z.ZodType<JSONSchemaProperty> = z.object({
78 type: z.union([JSONSchemaType, z.array(JSONSchemaType)]).optional(),
79 description: z.string().optional(),
80 anyOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
@@ -37,7 +82,7 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
82 allOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
83 not: z.lazy(() => JSONSchemaPropertySchema).optional(),
84 title: z.string().optional(),
40 - default: z.any().optional(),
85 + default: z.unknown().optional(),
86 nullable: z.boolean().optional(),
87 properties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
88 required: z.array(z.string()).optional(),
@@ -46,8 +91,8 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
91 items: z
92 .lazy(() => z.union([JSONSchemaPropertySchema, z.array(JSONSchemaPropertySchema)]))
93 .optional(),
49 - enum: z.array(z.any()).optional(),
50 - const: z.any().optional(),
94 + enum: z.array(z.unknown()).optional(),
95 + const: z.unknown().optional(),
96 minimum: z.number().optional(),
97 maximum: z.number().optional(),
98 exclusiveMinimum: z.number().optional(),
@@ -64,7 +109,7 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
109 maxProperties: z.number().optional(),
110 patternProperties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
111 additionalProperties: z.union([z.boolean(), z.lazy(() => JSONSchemaPropertySchema)]).optional(),
67 - examples: z.array(z.any()).optional(),
112 + examples: z.array(z.unknown()).optional(),
113 readOnly: z.boolean().optional(),
114 writeOnly: z.boolean().optional(),
115 if: z.lazy(() => JSONSchemaPropertySchema).optional(),
@@ -84,7 +129,6 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
129 )
130 .optional(),
131 });
87 -export type JSONSchemaProperty = z.infer<typeof JSONSchemaPropertySchema>;
132
133 // Schema for parameters (input/output)
134 const ParametersSchema = z.preprocess(
@@ -98,7 +142,7 @@ const ParametersSchema = z.preprocess(
142 properties: z.record(z.string(), JSONSchemaPropertySchema),
143 required: z.array(z.string()).optional(),
144 title: z.string().optional(),
101 - default: z.any().optional(),
145 + default: z.unknown().optional(),
146 nullable: z.boolean().optional(),
147 description: z.string().optional(),
148 additionalProperties: z.boolean().default(false).optional(),
ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
+3 -3
@@ -39,9 +39,9 @@ import { withCancellation } from '../cancellation';
39 * whose schema omits the `$defs` target working (see
40 * https://github.com/ComposioHQ/composio/issues/3307) instead of throwing.
41 */
42 -const resolveFileSchema = (
43 - schema: JSONSchemaProperty | undefined
44 -): JSONSchemaProperty | undefined =>
42 +const resolveFileSchema = <Schema extends JSONSchemaProperty>(
43 + schema: Schema | undefined
44 +): Schema | undefined =>
45 schema ? dereferenceJsonSchema(schema, { onUnresolved: 'sentinel' }) : schema;
46
47 const getSchemaVariants = (schema: JSONSchemaProperty | undefined): JSONSchemaProperty[] => [
ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
+6 -4
@@ -59,10 +59,12 @@ const transformSchema = (property: JSONSchemaProperty): JSONSchemaProperty => {
59 * @param properties - The properties of the tool schema.
60 * @returns The transformed properties.
61 */
62 -export const transformProperties = (properties: JSONSchemaProperty): JSONSchemaProperty => {
63 - const newProperties: JSONSchemaProperty = {};
62 +export const transformProperties = (
63 + properties: Record<string, JSONSchemaProperty>
64 +): Record<string, JSONSchemaProperty> => {
65 + const newProperties: Record<string, JSONSchemaProperty> = {};
66
65 - for (const [key, property] of Object.entries(properties) as [string, JSONSchemaProperty][]) {
67 + for (const [key, property] of Object.entries(properties)) {
68 newProperties[key] = transformSchema(property);
69 }
70
@@ -81,7 +83,7 @@ export const schemaHasFileProperty = (
83
84 // Check nested properties
85 if (schema.properties) {
84 - for (const prop of Object.values(schema.properties) as JSONSchemaProperty[]) {
86 + for (const prop of Object.values(schema.properties)) {
87 if (schemaHasFileProperty(prop, property)) return true;
88 }
89 }
ts/packages/core/test/connectedAccounts/connectedAccountAuthStates.test.ts
+2 -4
@@ -95,8 +95,7 @@ describe('connectedAccountAuthStates — REVOKED arms', () => {
95 revoked_at: '2026-05-01T00:00:00Z',
96 },
97 },
98 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
99 - } as any);
98 + } as unknown as Parameters<typeof transformConnectedAccountResponse>[0]);
99
100 expect(transformed.status).toBe(ConnectionStatuses.REVOKED);
101 expect(transformed.state).toBeDefined();
@@ -116,8 +115,7 @@ describe('connectedAccountAuthStates — REVOKED arms', () => {
115 revoked_at: '2026-05-01T00:00:00Z',
116 },
117 },
119 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
120 - } as any);
118 + } as unknown as Parameters<typeof transformConnectedAccountResponse>[0]);
119
120 expect(transformed.state).toBeDefined();
121 expect(transformed.state?.authScheme).toBe(AuthSchemeTypes.S2S_OAUTH2);
ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+3 -3
@@ -861,7 +861,7 @@ describe('ConnectedAccounts', () => {
861 const nanoid = 'conn_123';
862 const invalidOptions = { redirectUrl: 123 };
863
864 - await expect(connectedAccounts.refresh(nanoid, invalidOptions as any)).rejects.toThrow(
864 + await expect(connectedAccounts.refresh(nanoid, invalidOptions as unknown)).rejects.toThrow(
865 'Failed to parse connected account refresh options'
866 );
867
@@ -1171,7 +1171,7 @@ describe('ConnectedAccounts', () => {
1171
1172 it('should throw ValidationError for invalid params', async () => {
1173 await expect(
1174 - connectedAccounts.update('conn_abc123', { enabled: 'yes' } as any)
1174 + connectedAccounts.update('conn_abc123', { enabled: 'yes' } as unknown)
1175 ).rejects.toThrow('Failed to parse connected account update params');
1176 });
1177 });
@@ -1265,7 +1265,7 @@ describe('ConnectedAccounts', () => {
1265 };
1266
1267 await expect(
1268 - connectedAccounts.link(userId, authConfigId, invalidOptions as any)
1268 + connectedAccounts.link(userId, authConfigId, invalidOptions as unknown)
1269 ).rejects.toThrow('Failed to parse create connected account link options');
1270
1271 // Ensure API was not called with invalid options
ts/packages/core/test/core/session.test.ts
+2 -2
@@ -112,7 +112,7 @@ describe('Composio Session Management', () => {
112
113 it('should expose sessions.create and keep composio.create as a bound alias', async () => {
114 const composio = new Composio(baseConfig);
115 - const client = composio.getClient() as any;
115 + const client = composio.getClient() as unknown;
116 client.toolRouter.session.create = vi.fn().mockResolvedValue({
117 session_id: 'session_123',
118 mcp: {
@@ -185,7 +185,7 @@ describe('Session Headers Generation', () => {
185 it('should use fallback source when provider name is undefined', () => {
186 const mockProvider = {
187 name: undefined,
188 - } as any;
188 + } as unknown;
189 const headers = getSessionHeaders(mockProvider);
190
191 expect(headers).toEqual({
ts/packages/core/test/core/versions.test.ts
+5 -5
@@ -98,7 +98,7 @@ describe('Version Management', () => {
98 });
99
100 it('should return the string version as-is when user provides specific version', () => {
101 - const result = getToolkitVersionsFromEnv('20250902_00' as any);
101 + const result = getToolkitVersionsFromEnv('20250902_00' as unknown);
102 expect(result).toBe('20250902_00');
103 });
104
@@ -106,7 +106,7 @@ describe('Version Management', () => {
106 process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20250901_01';
107 process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
108
109 - const result = getToolkitVersionsFromEnv('20250902_00' as any);
109 + const result = getToolkitVersionsFromEnv('20250902_00' as unknown);
110 expect(result).toBe('20250902_00');
111 });
112 });
@@ -304,7 +304,7 @@ describe('Version Management', () => {
304 });
305
306 it('should return "latest" when toolkitVersions is null', () => {
307 - const result = getToolkitVersion('github', null as any);
307 + const result = getToolkitVersion('github', null as unknown);
308 expect(result).toBe('latest');
309 });
310 });
@@ -336,7 +336,7 @@ describe('Version Management', () => {
336 const toolkitVersions = {
337 github: '20250902_00',
338 slack: 'latest',
339 - } as any;
339 + } as unknown;
340
341 expect(getToolkitVersion('github', toolkitVersions)).toBe('20250902_00');
342 expect(getToolkitVersion('slack', toolkitVersions)).toBe('latest');
@@ -373,7 +373,7 @@ describe('Version Management', () => {
373 process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
374
375 // User provides global version
376 - const toolkitVersions = getToolkitVersionsFromEnv('20250902_00' as any);
376 + const toolkitVersions = getToolkitVersionsFromEnv('20250902_00' as unknown);
377
378 // All toolkits should get the global version
379 expect(getToolkitVersion('github', toolkitVersions)).toBe('20250902_00');
ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+14 -13
@@ -1,4 +1,5 @@
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
4 import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
5 import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
@@ -14,18 +15,18 @@ const mockLookup = vi.mocked(lookup);
15
16 const sessionId = 'trs_session_123';
17
17 -const createMockClient = () => ({
18 - toolRouter: {
19 - session: {
20 - files: {
21 - list: vi.fn(),
22 - createUploadURL: vi.fn(),
23 - createDownloadURL: vi.fn(),
24 - delete: vi.fn(),
25 - },
26 - },
27 - },
28 -});
18 +const createMockClient = () => {
19 + const client = new ComposioClient({ apiKey: 'test-api-key' });
20 + const files = Object.assign(client.toolRouter.session.files, {
21 + list: vi.fn<typeof client.toolRouter.session.files.list>(),
22 + createUploadURL: vi.fn<typeof client.toolRouter.session.files.createUploadURL>(),
23 + createDownloadURL: vi.fn<typeof client.toolRouter.session.files.createDownloadURL>(),
24 + delete: vi.fn<typeof client.toolRouter.session.files.delete>(),
25 + });
26 + const session = Object.assign(client.toolRouter.session, { files });
27 + const toolRouter = Object.assign(client.toolRouter, { session });
28 + return Object.assign(client, { toolRouter });
29 +};
30
31 describe('ToolRouterSessionFilesMount', () => {
32 let mockClient: ReturnType<typeof createMockClient>;
@@ -35,7 +36,7 @@ describe('ToolRouterSessionFilesMount', () => {
36 vi.clearAllMocks();
37 mockLookup.mockReset();
38 mockClient = createMockClient();
38 - filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);
39 + filesMount = new ToolRouterSessionFilesMount(mockClient, sessionId);
40 });
41
42 describe('list', () => {
ts/packages/core/test/models/customTool.test.ts
+26 -26
@@ -1,4 +1,5 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 +import ComposioClient from '@composio/client';
3 import { z as z4 } from 'zod';
4 import { z } from 'zod/v3';
5 import {
@@ -227,20 +228,20 @@ describe('createCustomTool', () => {
228 });
229
230 it('should throw if inputParams is missing', () => {
230 - expect(() => createCustomTool('SLUG', { ...baseOptions, inputParams: null as any })).toThrow(
231 - 'inputParams is required'
232 - );
231 + expect(() =>
232 + createCustomTool('SLUG', { ...baseOptions, inputParams: null as unknown })
233 + ).toThrow('inputParams is required');
234 });
235
236 it('should throw if execute is not a function', () => {
236 - expect(() => createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as any })).toThrow(
237 - 'execute must be a function'
238 - );
237 + expect(() =>
238 + createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as unknown })
239 + ).toThrow('execute must be a function');
240 });
241
242 it('should throw if a Zod v4 input schema is not an object', () => {
243 expect(() =>
243 - createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as any })
244 + createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as unknown })
245 ).toThrow('inputParams must be a z.object() schema');
246 });
247 });
@@ -254,7 +255,7 @@ describe('createCustomTool', () => {
255 execute: noSessionExecute,
256 });
257
257 - const result = await tool.execute({ category: 'test' } as any);
258 + const result = await tool.execute({ category: 'test' } as unknown);
259 expect(result.result).toBe(42);
260 expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
261 });
@@ -612,21 +613,20 @@ describe('serializeCustomToolkits', () => {
613 // ────────────────────────────────────────────────────────────────
614
615 describe('SessionContextImpl', () => {
615 - const mockClient = {
616 - toolRouter: {
617 - session: {
618 - execute: vi.fn(),
619 - proxyExecute: vi.fn(),
620 - },
621 - },
622 - };
616 + const client = new ComposioClient({ apiKey: 'test-api-key' });
617 + const session = Object.assign(client.toolRouter.session, {
618 + execute: vi.fn<typeof client.toolRouter.session.execute>(),
619 + proxyExecute: vi.fn<typeof client.toolRouter.session.proxyExecute>(),
620 + });
621 + const toolRouter = Object.assign(client.toolRouter, { session });
622 + const mockClient = Object.assign(client, { toolRouter });
623
624 beforeEach(() => {
625 vi.clearAllMocks();
626 });
627
628 it('should expose userId', () => {
629 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
629 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
630 expect(ctx.userId).toBe('user_1');
631 });
632
@@ -637,7 +637,7 @@ describe('SessionContextImpl', () => {
637 log_id: 'log_1',
638 });
639
640 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
640 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
641 const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: 'test@test.com' });
642
643 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
@@ -662,7 +662,7 @@ describe('SessionContextImpl', () => {
662 log_id: 'log_1',
663 });
664
665 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', undefined, {
665 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', undefined, {
666 custom_tools: [
667 {
668 slug: 'GREP',
@@ -694,7 +694,7 @@ describe('SessionContextImpl', () => {
694 log_id: 'log_2',
695 });
696
697 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
697 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
698 const result = await ctx.execute('BAD_TOOL', {});
699
700 expect(result.logId).toBe('log_2');
@@ -706,7 +706,7 @@ describe('SessionContextImpl', () => {
706 status: 200,
707 data: { proxy_result: true },
708 });
709 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
709 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
710
711 const result = await ctx.proxyExecute({
712 toolkit: 'github',
@@ -732,9 +732,9 @@ describe('SessionContextImpl', () => {
732 });
733
734 it('should throw on proxyExecute() with invalid params', async () => {
735 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
735 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
736 await expect(
737 - ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as any })
737 + ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as unknown })
738 ).rejects.toThrow('Invalid proxy execute parameters');
739 });
740
@@ -750,7 +750,7 @@ describe('SessionContextImpl', () => {
750 }),
751 ]);
752
753 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
753 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
754 const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
755
756 expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
@@ -774,7 +774,7 @@ describe('SessionContextImpl', () => {
774 log_id: 'log_3',
775 });
776
777 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
777 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
778 const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
779
780 expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
@@ -795,7 +795,7 @@ describe('SessionContextImpl', () => {
795 log_id: 'log_4',
796 });
797
798 - const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
798 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
799 const result = await ctx.execute('ANY_TOOL', {});
800
801 expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
ts/packages/core/test/models/customToolRouting.test.ts
+106 -51
@@ -5,8 +5,45 @@ import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5 import { createCustomTool, buildCustomToolsMap } from '../../src/models/CustomTool';
6 import { MockProvider } from '../utils/mocks/provider.mock';
7 import ComposioClient from '@composio/client';
8 -import { Tools } from '../../src/models/Tools';
9 -import type { CustomTool } from '../../src/types/customTool.types';
8 +import type { CustomTool, SessionContext } from '../../src/types/customTool.types';
9 +import type { ComposioConfig } from '../../src/composio';
10 +
11 +type MultiExecuteResultItem = {
12 + tool_slug: string;
13 + index?: number;
14 + response: {
15 + successful: boolean;
16 + data?: unknown;
17 + error?: string;
18 + };
19 + error?: string;
20 +};
21 +
22 +// Single-tool passthrough responses do not use the results array.
23 +type MultiExecuteResponse = {
24 + data: {
25 + results: MultiExecuteResultItem[];
26 + total_count?: number;
27 + success_count?: number;
28 + error_count?: number;
29 + [key: string]: unknown;
30 + };
31 + error: string | null;
32 + successful: boolean;
33 +};
34 +
35 +type CapturedExecuteFn = (
36 + toolSlug: string,
37 + input: Record<string, unknown>
38 +) => Promise<MultiExecuteResponse>;
39 +
40 +type MockedToolsInstance = {
41 + executeSessionTool: ReturnType<typeof vi.fn>;
42 +};
43 +
44 +const toolsMockState = vi.hoisted(() => ({
45 + latestInstance: undefined as MockedToolsInstance | undefined,
46 +}));
47
48 // Mock telemetry
49 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -16,7 +53,7 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
53 // Mock Tools class
54 vi.mock('../../src/models/Tools', () => ({
55 Tools: vi.fn().mockImplementation(function () {
19 - return {
56 + const instance = {
57 getRawToolRouterSessionTools: vi.fn().mockResolvedValue([
58 { slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' },
59 { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' },
@@ -28,9 +65,24 @@ vi.mock('../../src/models/Tools', () => ({
65 successful: true,
66 }),
67 };
68 +
69 + toolsMockState.latestInstance = instance;
70 + return instance;
71 }),
72 }));
73
74 +const getLatestToolsInstance = (): MockedToolsInstance => {
75 + const instance = toolsMockState.latestInstance;
76 + if (!instance) {
77 + throw new Error('Expected the Tools mock to have been instantiated');
78 + }
79 + return instance;
80 +};
81 +
82 +beforeEach(() => {
83 + toolsMockState.latestInstance = undefined;
84 +});
85 +
86 // ── Fixtures ─────────────────────────────────────────────────────
87
88 const createMockClient = () => ({
@@ -83,7 +135,7 @@ const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
135 execute: localExecute,
136 });
137
86 -const sessionExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => ({
138 +const sessionExecute = vi.fn().mockImplementation(async (input: unknown, ctx: SessionContext) => ({
139 userId: ctx.userId,
140 }));
141
@@ -114,11 +166,12 @@ const createSessionWithProvider = (
166 };
167
168 const captureExecuteFn = (provider: MockProvider) => {
117 - provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
118 - (provider as any)._capturedExecuteFn = executeFn;
119 - (provider as any)._capturedTools = tools;
169 + let executeFn: CapturedExecuteFn;
170 + provider.wrapTools.mockImplementation((_tools: unknown, capturedExecuteFn: unknown) => {
171 + executeFn = capturedExecuteFn as CapturedExecuteFn;
172 return 'wrapped-tools-with-routing';
173 });
174 + return () => executeFn;
175 };
176
177 // ────────────────────────────────────────────────────────────────
@@ -373,10 +426,12 @@ describe('ToolRouterSession execution routing', () => {
426 });
427
428 it('should provide a working execute() on SessionContext for remote tools', async () => {
376 - const chainedExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
377 - const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
378 - return { inner_result: inner.data };
379 - });
429 + const chainedExecute = vi
430 + .fn()
431 + .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => {
432 + const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
433 + return { inner_result: inner.data };
434 + });
435
436 const chainedTool = createCustomTool('CHAINED_TOOL', {
437 name: 'Chained',
@@ -407,10 +462,12 @@ describe('ToolRouterSession execution routing', () => {
462 execute: siblingExecute,
463 });
464
410 - const toolAExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
411 - const inner = await ctx.execute('TOOL_B', { key: input.value });
412 - return { fromA: true, fromB: inner.data };
413 - });
465 + const toolAExecute = vi
466 + .fn()
467 + .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => {
468 + const inner = await ctx.execute('TOOL_B', { key: input.value });
469 + return { fromA: true, fromB: inner.data };
470 + });
471 const toolA = createCustomTool('TOOL_A', {
472 name: 'Tool A',
473 description: 'Calls sibling tool B',
@@ -452,7 +509,7 @@ describe('ToolRouterSession execution routing', () => {
509 });
510
511 it('should apply Zod defaults when input is missing optional fields', async () => {
455 - const defaultExecute = vi.fn().mockImplementation(async (input: any) => ({
512 + const defaultExecute = vi.fn().mockImplementation(async (input: Record<string, unknown>) => ({
513 category: input.category,
514 }));
515
@@ -505,11 +562,11 @@ describe('ToolRouterSession execution routing', () => {
562 describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing with tools[] array', () => {
563 it('should route all-local tools[] to in-process execution', async () => {
564 const provider = new MockProvider();
508 - captureExecuteFn(provider);
565 + const getExecuteFn = captureExecuteFn(provider);
566 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
567
568 await session.tools();
512 - const executeFn = (provider as any)._capturedExecuteFn;
569 + const executeFn = getExecuteFn();
570
571 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
572 tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } }],
@@ -525,11 +582,11 @@ describe('ToolRouterSession execution routing', () => {
582
583 it('should route local tool by non-prefixed slug in multi-execute', async () => {
584 const provider = new MockProvider();
528 - captureExecuteFn(provider);
585 + const getExecuteFn = captureExecuteFn(provider);
586 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
587
588 await session.tools();
532 - const executeFn = (provider as any)._capturedExecuteFn;
589 + const executeFn = getExecuteFn();
590
591 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
592 tools: [{ tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } }],
@@ -545,11 +602,11 @@ describe('ToolRouterSession execution routing', () => {
602
603 it('should route all-remote tools[] to backend', async () => {
604 const provider = new MockProvider();
548 - captureExecuteFn(provider);
605 + const getExecuteFn = captureExecuteFn(provider);
606 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
607
608 await session.tools();
552 - const executeFn = (provider as any)._capturedExecuteFn;
609 + const executeFn = getExecuteFn();
610
611 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
612 tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: 'test@test.com' } }],
@@ -562,11 +619,11 @@ describe('ToolRouterSession execution routing', () => {
619
620 it('should route non-MULTI_EXECUTE session tools to backend', async () => {
621 const provider = new MockProvider();
565 - captureExecuteFn(provider);
622 + const getExecuteFn = captureExecuteFn(provider);
623 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
624
625 await session.tools();
569 - const executeFn = (provider as any)._capturedExecuteFn;
626 + const executeFn = getExecuteFn();
627
628 const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
629 queries: [{ use_case: 'send email' }],
@@ -595,16 +652,17 @@ describe('ToolRouterSession execution routing', () => {
652 customTools: CustomTool[]
653 ) => {
654 const provider = new MockProvider();
598 - captureExecuteFn(provider);
655 + const getExecuteFn = captureExecuteFn(provider);
656 const session = createSessionWithProvider(client, provider, customTools);
657 await session.tools();
601 - const executeFn = (provider as any)._capturedExecuteFn;
602 - const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
603 - .value;
658 + const executeFn = getExecuteFn();
659 + const toolsInstance = getLatestToolsInstance();
660 return { executeFn, toolsInstance, provider, session };
661 };
662
607 - const backendResponse = (results: Array<{ tool_slug: string; data: any; error?: string }>) => {
663 + const backendResponse = (
664 + results: Array<{ tool_slug: string; data: unknown; error?: string }>
665 + ) => {
666 const items = results.map((r, i) => ({
667 response: {
668 successful: !r.error,
@@ -628,8 +686,8 @@ describe('ToolRouterSession execution routing', () => {
686 };
687 };
688
631 - const findResult = (results: any[], slug: string) =>
632 - results.find((r: any) => r.tool_slug === slug);
689 + const findResult = (results: MultiExecuteResultItem[], slug: string) =>
690 + results.find(r => r.tool_slug === slug);
691
692 it('should append local results to remote results array', async () => {
693 const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
@@ -649,8 +707,8 @@ describe('ToolRouterSession execution routing', () => {
707 const { results } = result.data;
708 expect(results).toHaveLength(2);
709
652 - const remote = findResult(results, 'GMAIL_SEND_EMAIL');
653 - const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
710 + const remote = findResult(results, 'GMAIL_SEND_EMAIL')!;
711 + const local = findResult(results, 'LOCAL_GET_USER_CONTEXT')!;
712 expect(remote.response.data).toEqual({ sent: true });
713 expect(local.response.data).toEqual({ local_result: true });
714 expect(local.response.successful).toBe(true);
@@ -714,7 +772,7 @@ describe('ToolRouterSession execution routing', () => {
772 expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
773 expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
774 expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
717 - expect(results.map((entry: any) => entry.tool_slug)).toEqual([
775 + expect(results.map(entry => entry.tool_slug)).toEqual([
776 'LOCAL_GET_USER_CONTEXT',
777 'GMAIL_SEND_EMAIL',
778 'LOCAL_META_ADS_GET_AD_ACCOUNTS',
@@ -723,7 +781,7 @@ describe('ToolRouterSession execution routing', () => {
781
782 const backendTools = toolsInstance.executeSessionTool.mock.calls[0][1].arguments.tools;
783 expect(backendTools).toHaveLength(2);
726 - expect(backendTools.map((t: any) => t.tool_slug)).toEqual([
784 + expect(backendTools.map((t: { tool_slug: string }) => t.tool_slug)).toEqual([
785 'GMAIL_SEND_EMAIL',
786 'SLACK_POST_MESSAGE',
787 ]);
@@ -838,15 +896,15 @@ describe('ToolRouterSession execution routing', () => {
896 const { results } = result.data;
897 expect(results).toHaveLength(4);
898
841 - const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
899 + const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT')!;
900 expect(localOk.response.successful).toBe(true);
901
844 - const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
902 + const localErr = findResult(results, 'LOCAL_MIXED_THROWER')!;
903 expect(localErr.response.successful).toBe(false);
904 expect(localErr.response.error).toBe('batch-boom');
905 expect(localErr.error).toBe('batch-boom');
906
849 - const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
907 + const remoteErr = findResult(results, 'SLACK_POST_MESSAGE')!;
908 expect(remoteErr.response.error).toBe('auth failed');
909
910 expect(result.successful).toBe(false);
@@ -931,12 +989,11 @@ describe('ToolRouterSession execution routing', () => {
989 });
990
991 const provider = new MockProvider();
934 - captureExecuteFn(provider);
992 + const getExecuteFn = captureExecuteFn(provider);
993 const session = createSessionWithProvider(mockClient, provider, [slowLocalHandle]);
994 await session.tools();
937 - const executeFn = (provider as any)._capturedExecuteFn;
938 - const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
939 - .value;
995 + const executeFn = getExecuteFn();
996 + const toolsInstance = getLatestToolsInstance();
997
998 toolsInstance.executeSessionTool.mockImplementation(async () => {
999 callOrder.push('remote-start');
@@ -985,14 +1042,12 @@ describe('ToolRouterSession execution routing', () => {
1042 describe('per-tool results — each tool gets its own entry in results[]', () => {
1043 it('should return per-tool results for mixed local+remote batch', async () => {
1044 const provider = new MockProvider();
988 - captureExecuteFn(provider);
1045 + const getExecuteFn = captureExecuteFn(provider);
1046 const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
1047
1048 await session.tools();
1049
993 - const latestToolsInstance = (Tools as any).mock.results[
994 - (Tools as any).mock.results.length - 1
995 - ].value;
1050 + const latestToolsInstance = getLatestToolsInstance();
1051 latestToolsInstance.executeSessionTool.mockResolvedValueOnce({
1052 data: {
1053 results: [
@@ -1015,7 +1070,7 @@ describe('ToolRouterSession execution routing', () => {
1070 successful: true,
1071 });
1072
1018 - const executeFn = (provider as any)._capturedExecuteFn;
1073 + const executeFn = getExecuteFn();
1074
1075 const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
1076 tools: [
@@ -1029,9 +1084,9 @@ describe('ToolRouterSession execution routing', () => {
1084 const { results } = result.data;
1085 expect(results).toHaveLength(3);
1086
1032 - const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
1033 - const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
1034 - const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
1087 + const local = results.find(r => r.tool_slug === 'LOCAL_GET_USER_CONTEXT')!;
1088 + const gmail = results.find(r => r.tool_slug === 'GMAIL_SEND_EMAIL')!;
1089 + const slack = results.find(r => r.tool_slug === 'SLACK_POST_MESSAGE')!;
1090
1091 expect(local.response.data).toEqual({ local_result: true });
1092 expect(gmail.response.data).toEqual({ message_id: 'msg_1' });
@@ -1045,7 +1100,7 @@ describe('ToolRouterSession execution routing', () => {
1100
1101 const session = new ToolRouterSession(
1102 mockClient as unknown as ComposioClient,
1048 - { apiKey: 'key' } as any,
1103 + { apiKey: 'key' } as unknown as ComposioConfig<MockProvider>,
1104 'sess_123',
1105 { type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
1106 undefined,
ts/packages/core/test/models/mcp.test.ts
+6 -4
@@ -120,7 +120,9 @@ describe('MCP', () => {
120 });
121
122 it('should validate configuration', async () => {
123 - await expect(mcp.create('test', { toolkits: null as any })).rejects.toThrow(ValidationError);
123 + await expect(mcp.create('test', { toolkits: null as unknown })).rejects.toThrow(
124 + ValidationError
125 + );
126 });
127 });
128
@@ -198,7 +200,7 @@ describe('MCP', () => {
200 });
201
202 it('should handle validation errors', async () => {
201 - await expect(mcp.list({ page: 'invalid' as any })).rejects.toThrow(ValidationError);
203 + await expect(mcp.list({ page: 'invalid' as unknown })).rejects.toThrow(ValidationError);
204 });
205 });
206
@@ -287,7 +289,7 @@ describe('MCP', () => {
289 });
290
291 it('should validate update parameters', async () => {
290 - await expect(mcp.update('mcp_123', { toolkits: 'invalid' as any })).rejects.toThrow(
292 + await expect(mcp.update('mcp_123', { toolkits: 'invalid' as unknown })).rejects.toThrow(
293 ValidationError
294 );
295 });
@@ -369,7 +371,7 @@ describe('MCP', () => {
371 mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
372
373 await expect(
372 - mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as any })
374 + mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as unknown })
375 ).rejects.toThrow(ValidationError);
376 });
377 });
ts/packages/core/test/models/toolRouter.test.ts
+14 -14
@@ -1814,7 +1814,7 @@ describe('ToolRouter', () => {
1814 it('should throw error for invalid configuration', async () => {
1815 const invalidConfig = {
1816 toolkits: 'invalid-toolkits', // Should be array or object
1817 - } as any;
1817 + } as unknown;
1818
1819 await expect(toolRouter.create(userId, invalidConfig)).rejects.toThrow();
1820 });
@@ -2673,7 +2673,7 @@ describe('ToolRouter', () => {
2673 beforeEach(() => {
2674 // Reset the Tools mock before each test
2675 vi.clearAllMocks();
2676 - (Tools as any).mockImplementation(function () {
2676 + vi.mocked(Tools).mockImplementation(function () {
2677 return {
2678 getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
2679 getRawToolRouterSessionTools: vi
@@ -2695,7 +2695,7 @@ describe('ToolRouter', () => {
2695 apiKey: 'test-api-key',
2696 });
2697
2698 - const toolsInstance = (Tools as any).mock.results[0].value;
2698 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
2699 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
2700 sessionId,
2701 undefined,
@@ -2724,7 +2724,7 @@ describe('ToolRouter', () => {
2724 const session = await toolRouter.create(userId);
2725 const tools = await session.tools(modifiers);
2726
2727 - const toolsInstance = (Tools as any).mock.results[0].value;
2727 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
2728 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
2729 sessionId,
2730 { modifySchema: modifiers.modifySchema },
@@ -2747,7 +2747,7 @@ describe('ToolRouter', () => {
2747 },
2748 });
2749
2750 - (Tools as any).mockImplementation(function () {
2750 + vi.mocked(Tools).mockImplementation(function () {
2751 return {
2752 getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
2753 getRawToolRouterSessionTools: vi
@@ -2766,7 +2766,7 @@ describe('ToolRouter', () => {
2766 });
2767 const tools = await session.tools();
2768
2769 - const toolsInstance = (Tools as any).mock.results[0].value;
2769 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
2770 expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
2771 sessionId,
2772 [
@@ -2849,7 +2849,7 @@ describe('ToolRouter', () => {
2849 error: null,
2850 successful: true,
2851 });
2852 - (Tools as any).mockImplementation(function () {
2852 + vi.mocked(Tools).mockImplementation(function () {
2853 return {
2854 getRawToolRouterSessionTools: vi
2855 .fn()
@@ -2910,7 +2910,7 @@ describe('ToolRouter', () => {
2910 successful: true,
2911 });
2912 const multiExecuteTool = { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' };
2913 - (Tools as any).mockImplementation(function () {
2913 + vi.mocked(Tools).mockImplementation(function () {
2914 return {
2915 getRawToolRouterSessionTools: vi
2916 .fn()
@@ -3028,7 +3028,7 @@ describe('ToolRouter', () => {
3028 it('should handle tools fetching errors', async () => {
3029 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
3030
3031 - (Tools as any).mockImplementation(function () {
3031 + vi.mocked(Tools).mockImplementation(function () {
3032 return {
3033 getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
3034 getRawToolRouterSessionTools: vi
@@ -3058,7 +3058,7 @@ describe('ToolRouter', () => {
3058
3059 expect(Tools).toHaveBeenCalledTimes(2);
3060
3061 - const firstToolsInstance = (Tools as any).mock.results[0].value;
3061 + const firstToolsInstance = vi.mocked(Tools).mock.results[0].value;
3062 expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3063 sessionId,
3064 { modifySchema: modifier1.modifySchema },
@@ -3070,7 +3070,7 @@ describe('ToolRouter', () => {
3070 modifier1
3071 );
3072
3073 - const secondToolsInstance = (Tools as any).mock.results[1].value;
3073 + const secondToolsInstance = vi.mocked(Tools).mock.results[1].value;
3074 expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3075 sessionId,
3076 { modifySchema: modifier2.modifySchema },
@@ -3099,7 +3099,7 @@ describe('ToolRouter', () => {
3099 provider: mockProvider,
3100 apiKey: 'test-api-key',
3101 });
3102 - const toolsInstance = (Tools as any).mock.results[0].value;
3102 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
3103 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3104 'custom_session_123',
3105 undefined,
@@ -3128,7 +3128,7 @@ describe('ToolRouter', () => {
3128 provider: mockProvider,
3129 apiKey: 'test-api-key',
3130 });
3131 - const toolsInstance = (Tools as any).mock.results[0].value;
3131 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
3132 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3133 'empty_session_123',
3134 undefined,
@@ -3381,7 +3381,7 @@ describe('ToolRouter', () => {
3381 expect(tools).toBe('mocked-wrapped-tools');
3382 expect(Tools).toHaveBeenCalled();
3383
3384 - const toolsInstance = (Tools as any).mock.results[0].value;
3384 + const toolsInstance = vi.mocked(Tools).mock.results[0].value;
3385 expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
3386 sessionId,
3387 undefined,
ts/packages/core/test/models/toolkits.test.ts
+26 -7
@@ -5,6 +5,7 @@ import { telemetry } from '../../src/telemetry/Telemetry';
5 import { ComposioAuthConfigNotFoundError } from '../../src/errors/AuthConfigErrors';
6 import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
7 import { APIError } from '@composio/client';
8 +import type { ToolkitListParams } from '../../src/types/toolkit.types';
9
10 // Mock dependencies
11 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -13,6 +14,12 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
14 },
15 }));
16
17 +// Minimal structural shape for overriding `Toolkits.prototype.getToolkitBySlug`
18 +// (a protected method) with a mock implementation in tests.
19 +type ToolkitsPrototypeOverride = {
20 + getToolkitBySlug: unknown;
21 +};
22 +
23 // Create mock client with toolkit-related methods
24 const createMockClient = () => ({
25 baseURL: 'https://api.composio.dev',
@@ -222,7 +229,7 @@ describe('Toolkits', () => {
229 });
230
231 it('should throw ValidationError for invalid list query', async () => {
225 - const promise = toolkits.get({ category: 123 } as any);
232 + const promise = toolkits.get({ category: 123 } as unknown as ToolkitListParams);
233 await expect(promise).rejects.toThrowError('Failed to fetch toolkits');
234 });
235
@@ -552,7 +559,9 @@ describe('Toolkits', () => {
559 };
560
561 beforeEach(() => {
555 - vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
562 + vi.spyOn(Toolkits.prototype as unknown, 'getToolkitBySlug').mockResolvedValue(
563 + mockToolkit as unknown
564 + );
565 });
566
567 it('returns all fields when requiredOnly is false', async () => {
@@ -617,7 +626,9 @@ describe('Toolkits', () => {
626 },
627 ],
628 };
620 - (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
629 + (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
630 + .fn()
631 + .mockResolvedValueOnce(multiToolkit);
632 const result = await toolkits.getAuthConfigCreationFields(
633 toolkitSlug,
634 AuthSchemeTypes.API_KEY,
@@ -629,7 +640,9 @@ describe('Toolkits', () => {
640 });
641
642 it('throws if no authConfigDetails', async () => {
632 - (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
643 + (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
644 + .fn()
645 + .mockResolvedValueOnce({});
646 await expect(
647 toolkits.getAuthConfigCreationFields(toolkitSlug, AuthSchemeTypes.API_KEY, {
648 requiredOnly: true,
@@ -660,7 +673,9 @@ describe('Toolkits', () => {
673 };
674
675 beforeEach(() => {
663 - vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
676 + vi.spyOn(Toolkits.prototype as unknown, 'getToolkitBySlug').mockResolvedValue(
677 + mockToolkit as unknown
678 + );
679 });
680
681 it('returns all fields when requiredOnly is false', async () => {
@@ -713,7 +728,9 @@ describe('Toolkits', () => {
728 },
729 ],
730 };
716 - (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
731 + (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
732 + .fn()
733 + .mockResolvedValueOnce(multiToolkit);
734 const result = await toolkits.getConnectedAccountInitiationFields(
735 toolkitSlug,
736 AuthSchemeTypes.API_KEY,
@@ -725,7 +742,9 @@ describe('Toolkits', () => {
742 });
743
744 it('throws if no authConfigDetails', async () => {
728 - (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
745 + (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
746 + .fn()
747 + .mockResolvedValueOnce({});
748 await expect(
749 toolkits.getConnectedAccountInitiationFields(toolkitSlug, AuthSchemeTypes.API_KEY, {
750 requiredOnly: true,
ts/packages/core/test/models/triggers.test.ts
+3 -3
@@ -205,7 +205,7 @@ const mockIncomingTriggerPayload: IncomingTriggerPayload = {
205 };
206
207 describe('Triggers', () => {
208 - let triggers: Triggers<any>;
208 + let triggers: Triggers<unknown>;
209 let mockClient: ReturnType<typeof createMockClient>;
210 let mockPusherService: {
211 subscribe: Mock;
@@ -547,7 +547,7 @@ describe('Triggers', () => {
547 triggerConfig: null,
548 };
549
550 - await expect(triggers.create(userId, slug, invalidBody as any)).rejects.toThrow(
550 + await expect(triggers.create(userId, slug, invalidBody as unknown)).rejects.toThrow(
551 ValidationError
552 );
553 expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
@@ -753,7 +753,7 @@ describe('Triggers', () => {
753 });
754
755 it('should throw error if function is not provided', async () => {
756 - await expect(triggers.subscribe(null as any)).rejects.toThrow(
756 + await expect(triggers.subscribe(null as unknown)).rejects.toThrow(
757 'Function is required for trigger subscription'
758 );
759 });
ts/packages/core/test/models/verifyWebhook.integration.test.ts
+1 -1
@@ -112,7 +112,7 @@ function computeSignature(id: string, timestamp: string, payload: string, secret
112 }
113
114 describe('Triggers.verifyWebhook - Integration Tests', () => {
115 - let triggers: Triggers<any>;
115 + let triggers: Triggers<unknown>;
116 let mockClient: ReturnType<typeof createMockClient>;
117 const fixtures = loadFixtures();
118 const goldenSignatures = loadGoldenSignatures();
ts/packages/core/test/models/verifyWebhook.test.ts
+20 -10
@@ -7,12 +7,21 @@ import {
7 WebhookPayloadV2,
8 WebhookPayloadV3,
9 WebhookVersions,
10 + VerifyWebhookParams,
11 } from '../../src/types/triggers.types';
12 import { ValidationError } from '../../src/errors';
13 import {
14 ComposioWebhookSignatureVerificationError,
15 ComposioWebhookPayloadError,
16 } from '../../src/errors/TriggerErrors';
17 +import type { BaseComposioProvider } from '../../src/provider/BaseProvider';
18 +
19 +/** Shape of the `cause` payload attached to {@link ComposioWebhookPayloadError} when no version schema matches. */
20 +type WebhookVersionMismatchCause = {
21 + v1Error: string;
22 + v2Error: string;
23 + v3Error: string;
24 +};
25
26 // Mock dependencies
27 vi.mock('../../src/utils/logger');
@@ -105,7 +114,7 @@ const createMockV3Payload = (overrides: Partial<WebhookPayloadV3> = {}): Webhook
114 });
115
116 describe('Triggers.verifyWebhook', () => {
108 - let triggers: Triggers<any>;
117 + let triggers: Triggers<BaseComposioProvider<unknown, unknown, unknown>>;
118 let mockClient: ReturnType<typeof createMockClient>;
119 const testSecret = 'test-webhook-secret-12345';
120 const testWebhookId = 'msg_test123';
@@ -556,9 +565,10 @@ describe('Triggers.verifyWebhook', () => {
565 const webhookError = error as ComposioWebhookPayloadError;
566 expect(webhookError.cause).toBeDefined();
567 // The cause should contain v1Error, v2Error, and v3Error with schema validation messages
559 - expect((webhookError.cause as any).v1Error).toBeDefined();
560 - expect((webhookError.cause as any).v2Error).toBeDefined();
561 - expect((webhookError.cause as any).v3Error).toBeDefined();
568 + const cause = webhookError.cause as unknown as WebhookVersionMismatchCause;
569 + expect(cause.v1Error).toBeDefined();
570 + expect(cause.v2Error).toBeDefined();
571 + expect(cause.v3Error).toBeDefined();
572 }
573 });
574 });
@@ -650,7 +660,7 @@ describe('Triggers.verifyWebhook', () => {
660 secret: testSecret,
661 webhookId: testWebhookId,
662 webhookTimestamp: testTimestamp,
653 - } as any)
663 + } as unknown as VerifyWebhookParams)
664 ).rejects.toThrow(ValidationError);
665 });
666
@@ -661,7 +671,7 @@ describe('Triggers.verifyWebhook', () => {
671 secret: testSecret,
672 webhookId: testWebhookId,
673 webhookTimestamp: testTimestamp,
664 - } as any)
674 + } as unknown as VerifyWebhookParams)
675 ).rejects.toThrow(ValidationError);
676 });
677
@@ -672,7 +682,7 @@ describe('Triggers.verifyWebhook', () => {
682 signature: 'v1,sig',
683 webhookId: testWebhookId,
684 webhookTimestamp: testTimestamp,
675 - } as any)
685 + } as unknown as VerifyWebhookParams)
686 ).rejects.toThrow(ValidationError);
687 });
688
@@ -683,7 +693,7 @@ describe('Triggers.verifyWebhook', () => {
693 signature: 'v1,sig',
694 secret: testSecret,
695 webhookTimestamp: testTimestamp,
686 - } as any)
696 + } as unknown as VerifyWebhookParams)
697 ).rejects.toThrow(ValidationError);
698 });
699
@@ -694,7 +704,7 @@ describe('Triggers.verifyWebhook', () => {
704 signature: 'v1,sig',
705 secret: testSecret,
706 webhookId: testWebhookId,
697 - } as any)
707 + } as unknown as VerifyWebhookParams)
708 ).rejects.toThrow(ValidationError);
709 });
710
@@ -706,7 +716,7 @@ describe('Triggers.verifyWebhook', () => {
716 secret: testSecret,
717 id: testWebhookId,
718 timestamp: testTimestamp,
709 - tolerance: 'invalid' as any,
719 + tolerance: 'invalid' as unknown as number,
720 })
721 ).rejects.toThrow(ValidationError);
722 });
ts/packages/core/test/provider/openai-provider.test.ts
+2 -2
@@ -22,7 +22,7 @@ vi.mock('openai/streaming', () => {
22 describe('OpenAIProvider', () => {
23 let provider: OpenAIProvider;
24 let mockTool: Tool;
25 - let mockExecuteToolFn: any;
25 + let mockExecuteToolFn: unknown;
26
27 // Sample tool data
28 beforeEach(() => {
@@ -632,7 +632,7 @@ describe('OpenAIProvider', () => {
632 client.beta.threads.runs.retrieve = vi.fn().mockResolvedValue(finalRun);
633
634 // Collect the yielded events
635 - const collectedEvents: any[] = [];
635 + const collectedEvents: unknown[] = [];
636 for await (const event of provider.waitAndHandleAssistantStreamToolCalls(
637 userId,
638 client,
ts/packages/core/test/telemetry/TelemetryService.test.ts
+6 -6
@@ -281,7 +281,7 @@ describe('BatchProcessor', () => {
281 const batchesProcessed: number[][] = [];
282 let resolvers: (() => void)[] = [];
283
284 - const asyncCallback = vi.fn().mockImplementation((batch: any[]) => {
284 + const asyncCallback = vi.fn().mockImplementation((batch: unknown[]) => {
285 return new Promise<void>(resolve => {
286 resolvers.push(resolve);
287 }).then(() => {
@@ -317,8 +317,8 @@ describe('BatchProcessor', () => {
317
318 describe('TelemetryTransport', () => {
319 let transport: TelemetryTransport;
320 - let sendMetricSpy: any;
321 - let sendErrorLogSpy: any;
320 + let sendMetricSpy: unknown;
321 + let sendErrorLogSpy: unknown;
322 const metadata: TelemetryMetadata = {
323 apiKey: 'test-key',
324 baseUrl: 'http://localhost',
@@ -329,8 +329,8 @@ describe('TelemetryTransport', () => {
329 };
330
331 beforeEach(async () => {
332 - sendMetricSpy = vi.spyOn(TelemetryService, 'sendMetric').mockResolvedValue({} as any);
333 - sendErrorLogSpy = vi.spyOn(TelemetryService, 'sendErrorLog').mockResolvedValue({} as any);
332 + sendMetricSpy = vi.spyOn(TelemetryService, 'sendMetric').mockResolvedValue({} as unknown);
333 + sendErrorLogSpy = vi.spyOn(TelemetryService, 'sendErrorLog').mockResolvedValue({} as unknown);
334 transport = new TelemetryTransport();
335 transport.setup(metadata);
336 await transport.flush();
@@ -391,7 +391,7 @@ describe('TelemetryTransport', () => {
391 sendErrorLogSpy.mockImplementationOnce(
392 () =>
393 new Promise(resolve => {
394 - resolveTelemetry = () => resolve({} as any);
394 + resolveTelemetry = () => resolve({} as unknown);
395 })
396 );
397
ts/packages/core/test/tools/fileModifiers.test.ts
+1 -1
@@ -2088,7 +2088,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
2088 mockClient.tools.execute.mockResolvedValueOnce(mockResponse);
2089
2090 // Mock transformToolExecuteResponse to return the same data structure
2091 - vi.spyOn(context.tools as any, 'transformToolExecuteResponse').mockReturnValue({
2091 + vi.spyOn(context.tools as unknown, 'transformToolExecuteResponse').mockReturnValue({
2092 data: mockResponse.data,
2093 error: mockResponse.error,
2094 successful: mockResponse.successful,
ts/packages/core/test/tools/modifiers.test.ts
+2 -2
@@ -214,8 +214,8 @@ describe('Tools Modifiers', () => {
214 };
215 getRawComposioToolBySlugSpy.mockResolvedValueOnce(mockTool);
216
217 - const createExecuteToolFnSpy = vi.spyOn(context.tools as any, 'createExecuteToolFn');
218 - const executeWithModifiers = async (params: any) => {
217 + const createExecuteToolFnSpy = vi.spyOn(context.tools as unknown, 'createExecuteToolFn');
218 + const executeWithModifiers = async (params: unknown) => {
219 // Apply beforeExecute modifier
220 const modifiedParams = await executionModifiers.beforeExecute({
221 toolSlug: slug,
ts/packages/core/test/tools/tools.test.ts
+59 -40
@@ -2,8 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 import { mockClient } from '../utils/mocks/client.mock';
3 import { toolMocks } from '../utils/mocks/data.mock';
4 import { Tool, ToolListParams, ToolExecuteParams } from '../../src/types/tool.types';
5 +import { ExecuteToolFn } from '../../src/types/provider.types';
6 import { Tools } from '../../src/models/Tools';
6 -import ComposioClient from '@composio/client';
7 import {
8 createTestContext,
9 setupTest,
@@ -13,19 +13,33 @@ import {
13 import { MockProvider } from '../utils/mocks/provider.mock';
14 import { ValidationError } from '../../src/errors/ValidationErrors';
15
16 +// Minimal structural shape for a ComposioError-like value (possibly wrapping
17 +// another error as its `cause`), used to narrow `catch (error: unknown)`
18 +// blocks that assert on `.code` / `.message` / `.possibleFixes`.
19 +type ErrorWithPossibleFixes = {
20 + code?: string;
21 + message?: string;
22 + possibleFixes?: string[];
23 + cause?: {
24 + code?: string;
25 + message?: string;
26 + possibleFixes?: string[];
27 + };
28 +};
29 +
30 describe('Tools', () => {
31 const context = createTestContext();
32 setupTest(context);
33
34 describe('constructor', () => {
35 it('should throw an error if client is not provided', () => {
22 - expect(() => new Tools(null as any, { provider: context.mockProvider })).toThrow(
36 + expect(() => new Tools(null as unknown, { provider: context.mockProvider })).toThrow(
37 'ComposioClient is required'
38 );
39 });
40
41 it('should throw an error if provider is not provided', () => {
28 - expect(() => new Tools(mockClient as unknown as ComposioClient, null as any)).toThrow(
42 + expect(() => new Tools(mockClient, null as unknown)).toThrow(
43 'Provider not passed into Tools instance'
44 );
45 });
@@ -296,7 +310,7 @@ describe('Tools', () => {
310 it('should throw a validation error when scopes are provided without toolkits', async () => {
311 const invalidQuery = {
312 scopes: ['task:add'],
299 - } as any;
313 + } as unknown;
314
315 await expect(context.tools.getRawComposioTools(invalidQuery)).rejects.toThrow(
316 'Invalid tool list parameters'
@@ -335,7 +349,7 @@ describe('Tools', () => {
349 });
350
351 it('should throw an error if schema modifier is not a function', async () => {
338 - const invalidModifier = 'not a function' as any;
352 + const invalidModifier = 'not a function' as unknown;
353
354 mockClient.tools.list.mockResolvedValueOnce({
355 items: [toolMocks.rawTool],
@@ -356,7 +370,7 @@ describe('Tools', () => {
370 const invalidQuery = {
371 tools: ['TOOL1'],
372 toolkits: ['github'],
359 - } as any;
373 + } as unknown;
374
375 await expect(context.tools.getRawComposioTools(invalidQuery)).rejects.toThrow(
376 'Invalid tool list parameters'
@@ -364,7 +378,7 @@ describe('Tools', () => {
378 });
379
380 it('should throw a validation error when no required parameters are provided', async () => {
367 - const emptyQuery = {} as any;
381 + const emptyQuery = {} as unknown;
382
383 await expect(context.tools.getRawComposioTools(emptyQuery)).rejects.toThrow(ValidationError);
384 });
@@ -493,7 +507,7 @@ describe('Tools', () => {
507 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
508
509 // Create a Tools instance with SDK-level toolkitVersions as mapping object
496 - const toolsWithVersions = new Tools(mockClient as any, {
510 + const toolsWithVersions = new Tools(mockClient, {
511 provider: context.mockProvider,
512 toolkitVersions: versionMapping,
513 });
@@ -533,7 +547,7 @@ describe('Tools', () => {
547 const explicitVersion = '20250909_00';
548
549 // Create a Tools instance with SDK-level toolkitVersions
536 - const toolsWithVersions = new Tools(mockClient as any, {
550 + const toolsWithVersions = new Tools(mockClient, {
551 provider: context.mockProvider,
552 toolkitVersions: { github: explicitVersion },
553 });
@@ -1226,7 +1240,7 @@ describe('Tools', () => {
1240 it('should throw validation error for invalid parameters', async () => {
1241 const invalidProxyParams = {
1242 endpoint: '/api/test',
1229 - method: 'INVALID_METHOD' as any,
1243 + method: 'INVALID_METHOD' as unknown,
1244 parameters: [
1245 {
1246 in: 'header' as const,
@@ -1322,7 +1336,7 @@ describe('Tools', () => {
1336 const invalidBody = {
1337 // missing sessionId
1338 arguments: { query: 'test' },
1325 - } as any;
1339 + } as unknown;
1340
1341 await expect(
1342 context.tools.executeSessionTool('COMPOSIO_TOOL', invalidBody)
@@ -1508,7 +1522,10 @@ describe('Tools', () => {
1522 it('should create execute function that calls executeSessionTool', async () => {
1523 const tools = [toolMocks.transformedTool as unknown as Tool];
1524
1511 - let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
1525 + let capturedExecuteFn: (
1526 + toolSlug: string,
1527 + input: Record<string, unknown>
1528 + ) => Promise<unknown>;
1529
1530 context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
1531 capturedExecuteFn = executeFn;
@@ -1552,7 +1569,10 @@ describe('Tools', () => {
1569 })),
1570 };
1571
1555 - let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
1572 + let capturedExecuteFn: (
1573 + toolSlug: string,
1574 + input: Record<string, unknown>
1575 + ) => Promise<unknown>;
1576
1577 context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
1578 capturedExecuteFn = executeFn;
@@ -1633,9 +1653,9 @@ describe('Tools', () => {
1653
1654 it('should pass global version string when configured', async () => {
1655 const mockProvider = new MockProvider();
1636 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1656 + const tools = new Tools(mockClient, {
1657 provider: mockProvider,
1638 - toolkitVersions: '20251201_03' as any,
1658 + toolkitVersions: '20251201_03' as unknown,
1659 });
1660
1661 mockClient.tools.list.mockResolvedValueOnce({
@@ -1657,7 +1677,7 @@ describe('Tools', () => {
1677
1678 it('should pass toolkit-specific versions when configured as object', async () => {
1679 const mockProvider = new MockProvider();
1660 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1680 + const tools = new Tools(mockClient, {
1681 provider: mockProvider,
1682 toolkitVersions: {
1683 github: '20251201_01',
@@ -1689,7 +1709,7 @@ describe('Tools', () => {
1709
1710 it('should pass versions when fetching tools by tool slugs', async () => {
1711 const mockProvider = new MockProvider();
1692 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1712 + const tools = new Tools(mockClient, {
1713 provider: mockProvider,
1714 toolkitVersions: {
1715 github: '20251201_01',
@@ -1719,7 +1739,7 @@ describe('Tools', () => {
1739
1740 it('should pass versions when searching tools', async () => {
1741 const mockProvider = new MockProvider();
1722 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1742 + const tools = new Tools(mockClient, {
1743 provider: mockProvider,
1744 toolkitVersions: 'latest',
1745 });
@@ -1760,9 +1780,9 @@ describe('Tools', () => {
1780
1781 it('should pass global version when retrieving single tool', async () => {
1782 const mockProvider = new MockProvider();
1763 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1783 + const tools = new Tools(mockClient, {
1784 provider: mockProvider,
1765 - toolkitVersions: '20251201_03' as any,
1785 + toolkitVersions: '20251201_03' as unknown,
1786 });
1787
1788 mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
@@ -1780,7 +1800,7 @@ describe('Tools', () => {
1800
1801 it('should pass toolkit-specific versions when retrieving single tool', async () => {
1802 const mockProvider = new MockProvider();
1783 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1803 + const tools = new Tools(mockClient, {
1804 provider: mockProvider,
1805 toolkitVersions: {
1806 github: '20251201_01',
@@ -1838,9 +1858,9 @@ describe('Tools', () => {
1858
1859 it('should use global version when configured', async () => {
1860 const mockProvider = new MockProvider();
1841 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1861 + const tools = new Tools(mockClient, {
1862 provider: mockProvider,
1843 - toolkitVersions: '20251201_03' as any,
1863 + toolkitVersions: '20251201_03' as unknown,
1864 });
1865 const spies = await mockToolExecution(tools);
1866
@@ -1869,7 +1889,7 @@ describe('Tools', () => {
1889
1890 it('should use toolkit-specific version when configured as object', async () => {
1891 const mockProvider = new MockProvider();
1872 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1892 + const tools = new Tools(mockClient, {
1893 provider: mockProvider,
1894 toolkitVersions: {
1895 'test-toolkit': '20251201_01', // Use the actual toolkit slug from mock
@@ -1914,7 +1934,7 @@ describe('Tools', () => {
1934
1935 it('should use fallback to "latest" when toolkit not in version mapping', async () => {
1936 const mockProvider = new MockProvider();
1917 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1937 + const tools = new Tools(mockClient, {
1938 provider: mockProvider,
1939 toolkitVersions: {
1940 github: '20251201_01',
@@ -1957,7 +1977,7 @@ describe('Tools', () => {
1977
1978 it('should prioritize explicit version parameter over configured versions', async () => {
1979 const mockProvider = new MockProvider();
1960 - const tools = new Tools(mockClient as unknown as ComposioClient, {
1980 + const tools = new Tools(mockClient, {
1981 provider: mockProvider,
1982 toolkitVersions: {
1983 github: '20251201_01',
@@ -1993,7 +2013,7 @@ describe('Tools', () => {
2013
2014 it('should handle tool without toolkit gracefully', async () => {
2015 const mockProvider = new MockProvider();
1996 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2016 + const tools = new Tools(mockClient, {
2017 provider: mockProvider,
2018 toolkitVersions: {
2019 github: '20251201_01',
@@ -2054,7 +2074,7 @@ describe('Tools', () => {
2074
2075 const mockProvider = new MockProvider();
2076 // Pass the processed environment variables to the Tools constructor
2057 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2077 + const tools = new Tools(mockClient, {
2078 provider: mockProvider,
2079 toolkitVersions: {
2080 github: '20251201_08',
@@ -2088,7 +2108,7 @@ describe('Tools', () => {
2108 process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
2109
2110 const mockProvider = new MockProvider();
2091 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2111 + const tools = new Tools(mockClient, {
2112 provider: mockProvider,
2113 toolkitVersions: {
2114 github: '20251201_04', // should override env
@@ -2122,9 +2142,9 @@ describe('Tools', () => {
2142 process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
2143
2144 const mockProvider = new MockProvider();
2125 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2145 + const tools = new Tools(mockClient, {
2146 provider: mockProvider,
2127 - toolkitVersions: '20251201_09' as any, // global version overrides everything
2147 + toolkitVersions: '20251201_09' as unknown, // global version overrides everything
2148 });
2149
2150 mockClient.tools.list.mockResolvedValueOnce({
@@ -2207,7 +2227,7 @@ describe('Tools', () => {
2227
2228 it('should succeed when executing with a specific version (not "latest") without dangerouslySkipVersionCheck', async () => {
2229 const mockProvider = new MockProvider();
2210 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2230 + const tools = new Tools(mockClient, {
2231 provider: mockProvider,
2232 toolkitVersions: {
2233 'test-toolkit': '20251201_01',
@@ -2280,7 +2300,7 @@ describe('Tools', () => {
2300
2301 it('should throw error when explicit version parameter is "latest" without dangerouslySkipVersionCheck', async () => {
2302 const mockProvider = new MockProvider();
2283 - const tools = new Tools(mockClient as unknown as ComposioClient, {
2303 + const tools = new Tools(mockClient, {
2304 provider: mockProvider,
2305 toolkitVersions: {
2306 'test-toolkit': '20251201_01', // specific version in config
@@ -2319,7 +2339,8 @@ describe('Tools', () => {
2339 try {
2340 await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);
2341 expect.fail('Should have thrown an error');
2322 - } catch (error: any) {
2342 + } catch (rawError: unknown) {
2343 + const error = rawError as unknown as ErrorWithPossibleFixes;
2344 // The error should be wrapped in ComposioToolExecutionError
2345 expect(error).toBeDefined();
2346
@@ -2364,17 +2385,15 @@ describe('Tools', () => {
2385 );
2386
2387 // Mock provider wrapping
2367 - context.mockProvider.wrapTools.mockImplementation((tools, executeToolFn) => {
2368 - // Store the execute function so we can test it
2369 - (context as any).storedExecuteToolFn = executeToolFn;
2388 + let storedExecuteToolFn: ExecuteToolFn | undefined;
2389 + context.mockProvider.wrapTools.mockImplementation((_tools, executeToolFn) => {
2390 + storedExecuteToolFn = executeToolFn;
2391 return 'wrapped-tools-collection';
2392 });
2393
2394 // Get the tool (this will internally create the execute tool function)
2395 await context.tools.get(userId, 'GITHUB_CREATE_ISSUE');
2396
2376 - // Now call the stored execute function (simulating agentic provider calling it)
2377 - const storedExecuteToolFn = (context as any).storedExecuteToolFn;
2397 expect(storedExecuteToolFn).toBeDefined();
2398
2399 // Setup mocks for the actual execution
@@ -2382,7 +2401,7 @@ describe('Tools', () => {
2401
2402 // Call the execute function that was passed to the provider
2403 // This should succeed because createExecuteToolFn sets dangerouslySkipVersionCheck: true
2385 - const result = await storedExecuteToolFn('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });
2404 + const result = await storedExecuteToolFn!('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });
2405
2406 expect(result).toEqual(toolMocks.toolExecuteResponse);
2407 expect(mockClient.tools.execute).toHaveBeenCalledWith(
ts/packages/core/test/utils/fileUtils.test.ts
+9 -9
@@ -1,4 +1,4 @@
1 -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
2 import * as path from 'node:path';
3 import { getFileDataAfterUploadingToS3, downloadFileFromS3 } from '../../src/utils/fileUtils.node';
4 import ComposioClient from '@composio/client';
@@ -85,7 +85,7 @@ describe('fileUtils', () => {
85 mockFetch.mockResolvedValue(fetchedFileResponse());
86
87 // Mock successful S3 upload
88 - (mockClient.files.createPresignedURL as any).mockResolvedValue({
88 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValue({
89 key: 'test-key',
90 type: 'new',
91 new_presigned_url: 'https://s3.example.com/upload',
@@ -199,7 +199,7 @@ describe('fileUtils', () => {
199 mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
200
201 // Mock successful S3 upload
202 - (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
202 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
203 key: 'test-key',
204 type: 'new',
205 new_presigned_url: 'https://s3.example.com/upload',
@@ -225,7 +225,7 @@ describe('fileUtils', () => {
225 mockFetch.mockResolvedValueOnce(fetchedFileResponse('text/plain; charset=utf-8'));
226
227 // Mock successful S3 upload
228 - (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
228 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
229 key: 'test-key',
230 type: 'new',
231 new_presigned_url: 'https://s3.example.com/upload',
@@ -260,7 +260,7 @@ describe('fileUtils', () => {
260 mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
261
262 // Mock successful S3 upload
263 - (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
263 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
264 key: 'test-key',
265 type: 'new',
266 new_presigned_url: 'https://s3.example.com/upload',
@@ -286,7 +286,7 @@ describe('fileUtils', () => {
286 mockFetch.mockResolvedValueOnce(fetchedFileResponse('application/custom-format'));
287
288 // Mock successful S3 upload
289 - (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
289 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
290 key: 'test-key',
291 type: 'new',
292 new_presigned_url: 'https://s3.example.com/upload',
@@ -410,7 +410,7 @@ describe('fileUtils', () => {
410 vi.clearAllMocks();
411
412 // Mock successful S3 upload
413 - (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
413 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
414 key: 'test-key',
415 type: 'new',
416 new_presigned_url: 'https://s3.example.com/upload',
@@ -479,7 +479,7 @@ describe('fileUtils', () => {
479 it('should handle S3 upload errors', async () => {
480 mockFetch.mockResolvedValueOnce(fetchedFileResponse());
481
482 - (mockClient.files.createPresignedURL as any).mockResolvedValue({
482 + (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValue({
483 key: 'test-key',
484 type: 'new',
485 new_presigned_url: 'https://s3.example.com/upload',
@@ -502,7 +502,7 @@ describe('fileUtils', () => {
502
503 it('should handle invalid file types', async () => {
504 await expect(
505 - getFileDataAfterUploadingToS3(123 as any, {
505 + getFileDataAfterUploadingToS3(123 as unknown as string, {
506 toolSlug: 'test-tool',
507 toolkitSlug: 'test-toolkit',
508 client: mockClient,
ts/packages/core/test/utils/jsonSchema.test.ts
+1 -2
@@ -227,8 +227,7 @@ describe('dereferenceJsonSchema', () => {
227 v: { $ref: '#/$defs/User' },
228 },
229 $defs: {
230 - // eslint-disable-next-line @typescript-eslint/no-explicit-any
231 - User: { type: 'object', __proto__: { polluted: true } } as any,
230 + User: { type: 'object', __proto__: { polluted: true } },
231 },
232 } as Record<string, unknown>);
233
ts/packages/core/test/utils/mocks/client.mock.ts
+52 -47
@@ -1,50 +1,55 @@
1 import { vi } from 'vitest';
2 +import ComposioClient from '@composio/client';
3
3 -const mockClientBase = {
4 - tools: {
5 - list: vi.fn(),
6 - retrieve: vi.fn(),
7 - execute: vi.fn(),
8 - retrieveEnum: vi.fn(),
9 - getInput: vi.fn(),
10 - proxy: vi.fn(),
11 - },
12 - connectedAccounts: {
13 - list: vi.fn(),
14 - get: vi.fn(),
15 - retrieve: vi.fn(),
16 - delete: vi.fn(),
17 - refresh: vi.fn(),
18 - updateStatus: vi.fn(),
19 - },
20 - toolkits: {
21 - list: vi.fn(),
22 - retrieve: vi.fn(),
23 - retrieveCategories: vi.fn(),
24 - },
25 - authConfigs: {
26 - list: vi.fn(),
27 - create: vi.fn(),
28 - retrieve: vi.fn(),
29 - update: vi.fn(),
30 - delete: vi.fn(),
31 - updateStatus: vi.fn(),
32 - },
33 - toolRouter: {
34 - session: {
35 - execute: vi.fn(),
36 - tools: vi.fn(),
37 - },
38 - },
39 -};
40 -
41 -// `withOptions` returns the same mock so chained calls (e.g.
42 -// `client.withOptions({ maxRetries: 0 }).tools.execute(...)`) still record on
43 -// the same spies. Mirrors the real client's `withOptions`.
44 -//
45 -// This implementation is load-bearing: tests rely on `vi.clearAllMocks()`
46 -// (which preserves implementations), not `vi.resetAllMocks()` (which would wipe
47 -// it and make chained `.tools.*` calls throw on `undefined`).
48 -export const mockClient = Object.assign(mockClientBase, {
49 - withOptions: vi.fn(() => mockClientBase),
4 +const client = new ComposioClient({ apiKey: 'test-api-key' });
5 +
6 +const tools = Object.assign(client.tools, {
7 + list: vi.fn<typeof client.tools.list>(),
8 + retrieve: vi.fn<typeof client.tools.retrieve>(),
9 + execute: vi.fn<typeof client.tools.execute>(),
10 + retrieveEnum: vi.fn<typeof client.tools.retrieveEnum>(),
11 + getInput: vi.fn<typeof client.tools.getInput>(),
12 + proxy: vi.fn<typeof client.tools.proxy>(),
13 +});
14 +
15 +const connectedAccounts = Object.assign(client.connectedAccounts, {
16 + list: vi.fn<typeof client.connectedAccounts.list>(),
17 + create: vi.fn<typeof client.connectedAccounts.create>(),
18 + retrieve: vi.fn<typeof client.connectedAccounts.retrieve>(),
19 + delete: vi.fn<typeof client.connectedAccounts.delete>(),
20 + refresh: vi.fn<typeof client.connectedAccounts.refresh>(),
21 + updateStatus: vi.fn<typeof client.connectedAccounts.updateStatus>(),
22 +});
23 +
24 +const toolkits = Object.assign(client.toolkits, {
25 + list: vi.fn<typeof client.toolkits.list>(),
26 + retrieve: vi.fn<typeof client.toolkits.retrieve>(),
27 + retrieveCategories: vi.fn<typeof client.toolkits.retrieveCategories>(),
28 +});
29 +
30 +const authConfigs = Object.assign(client.authConfigs, {
31 + list: vi.fn<typeof client.authConfigs.list>(),
32 + create: vi.fn<typeof client.authConfigs.create>(),
33 + retrieve: vi.fn<typeof client.authConfigs.retrieve>(),
34 + update: vi.fn<typeof client.authConfigs.update>(),
35 + delete: vi.fn<typeof client.authConfigs.delete>(),
36 + updateStatus: vi.fn<typeof client.authConfigs.updateStatus>(),
37 +});
38 +
39 +const session = Object.assign(client.toolRouter.session, {
40 + execute: vi.fn<typeof client.toolRouter.session.execute>(),
41 + tools: vi.fn<typeof client.toolRouter.session.tools>(),
42 });
43 +const toolRouter = Object.assign(client.toolRouter, { session });
44 +const withOptions = vi.fn<typeof client.withOptions>();
45 +
46 +export const mockClient = Object.assign(client, {
47 + tools,
48 + connectedAccounts,
49 + toolkits,
50 + authConfigs,
51 + toolRouter,
52 + withOptions,
53 +});
54 +
55 +withOptions.mockReturnValue(mockClient);
ts/packages/core/test/utils/pusher.test.ts
+2 -2
@@ -4,7 +4,7 @@ import { PusherUtils } from '../../src/utils/pusher';
4 // Capture the options passed to the Pusher constructor so the
5 // channelAuthorization.customHandler can be exercised in isolation.
6 const { constructorCalls } = vi.hoisted(() => ({
7 - constructorCalls: [] as Array<{ key: string; options: Record<string, any> }>,
7 + constructorCalls: [] as Array<{ key: string; options: Record<string, unknown> }>,
8 }));
9
10 vi.mock('pusher-js', () => {
@@ -13,7 +13,7 @@ vi.mock('pusher-js', () => {
13 subscribe = vi.fn();
14 unsubscribe = vi.fn();
15 bind = vi.fn();
16 - constructor(key: string, options: Record<string, any>) {
16 + constructor(key: string, options: Record<string, unknown>) {
17 constructorCalls.push({ key, options });
18 }
19 }
ts/packages/core/test/utils/toolExecuteUtils.ts
+2 -3
@@ -3,7 +3,6 @@ import { Tools } from '../../src/models/Tools';
3 import { mockClient } from './mocks/client.mock';
4 import { MockProvider } from './mocks/provider.mock';
5 import { connectedAccountMocks, toolkitMocks, toolMocks } from './mocks/data.mock';
6 -import ComposioClient from '@composio/client';
6 import { Tool, ToolExecuteResponse, ToolExecuteParams } from '../../src/types/tool.types';
7
8 export type TestTools = Tools<Tool[], Tool, MockProvider>;
@@ -15,7 +14,7 @@ export interface TestContext {
14
15 export const createTestContext = (): TestContext => {
16 const mockProvider = new MockProvider();
18 - const tools = new Tools(mockClient as unknown as ComposioClient, { provider: mockProvider });
17 + const tools = new Tools(mockClient, { provider: mockProvider });
18 return { tools, mockProvider };
19 };
20
@@ -23,7 +22,7 @@ export const setupTest = (context: TestContext) => {
22 beforeEach(() => {
23 vi.clearAllMocks();
24 context.mockProvider = new MockProvider();
26 - context.tools = new Tools(mockClient as unknown as ComposioClient, {
25 + context.tools = new Tools(mockClient, {
26 provider: context.mockProvider,
27 });
28 });
ts/packages/core/test/utils/transform.test.ts
+5 -5
@@ -43,7 +43,7 @@ describe('transform', () => {
43
44 const result = transform({ name: 'Alice', extra: 'field' })
45 .with(schema)
46 - .using(raw => raw as any);
46 + .using(raw => raw as unknown);
47
48 expect(result).toEqual({ name: 'Alice' });
49 expect(result).not.toHaveProperty('extra');
@@ -57,7 +57,7 @@ describe('transform', () => {
57
58 const result = transform({ name: 123, age: 'not a number' })
59 .with(schema)
60 - .using(raw => raw as any);
60 + .using(raw => raw as unknown);
61
62 expect(result).toEqual({ name: 123, age: 'not a number' });
63
@@ -75,7 +75,7 @@ describe('transform', () => {
75
76 transform({ id: 42 })
77 .with(schema)
78 - .using(raw => raw as any, { label: 'ConnectedAccount' });
78 + .using(raw => raw as unknown, { label: 'ConnectedAccount' });
79
80 expect(mockLogger.warn).toHaveBeenCalledTimes(1);
81 const warnMessage = mockLogger.warn.mock.calls[0][0] as string;
@@ -87,7 +87,7 @@ describe('transform', () => {
87
88 const result = transform({ id: 'abc' })
89 .with(schema)
90 - .using(raw => raw as any);
90 + .using(raw => raw as unknown);
91
92 expect(result).toEqual({ id: 'abc' });
93 expect(mockLogger.warn).not.toHaveBeenCalled();
@@ -103,7 +103,7 @@ describe('transform', () => {
103
104 const result = transform({ user: { email: 'not-an-email' } })
105 .with(schema)
106 - .using(raw => raw as any);
106 + .using(raw => raw as unknown);
107
108 expect(result).toEqual({ user: { email: 'not-an-email' } });
109 expect(mockLogger.warn).toHaveBeenCalledTimes(1);
ts/packages/core/test/utils/transformers/mcp.test.ts
+17 -17
@@ -18,7 +18,7 @@ describe('MCP Transformers', () => {
18 created_at: '2024-01-01T00:00:00Z',
19 updated_at: '2024-01-02T00:00:00Z',
20 status: 'active',
21 - } as any;
21 + } as unknown;
22
23 const result = transformMcpCreateResponse(snakeCaseResponse);
24
@@ -35,7 +35,7 @@ describe('MCP Transformers', () => {
35 const minimalResponse = {
36 id: 'mcp_123',
37 name: 'test-server',
38 - } as any;
38 + } as unknown;
39
40 const result = transformMcpCreateResponse(minimalResponse);
41
@@ -49,7 +49,7 @@ describe('MCP Transformers', () => {
49 const invalidResponse = {
50 id: '', // Empty ID should fail validation
51 name: 'test-server',
52 - } as any;
52 + } as unknown;
53
54 expect(() => transformMcpCreateResponse(invalidResponse)).toThrow(ValidationError);
55 expect(() => transformMcpCreateResponse(invalidResponse)).toThrow(
@@ -77,7 +77,7 @@ describe('MCP Transformers', () => {
77 status: 'inactive',
78 },
79 ],
80 - } as any;
80 + } as unknown;
81
82 const result = transformMcpListResponse(snakeCaseResponse);
83
@@ -104,7 +104,7 @@ describe('MCP Transformers', () => {
104 it('should handle empty items array', () => {
105 const emptyResponse = {
106 items: [],
107 - } as any;
107 + } as unknown;
108
109 const result = transformMcpListResponse(emptyResponse);
110
@@ -114,7 +114,7 @@ describe('MCP Transformers', () => {
114 });
115
116 it('should handle missing items', () => {
117 - const noItemsResponse = {} as any;
117 + const noItemsResponse = {} as unknown;
118
119 const result = transformMcpListResponse(noItemsResponse);
120
@@ -141,7 +141,7 @@ describe('MCP Transformers', () => {
141 cursor: 'cursor-command',
142 windsurf: 'windsurf-command',
143 },
144 - } as any;
144 + } as unknown;
145
146 const result = transformMcpRetrieveResponse(snakeCaseResponse);
147
@@ -173,7 +173,7 @@ describe('MCP Transformers', () => {
173 cursor: 'cursor-command',
174 windsurf: 'windsurf-command',
175 },
176 - } as any;
176 + } as unknown;
177
178 const result = transformMcpRetrieveResponse(minimalResponse);
179
@@ -193,7 +193,7 @@ describe('MCP Transformers', () => {
193 const invalidResponse = {
194 id: 'mcp_123',
195 // Missing required 'name' field
196 - } as any;
196 + } as unknown;
197
198 expect(() => transformMcpRetrieveResponse(invalidResponse)).toThrow(ValidationError);
199 });
@@ -205,7 +205,7 @@ describe('MCP Transformers', () => {
205 id: 'mcp_123',
206 deleted: true,
207 message: 'Server deleted successfully',
208 - } as any;
208 + } as unknown;
209
210 const result = transformMcpDeleteResponse(snakeCaseResponse);
211
@@ -219,7 +219,7 @@ describe('MCP Transformers', () => {
219 it('should handle response without optional fields', () => {
220 const minimalResponse = {
221 id: 'mcp_123',
222 - } as any;
222 + } as unknown;
223
224 const result = transformMcpDeleteResponse(minimalResponse);
225
@@ -239,7 +239,7 @@ describe('MCP Transformers', () => {
239 status: 'active',
240 toolkits: ['gmail', 'slack'],
241 tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE'],
242 - } as any;
242 + } as unknown;
243
244 const result = transformMcpUpdateResponse(snakeCaseResponse);
245
@@ -258,7 +258,7 @@ describe('MCP Transformers', () => {
258 const minimalResponse = {
259 id: 'mcp_123',
260 name: 'updated-server',
261 - } as any;
261 + } as unknown;
262
263 const result = transformMcpUpdateResponse(minimalResponse);
264
@@ -272,7 +272,7 @@ describe('MCP Transformers', () => {
272 const invalidResponse = {
273 id: 'mcp_123',
274 name: '', // Empty name should fail validation
275 - } as any;
275 + } as unknown;
276
277 expect(() => transformMcpUpdateResponse(invalidResponse)).toThrow(ValidationError);
278 expect(() => transformMcpUpdateResponse(invalidResponse)).toThrow(
@@ -362,7 +362,7 @@ describe('MCP Transformers', () => {
362 created_at: null,
363 updated_at: null,
364 status: null,
365 - } as any;
365 + } as unknown;
366
367 const result = transformMcpCreateResponse(responseWithNulls);
368
@@ -382,7 +382,7 @@ describe('MCP Transformers', () => {
382 created_at: undefined,
383 updated_at: undefined,
384 status: undefined,
385 - } as any;
385 + } as unknown;
386
387 const result = transformMcpCreateResponse(responseWithUndefined);
388
@@ -399,7 +399,7 @@ describe('MCP Transformers', () => {
399 created_at: '2024-01-01T00:00:00Z',
400 some_unknown_field: 'value',
401 nested_object: { key: 'value' },
402 - } as any;
402 + } as unknown;
403
404 const result = transformMcpCreateResponse(responseWithExtraFields);
405
ts/packages/core/type-tests/json-schema-property.test-d.ts new
+35
@@ -0,0 +1,35 @@
1 +import type { JSONSchemaProperty, Tool } from '../src';
2 +
3 +const recursiveSchema: JSONSchemaProperty = {
4 + type: 'object',
5 + properties: {
6 + filters: {
7 + anyOf: [
8 + { type: 'string', enum: ['active', 'archived'] },
9 + {
10 + type: 'array',
11 + items: { type: 'integer', minimum: 1 },
12 + },
13 + ],
14 + },
15 + },
16 + additionalProperties: false,
17 + default: { filters: 'active' },
18 + 'x-composio-metadata': { source: 'type-test' },
19 +};
20 +
21 +const defaultValue: unknown = recursiveSchema.default;
22 +void defaultValue;
23 +
24 +declare const tool: Tool;
25 +const inputProperties: Record<string, JSONSchemaProperty> | undefined =
26 + tool.inputParameters?.properties;
27 +void inputProperties;
28 +
29 +// @ts-expect-error known JSON Schema keywords keep their concrete types
30 +const invalidType: JSONSchemaProperty = { type: 'date' };
31 +void invalidType;
32 +
33 +// @ts-expect-error recursive properties must contain JSON Schema nodes
34 +const invalidProperty: JSONSchemaProperty = { properties: { query: 'string' } };
35 +void invalidProperty;
ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
+5 -12
@@ -7,8 +7,7 @@ import { its } from '../utils/its';
7 import type { JSONSchema7TypeName } from 'json-schema';
8
9 type MetadataFields =
10 - | keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'>
11 - | 'examples';
10 + keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'> | 'examples';
11
12 export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, refs: Refs) => {
13 // Handle anyOf pattern first
@@ -84,26 +83,20 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
83 );
84
85 // Handle generic 'min' property as alias for 'minItems'
87 - if (
88 - typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
89 - typeof jsonSchema.minItems !== 'number'
90 - ) {
86 + if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minItems !== 'number') {
87 zodSchema = extendSchemaWithMessage(
88 zodSchema,
93 - { ...jsonSchema, minItems: (jsonSchema as unknown as { min?: number }).min },
89 + { ...jsonSchema, minItems: jsonSchema.min },
90 'minItems',
91 (zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
92 );
93 }
94
95 // Handle generic 'max' property as alias for 'maxItems'
100 - if (
101 - typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
102 - typeof jsonSchema.maxItems !== 'number'
103 - ) {
96 + if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maxItems !== 'number') {
97 zodSchema = extendSchemaWithMessage(
98 zodSchema,
106 - { ...jsonSchema, maxItems: (jsonSchema as unknown as { max?: number }).max },
99 + { ...jsonSchema, maxItems: jsonSchema.max },
100 'maxItems',
101 (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
102 );
ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
+4 -10
@@ -85,26 +85,20 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
85 }
86
87 // Handle generic 'min' property as alias for 'minimum'
88 - if (
89 - typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
90 - typeof jsonSchema.minimum !== 'number'
91 - ) {
88 + if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minimum !== 'number') {
89 zodSchema = extendSchemaWithMessage(
90 zodSchema,
94 - { ...jsonSchema, minimum: (jsonSchema as unknown as { min?: number }).min },
91 + { ...jsonSchema, minimum: jsonSchema.min },
92 'minimum',
93 (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
94 );
95 }
96
97 // Handle generic 'max' property as alias for 'maximum'
101 - if (
102 - typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
103 - typeof jsonSchema.maximum !== 'number'
104 - ) {
98 + if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maximum !== 'number') {
99 zodSchema = extendSchemaWithMessage(
100 zodSchema,
107 - { ...jsonSchema, maximum: (jsonSchema as unknown as { max?: number }).max },
101 + { ...jsonSchema, maximum: jsonSchema.max },
102 'maximum',
103 (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
104 );
ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
+6 -9
@@ -29,15 +29,12 @@ const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.
29 }
30
31 // Append example(s) if they exist
32 - if ((jsonSchema as unknown as { example?: unknown }).example !== undefined) {
33 - const exampleText = `Example: ${JSON.stringify((jsonSchema as unknown as { example?: unknown }).example)}`;
32 + if (jsonSchema.example !== undefined) {
33 + const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
34 description = description ? `${description}\n${exampleText}` : exampleText;
35 - } else if (
36 - (jsonSchema as unknown as { examples?: unknown[] }).examples !== undefined &&
37 - Array.isArray((jsonSchema as unknown as { examples?: unknown[] }).examples)
38 - ) {
39 - const examples = (jsonSchema as unknown as { examples?: unknown[] }).examples;
40 - if (examples && examples.length && examples.length > 0) {
35 + } else if (jsonSchema.examples !== undefined && Array.isArray(jsonSchema.examples)) {
36 + const examples = jsonSchema.examples;
37 + if (examples.length > 0) {
38 const exampleText =
39 examples.length === 1
40 ? `Example: ${JSON.stringify(examples[0])}`
@@ -69,7 +66,7 @@ const addDefaults = (
66 inAnyOfOrOneOf &&
67 jsonSchema.type &&
68 jsonSchema.type !== 'null' &&
72 - // @ts-ignore: `nullable` is not publicly available in Zod 4
69 + // @ts-expect-error: `nullable` is not publicly available in Zod 4
70 !jsonSchema.nullable
71 ) {
72 return zodSchema;
ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
+4 -10
@@ -55,26 +55,20 @@ export const parseString = (jsonSchema: JsonSchemaObject & { type: 'string' }) =
55 );
56
57 // Handle generic 'min' property as alias for 'minLength'
58 - if (
59 - typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
60 - typeof jsonSchema.minLength !== 'number'
61 - ) {
58 + if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minLength !== 'number') {
59 zodSchema = extendSchemaWithMessage(
60 zodSchema,
64 - { ...jsonSchema, minLength: (jsonSchema as unknown as { min?: number }).min },
61 + { ...jsonSchema, minLength: jsonSchema.min },
62 'minLength',
63 (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
64 );
65 }
66
67 // Handle generic 'max' property as alias for 'maxLength'
71 - if (
72 - typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
73 - typeof jsonSchema.maxLength !== 'number'
74 - ) {
68 + if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maxLength !== 'number') {
69 zodSchema = extendSchemaWithMessage(
70 zodSchema,
77 - { ...jsonSchema, maxLength: (jsonSchema as unknown as { max?: number }).max },
71 + { ...jsonSchema, maxLength: jsonSchema.max },
72 'maxLength',
73 (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
74 );
ts/packages/json-schema-to-zod/src/types.ts
+46 -7
@@ -2,15 +2,54 @@ import type { ZodTypeAny } from 'zod/v3';
2 import type { JSONSchema7 } from 'json-schema';
3
4 export type Serializable =
5 - | { [key: string]: Serializable }
6 - | Serializable[]
7 - | string
8 - | number
9 - | boolean
10 - | null;
5 + { [key: string]: Serializable } | Serializable[] | string | number | boolean | null;
6
7 export type JsonSchema = JsonSchemaObject | boolean;
13 -export type JsonSchemaObject = JSONSchema7;
8 +
9 +type JsonSchemaDefinitions = Record<string, JsonSchema>;
10 +
11 +export interface JsonSchemaObject extends Omit<
12 + JSONSchema7,
13 + | '$defs'
14 + | 'items'
15 + | 'additionalItems'
16 + | 'contains'
17 + | 'properties'
18 + | 'patternProperties'
19 + | 'additionalProperties'
20 + | 'dependencies'
21 + | 'propertyNames'
22 + | 'if'
23 + | 'then'
24 + | 'else'
25 + | 'allOf'
26 + | 'anyOf'
27 + | 'oneOf'
28 + | 'not'
29 + | 'definitions'
30 +> {
31 + min?: number;
32 + max?: number;
33 + example?: Serializable;
34 +
35 + $defs?: JsonSchemaDefinitions;
36 + definitions?: JsonSchemaDefinitions;
37 + items?: JsonSchema | JsonSchema[];
38 + additionalItems?: JsonSchema;
39 + contains?: JsonSchema;
40 + properties?: JsonSchemaDefinitions;
41 + patternProperties?: JsonSchemaDefinitions;
42 + additionalProperties?: JsonSchema;
43 + dependencies?: Record<string, JsonSchema | string[]>;
44 + propertyNames?: JsonSchema;
45 + if?: JsonSchema;
46 + then?: JsonSchema;
47 + else?: JsonSchema;
48 + allOf?: JsonSchema[];
49 + anyOf?: JsonSchema[];
50 + oneOf?: JsonSchema[];
51 + not?: JsonSchema;
52 +}
53 export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny;
54 export type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny | undefined;
55
ts/packages/json-schema-to-zod/test/comprehensive-edge-case-tests.ts
+2 -2
@@ -163,7 +163,7 @@ const complexNestedSchema: JsonSchema = {
163 format: 'email',
164 nullable: true,
165 default: null,
166 - } as any,
166 + } as JsonSchema,
167 },
168 required: ['name'],
169 default: { id: 'user-123', name: 'Anonymous', email: null },
@@ -209,7 +209,7 @@ const complexNestedSchema: JsonSchema = {
209 type: 'string',
210 nullable: true,
211 default: null,
212 - } as any,
212 + } as JsonSchema,
213 },
214 default: {
215 settings: { theme: 'light', notifications: true },
ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
+55 -33
@@ -125,11 +125,11 @@ describe('jsonSchemaToZod', () => {
125 });
126
127 it('should handle generic min and max properties for numbers', () => {
128 - const schema: JsonSchema = {
128 + const schema = {
129 type: 'number',
130 min: 0,
131 max: 100,
132 - } as any;
132 + } satisfies JsonSchema;
133 const zodSchema = jsonSchemaToZod(schema);
134 expect(zodSchema.parse(50)).toBe(50);
135 expect(() => zodSchema.parse(-1)).toThrow();
@@ -137,13 +137,13 @@ describe('jsonSchemaToZod', () => {
137 });
138
139 it('should prioritize minimum/maximum over min/max for numbers', () => {
140 - const schema: JsonSchema = {
140 + const schema = {
141 type: 'number',
142 minimum: 10,
143 maximum: 90,
144 min: 0,
145 max: 100,
146 - } as any;
146 + } satisfies JsonSchema;
147 const zodSchema = jsonSchemaToZod(schema);
148 expect(zodSchema.parse(50)).toBe(50);
149 expect(zodSchema.parse(10)).toBe(10);
@@ -155,11 +155,11 @@ describe('jsonSchemaToZod', () => {
155
156 describe('String Validations', () => {
157 it('should handle generic min and max properties for strings', () => {
158 - const schema: JsonSchema = {
158 + const schema = {
159 type: 'string',
160 min: 3,
161 max: 10,
162 - } as any;
162 + } satisfies JsonSchema;
163 const zodSchema = jsonSchemaToZod(schema);
164 expect(zodSchema.parse('hello')).toBe('hello');
165 expect(() => zodSchema.parse('hi')).toThrow();
@@ -167,13 +167,13 @@ describe('jsonSchemaToZod', () => {
167 });
168
169 it('should prioritize minLength/maxLength over min/max for strings', () => {
170 - const schema: JsonSchema = {
170 + const schema = {
171 type: 'string',
172 minLength: 5,
173 maxLength: 8,
174 min: 3,
175 max: 10,
176 - } as any;
176 + } satisfies JsonSchema;
177 const zodSchema = jsonSchemaToZod(schema);
178 expect(zodSchema.parse('hello')).toBe('hello');
179 expect(zodSchema.parse('testing')).toBe('testing');
@@ -183,6 +183,28 @@ describe('jsonSchemaToZod', () => {
183 });
184
185 describe('Object Schemas', () => {
186 + it('should support extension keywords in nested schemas', () => {
187 + const schema = {
188 + type: 'object',
189 + properties: {
190 + username: {
191 + type: 'string',
192 + min: 3,
193 + max: 10,
194 + example: 'john_doe',
195 + },
196 + },
197 + required: ['username'],
198 + } satisfies JsonSchema;
199 +
200 + const zodSchema = jsonSchemaToZod(schema) as z.ZodObject<z.ZodRawShape>;
201 +
202 + expect(zodSchema.parse({ username: 'john_doe' })).toEqual({ username: 'john_doe' });
203 + expect(() => zodSchema.parse({ username: 'ab' })).toThrow();
204 + expect(() => zodSchema.parse({ username: 'a very long username' })).toThrow();
205 + expect(zodSchema.shape.username.description).toBe('Example: "john_doe"');
206 + });
207 +
208 it('should validate required properties', () => {
209 const schema: JsonSchema = {
210 type: 'object',
@@ -514,12 +536,12 @@ describe('jsonSchemaToZod', () => {
536 });
537
538 it('should handle generic min and max properties for arrays', () => {
517 - const schema: JsonSchema = {
539 + const schema = {
540 type: 'array',
541 items: { type: 'string' },
542 min: 1,
543 max: 3,
522 - } as any;
544 + } satisfies JsonSchema;
545 const zodSchema = jsonSchemaToZod(schema);
546 expect(zodSchema.parse(['one'])).toEqual(['one']);
547 expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
@@ -528,14 +550,14 @@ describe('jsonSchemaToZod', () => {
550 });
551
552 it('should prioritize minItems/maxItems over min/max for arrays', () => {
531 - const schema: JsonSchema = {
553 + const schema = {
554 type: 'array',
555 items: { type: 'string' },
556 minItems: 2,
557 maxItems: 4,
558 min: 1,
559 max: 3,
538 - } as any;
560 + } satisfies JsonSchema;
561 const zodSchema = jsonSchemaToZod(schema);
562 expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
563 expect(zodSchema.parse(['one', 'two', 'three', 'four'])).toEqual([
@@ -994,55 +1016,55 @@ describe('jsonSchemaToZod', () => {
1016 });
1017
1018 // Test property description
997 - const shape = (zodSchema as any)._def.shape();
1019 + const shape = (zodSchema as z.ZodObject<z.ZodRawShape>).shape;
1020 expect(shape.username.description).toBe('The username of the Hacker News user to retrieve.');
1021 });
1022
1023 it('should append example to description', () => {
1002 - const schema: JsonSchema = {
1024 + const schema = {
1025 type: 'string',
1026 description: 'User name',
1027 example: 'john_doe',
1006 - } as any;
1028 + } satisfies JsonSchema;
1029 const zodSchema = jsonSchemaToZod(schema);
1030 expect(zodSchema.description).toBe('User name\nExample: "john_doe"');
1031 });
1032
1033 it('should handle example without description', () => {
1012 - const schema: JsonSchema = {
1034 + const schema = {
1035 type: 'number',
1036 example: 42,
1015 - } as any;
1037 + } satisfies JsonSchema;
1038 const zodSchema = jsonSchemaToZod(schema);
1039 expect(zodSchema.description).toBe('Example: 42');
1040 });
1041
1042 it('should handle example with title but no description', () => {
1021 - const schema: JsonSchema = {
1043 + const schema = {
1044 type: 'object',
1045 title: 'User Object',
1046 example: { name: 'John', age: 30 },
1025 - } as any;
1047 + } satisfies JsonSchema;
1048 const zodSchema = jsonSchemaToZod(schema);
1049 expect(zodSchema.description).toBe('User Object\nExample: {"name":"John","age":30}');
1050 });
1051
1052 it('should handle single example in examples array', () => {
1031 - const schema: JsonSchema = {
1053 + const schema = {
1054 type: 'string',
1055 description: 'Property name',
1056 examples: ['lifecyclestage'],
1035 - } as any;
1057 + } satisfies JsonSchema;
1058 const zodSchema = jsonSchemaToZod(schema);
1059 expect(zodSchema.description).toBe('Property name\nExample: "lifecyclestage"');
1060 });
1061
1062 it('should handle multiple examples in examples array', () => {
1041 - const schema: JsonSchema = {
1063 + const schema = {
1064 type: 'array',
1065 description: 'List of property names',
1066 examples: ["['lifecyclestage', 'hs_lead_status']", "['hubspot_owner_id']"],
1045 - } as any;
1067 + } satisfies JsonSchema;
1068 const zodSchema = jsonSchemaToZod(schema);
1069 expect(zodSchema.description).toBe(
1070 "List of property names\nExamples:\n \"['lifecyclestage', 'hs_lead_status']\"\n \"['hubspot_owner_id']\""
@@ -1050,28 +1072,28 @@ describe('jsonSchemaToZod', () => {
1072 });
1073
1074 it('should prioritize example over examples', () => {
1053 - const schema: JsonSchema = {
1075 + const schema = {
1076 type: 'string',
1077 description: 'Property name',
1078 example: 'single_example',
1079 examples: ['example1', 'example2'],
1058 - } as any;
1080 + } satisfies JsonSchema;
1081 const zodSchema = jsonSchemaToZod(schema);
1082 expect(zodSchema.description).toBe('Property name\nExample: "single_example"');
1083 });
1084
1085 it('should handle empty examples array', () => {
1064 - const schema: JsonSchema = {
1086 + const schema = {
1087 type: 'string',
1088 description: 'Property name',
1089 examples: [],
1068 - } as any;
1090 + } satisfies JsonSchema;
1091 const zodSchema = jsonSchemaToZod(schema);
1092 expect(zodSchema.description).toBe('Property name');
1093 });
1094
1095 it('should preserve array structure in examples', () => {
1074 - const schema: JsonSchema = {
1096 + const schema = {
1097 type: 'array',
1098 description: 'Property combinations',
1099 examples: [
@@ -1079,7 +1101,7 @@ describe('jsonSchemaToZod', () => {
1101 ['hubspot_owner_id'],
1102 ['created_date', 'modified_date', 'status'],
1103 ],
1082 - } as any;
1104 + } satisfies JsonSchema;
1105 const zodSchema = jsonSchemaToZod(schema);
1106 expect(zodSchema.description).toBe(
1107 'Property combinations\nExamples:\n ["lifecyclestage","hs_lead_status"]\n ["hubspot_owner_id"]\n ["created_date","modified_date","status"]'
@@ -1087,11 +1109,11 @@ describe('jsonSchemaToZod', () => {
1109 });
1110
1111 it('should handle primitive types in examples array', () => {
1090 - const schema: JsonSchema = {
1112 + const schema = {
1113 type: 'string',
1114 description: 'Status values',
1115 examples: ['active', 'inactive', 'pending'],
1094 - } as any;
1116 + } satisfies JsonSchema;
1117 const zodSchema = jsonSchemaToZod(schema);
1118 expect(zodSchema.description).toBe(
1119 'Status values\nExamples:\n "active"\n "inactive"\n "pending"'
@@ -1099,11 +1121,11 @@ describe('jsonSchemaToZod', () => {
1121 });
1122
1123 it('should handle mixed primitive types in examples array', () => {
1102 - const schema: JsonSchema = {
1124 + const schema = {
1125 type: 'number',
1126 description: 'Various numbers',
1127 examples: [42, 3.14, 0, -5],
1106 - } as any;
1128 + } satisfies JsonSchema;
1129 const zodSchema = jsonSchemaToZod(schema);
1130 expect(zodSchema.description).toBe('Various numbers\nExamples:\n 42\n 3.14\n 0\n -5');
1131 });
ts/packages/providers/anthropic/test/anthropic.test.ts
+1 -1
@@ -28,7 +28,7 @@ vi.mock('@anthropic-ai/sdk', () => {
28 describe('AnthropicProvider', () => {
29 let provider: AnthropicProvider;
30 let mockTool: Tool;
31 - let mockExecuteToolFn: any;
31 + let mockExecuteToolFn: unknown;
32
33 beforeEach(() => {
34 provider = new AnthropicProvider();
ts/packages/providers/anthropic/test/sanitize-keys.test.ts
+37 -9
@@ -14,6 +14,13 @@ vi.mock('@anthropic-ai/sdk', () => ({
14
15 const ANTHROPIC_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
16
17 +/**
18 + * Minimal structural shape for a JSON-schema node carrying a `properties` bag,
19 + * used to dereference `sanitizeSchemaPropertyKeys` output (typed loosely as the
20 + * generic input schema) in test assertions without weakening the cast to `any`.
21 + */
22 +type SchemaWithProperties = { properties: Record<string, unknown>; required?: string[] };
23 +
24 describe('sanitizeSchemaPropertyKeys', () => {
25 it('leaves already-valid keys untouched and reports no mapping', () => {
26 const schema = {
@@ -121,7 +128,7 @@ describe('sanitizeSchemaPropertyKeys', () => {
128 };
129
130 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
124 - const nested = (out.properties as any).options;
131 + const nested = (out.properties as unknown as { options: SchemaWithProperties }).options;
132
133 expect(nested.properties).toHaveProperty('dollar_skip');
134 expect(nested.required).toEqual(['dollar_skip']);
@@ -162,7 +169,8 @@ describe('sanitizeSchemaPropertyKeys', () => {
169 };
170
171 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
165 - const itemSchema = (out.properties as any).rows.items;
172 + const itemSchema = (out.properties as unknown as { rows: { items: SchemaWithProperties } }).rows
173 + .items;
174
175 expect(itemSchema.properties).toHaveProperty('dollar_top');
176 expect(itemSchema.properties).not.toHaveProperty('$top');
@@ -188,7 +196,11 @@ describe('sanitizeSchemaPropertyKeys', () => {
196 };
197
198 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
191 - const [first, second] = (out.properties as any).pair.items;
199 + const [first, second] = (
200 + out.properties as unknown as {
201 + pair: { items: [SchemaWithProperties, SchemaWithProperties] };
202 + }
203 + ).pair.items;
204
205 expect(first.properties).toHaveProperty('dollar_top');
206 expect(second.properties).toHaveProperty('plain');
@@ -285,7 +297,13 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
297
298 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
299 expectNoIllegalPropertyKeys(out);
288 - expect((out.properties as any).foo.anyOf[0].properties).toHaveProperty('dollar_top');
300 + expect(
301 + (
302 + out.properties as unknown as {
303 + foo: { anyOf: SchemaWithProperties[] };
304 + }
305 + ).foo.anyOf[0].properties
306 + ).toHaveProperty('dollar_top');
307
308 // The branch rename folds into `foo`'s value level, so restoration finds it.
309 expect(restoreOriginalKeys({ foo: { dollar_top: 5 } }, mapping)).toEqual({ foo: { $top: 5 } });
@@ -342,7 +360,10 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
360
361 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
362 // 400-prevention: the alias is emitted so Anthropic accepts the schema.
345 - expect((out as any).additionalProperties.properties).toHaveProperty('dollar_top');
363 + expect(
364 + (out as unknown as { additionalProperties: SchemaWithProperties }).additionalProperties
365 + .properties
366 + ).toHaveProperty('dollar_top');
367 // Documented limitation: dynamic-key values are not restored — the alias
368 // reaches the backend rather than being silently (mis)mapped at every level.
369 expect(restoreOriginalKeys({ anyKey: { dollar_top: 1 } }, mapping)).toEqual({
@@ -358,7 +379,9 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
379 });
380
381 expectNoIllegalPropertyKeys(out);
361 - expect((out as any).$defs.Foo.properties).toHaveProperty('dollar_top');
382 + expect(
383 + (out as unknown as { $defs: { Foo: SchemaWithProperties } }).$defs.Foo.properties
384 + ).toHaveProperty('dollar_top');
385 });
386
387 it('sanitizes and restores `prefixItems` tuples', () => {
@@ -450,7 +473,9 @@ describe('restoreOriginalKeys', () => {
473 const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
474
475 expect(out.properties).toHaveProperty('dollar_top');
453 - expect((out.properties as any).filters.properties).toHaveProperty('dollar_top');
476 + expect(
477 + (out.properties as unknown as { filters: SchemaWithProperties }).filters.properties
478 + ).toHaveProperty('dollar_top');
479
480 const restored = restoreOriginalKeys(
481 { dollar_top: 10, filters: { dollar_top: 'keep-me' } },
@@ -676,8 +701,11 @@ describe('AnthropicProvider key sanitization', () => {
701
702 const wrapped = provider.wrapTool(refTool) as AnthropicTool;
703 // The $ref is inlined, `$defs` removed, and the nested `$top` sanitized.
679 - expect((wrapped.input_schema.properties as any).filter.properties).toHaveProperty('dollar_top');
680 - expect((wrapped.input_schema as any).$defs).toBeUndefined();
704 + expect(
705 + (wrapped.input_schema.properties as unknown as { filter: SchemaWithProperties }).filter
706 + .properties
707 + ).toHaveProperty('dollar_top');
708 + expect((wrapped.input_schema as unknown as { $defs?: unknown }).$defs).toBeUndefined();
709
710 await provider.executeToolCall('user-1', {
711 type: 'tool_use',
ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
+46 -13
@@ -1,5 +1,5 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
2 -import { Tool } from '@composio/core';
1 +import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
2 +import { Tool, GlobalExecuteToolFn } from '@composio/core';
3 import { ClaudeAgentSDKProvider } from '../src';
4
5 // Mock the claude-agent-sdk module
@@ -24,15 +24,46 @@ import { tool } from '@anthropic-ai/claude-agent-sdk';
24 interface MockedClaudeAgentTool {
25 name: string;
26 description: string;
27 - schema: any;
27 + schema: unknown;
28 handler: Function;
29 _isMockedClaudeAgentTool: boolean;
30 }
31
32 +// Minimal structural type for a zod-like raw shape value, matching only the member these
33 +// tests dereference (`safeParse`).
34 +type MinimalZodSchema = {
35 + safeParse: (value: unknown) => { success: boolean };
36 +};
37 +
38 +// The handler captured off the mocked `tool()` call. Some tests intentionally pass a raw
39 +// (possibly malformed) JSON string instead of an object to exercise the stringified-input
40 +// normalization path (issue #2406), so the parameter is typed `unknown` here rather than the
41 +// stricter `Record<string, unknown>` used by the real `wrapTool` handler signature.
42 +type MockedToolHandler = (
43 + args: unknown
44 +) => Promise<{ content: Array<{ type: string; text: string }> }>;
45 +
46 +type MockedToolFn = Mock<
47 + (
48 + name: string,
49 + description: string | undefined,
50 + schema: Record<string, MinimalZodSchema>,
51 + handler: MockedToolHandler
52 + ) => unknown
53 +>;
54 +
55 +// `mockExecuteToolFn` is declared against the real `GlobalExecuteToolFn` contract, which always
56 +// resolves with a `ToolExecuteResponse`. A couple of tests deliberately stub it with a plain
57 +// string / `undefined` to exercise the wrapTool handler's defensive "stringify anything" branch,
58 +// so those specific stubbing calls need a widened, minimal view of just the method they use.
59 +type MockResolvableWithAnyValue = {
60 + mockResolvedValueOnce: (value: unknown) => void;
61 +};
62 +
63 describe('ClaudeAgentSDKProvider', () => {
64 let provider: ClaudeAgentSDKProvider;
65 let mockTool: Tool;
35 - let mockExecuteToolFn: any;
66 + let mockExecuteToolFn: Mock<GlobalExecuteToolFn>;
67
68 beforeEach(() => {
69 provider = new ClaudeAgentSDKProvider();
@@ -111,7 +142,7 @@ describe('ClaudeAgentSDKProvider', () => {
142 it('should pass a raw Zod shape to the Claude Agent SDK', () => {
143 provider.wrapTool(mockTool, mockExecuteToolFn);
144
114 - const schemaShape = (tool as any).mock.calls[0][2];
145 + const schemaShape = (tool as unknown as MockedToolFn).mock.calls[0][2];
146 expect(Object.keys(schemaShape)).toEqual(['to', 'subject', 'body']);
147 expect(schemaShape.to.safeParse('test@example.com').success).toBe(true);
148 expect(schemaShape.to.safeParse(123).success).toBe(false);
@@ -161,7 +192,7 @@ describe('ClaudeAgentSDKProvider', () => {
192 provider.wrapTool(mockTool, mockExecuteToolFn);
193
194 // Extract the handler function from the call to tool()
164 - const handler = (tool as any).mock.calls[0][3];
195 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
196
197 // Test the handler
198 const params = { to: 'test@example.com', subject: 'Test', body: 'Hello' };
@@ -184,7 +215,7 @@ describe('ClaudeAgentSDKProvider', () => {
215
216 it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
217 provider.wrapTool(mockTool, mockExecuteToolFn);
187 - const handler = (tool as any).mock.calls[0][3];
218 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
219
220 const params = { to: 'test@example.com', subject: 'Test', body: 'Hello' };
221 await handler(JSON.stringify(params));
@@ -194,7 +225,7 @@ describe('ClaudeAgentSDKProvider', () => {
225
226 it('should surface a typed error for a malformed-JSON string input (issue #2406)', async () => {
227 provider.wrapTool(mockTool, mockExecuteToolFn);
197 - const handler = (tool as any).mock.calls[0][3];
228 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
229
230 const result = await handler('{"to":');
231
@@ -206,10 +237,12 @@ describe('ClaudeAgentSDKProvider', () => {
237 });
238
239 it('should handle string results from tool execution', async () => {
209 - mockExecuteToolFn.mockResolvedValueOnce('Simple string result');
240 + (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(
241 + 'Simple string result'
242 + );
243 provider.wrapTool(mockTool, mockExecuteToolFn);
244
212 - const handler = (tool as any).mock.calls[0][3];
245 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
246 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
247
248 expect(result).toEqual({
@@ -223,10 +256,10 @@ describe('ClaudeAgentSDKProvider', () => {
256 });
257
258 it('should handle undefined results from tool execution and convert to "null" string', async () => {
226 - mockExecuteToolFn.mockResolvedValueOnce(undefined);
259 + (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(undefined);
260 provider.wrapTool(mockTool, mockExecuteToolFn);
261
229 - const handler = (tool as any).mock.calls[0][3];
262 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
263 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
264
265 // text should always be a string, never undefined
@@ -239,7 +272,7 @@ describe('ClaudeAgentSDKProvider', () => {
272 mockExecuteToolFn.mockRejectedValueOnce(testError);
273 provider.wrapTool(mockTool, mockExecuteToolFn);
274
242 - const handler = (tool as any).mock.calls[0][3];
275 + const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
276 const result = await handler({ to: 'test@example.com', subject: 'Test', body: 'Hello' });
277
278 expect(result.content[0].type).toBe('text');
ts/packages/providers/cloudflare/test/cloudflare.test.ts
+3 -3
@@ -6,7 +6,7 @@ import { Tool } from '@composio/core';
6 interface AiTextGenerationFunction {
7 name: string;
8 description: string;
9 - parameters: any;
9 + parameters: unknown;
10 }
11
12 interface MockedCloudflareToolInput {
@@ -14,7 +14,7 @@ interface MockedCloudflareToolInput {
14 function: {
15 name: string;
16 description?: string;
17 - parameters?: any;
17 + parameters?: unknown;
18 };
19 }
20
@@ -26,7 +26,7 @@ vi.mock('@cloudflare/workers-types', () => {
26 describe('CloudflareProvider', () => {
27 let provider: CloudflareProvider;
28 let mockTool: Tool;
29 - let mockExecuteToolFn: any;
29 + let mockExecuteToolFn: unknown;
30
31 beforeEach(() => {
32 provider = new CloudflareProvider();
ts/packages/providers/google/test/google.test.ts
+1 -1
@@ -5,7 +5,7 @@ import { Tool } from '@composio/core';
5 describe('GoogleProvider', () => {
6 let provider: GoogleProvider;
7 let mockTool: Tool;
8 - let mockExecuteToolFn: any;
8 + let mockExecuteToolFn: unknown;
9
10 beforeEach(() => {
11 provider = new GoogleProvider();
ts/packages/providers/langchain/test/langchain.test.ts
+1 -1
@@ -6,7 +6,7 @@ import { DynamicStructuredTool } from '@langchain/core/tools';
6 describe('LangchainProvider', () => {
7 let provider: LangchainProvider;
8 let sampleTool: Tool;
9 - let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<any>;
9 + let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<unknown>;
10
11 beforeEach(() => {
12 provider = new LangchainProvider();
ts/packages/providers/llamaindex/test/llamaindex.test.ts
+1 -1
@@ -23,7 +23,7 @@ vi.mock('llamaindex', () => {
23 describe('LlamaindexProvider', () => {
24 let provider: LlamaindexProvider;
25 let sampleTool: Tool;
26 - let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<any>;
26 + let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<unknown>;
27
28 beforeEach(() => {
29 provider = new LlamaindexProvider();
ts/packages/providers/mastra/test/mastra.test.ts
+21 -12
@@ -1,4 +1,4 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
2 import { MastraProvider } from '../src';
3 import { Tool } from '@composio/core';
4 import { createTool } from '@mastra/core/tools';
@@ -7,12 +7,21 @@ import { createTool } from '@mastra/core/tools';
7 interface MockedMastraTool {
8 id: string;
9 description: string;
10 - inputSchema?: any;
11 - outputSchema?: any;
10 + inputSchema?: unknown;
11 + outputSchema?: unknown;
12 execute: Function;
13 _isMockedMastraTool: boolean;
14 }
15
16 +// Minimal shape of the config object the wrapped tool's `execute` closure is
17 +// pulled off of, i.e. the argument the mocked `createTool` factory (below) was
18 +// called with. Only `execute` is dereferenced at the `.mock.calls[...][0]`
19 +// call sites in this file, so that's all this type declares.
20 +type CreateToolMockConfig = { execute: (...args: unknown[]) => unknown };
21 +type CreateToolMock = Mock<(config: CreateToolMockConfig) => unknown>;
22 +const getCreatedToolExecute = () =>
23 + (createTool as unknown as CreateToolMock).mock.calls[0][0].execute;
24 +
25 // Mock the @mastra/core/tools module
26 vi.mock('@mastra/core/tools', () => {
27 return {
@@ -61,7 +70,7 @@ const RELAXED_MOCK_OUTPUT_SCHEMA = {
70 describe('MastraProvider', () => {
71 let provider: MastraProvider;
72 let mockTool: Tool;
64 - let mockExecuteToolFn: any;
73 + let mockExecuteToolFn: Mock;
74
75 beforeEach(() => {
76 provider = new MastraProvider();
@@ -226,7 +235,7 @@ describe('MastraProvider', () => {
235 provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
236
237 // Extract the execute function from the call to createTool()
229 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
238 + const executeFunction = getCreatedToolExecute();
239
240 // Test the execute function
241 const inputData = { input: 'test-value' };
@@ -245,7 +254,7 @@ describe('MastraProvider', () => {
254 provider.wrapTool(toolWithVersion, mockExecuteToolFn) as unknown as MockedMastraTool;
255
256 // Extract the execute function from the call to createTool()
248 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
257 + const executeFunction = getCreatedToolExecute();
258
259 // Test that the version is passed correctly
260 const inputData = { input: 'version-test' };
@@ -259,7 +268,7 @@ describe('MastraProvider', () => {
268 provider.wrapTool(toolWithoutVersion, mockExecuteToolFn) as unknown as MockedMastraTool;
269
270 // Extract the execute function from the call to createTool()
262 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
271 + const executeFunction = getCreatedToolExecute();
272
273 // Test that undefined version is passed correctly
274 const inputData = { input: 'no-version-test' };
@@ -272,7 +281,7 @@ describe('MastraProvider', () => {
281 provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
282
283 // Extract the execute function from the call to createTool()
275 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
284 + const executeFunction = getCreatedToolExecute();
285
286 // Test the execute function with empty input
287 const result = await executeFunction({});
@@ -289,7 +298,7 @@ describe('MastraProvider', () => {
298 provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
299
300 // Extract the execute function from the call to createTool()
292 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
301 + const executeFunction = getCreatedToolExecute();
302
303 // Test the execute function without any parameters: a missing payload is
304 // normalized to an empty object rather than forwarded as undefined (issue #2406).
@@ -487,7 +496,7 @@ describe('MastraProvider', () => {
496 mockTool,
497 errorExecuteToolFn
498 ) as unknown as MockedMastraTool;
490 - const executeFunction = (createTool as any).mock.calls[0][0].execute;
499 + const executeFunction = getCreatedToolExecute();
500
501 await expect(executeFunction({ input: 'test' })).rejects.toThrow('Execution failed');
502 });
@@ -495,7 +504,7 @@ describe('MastraProvider', () => {
504 it('should handle tools with malformed schemas', () => {
505 const toolWithMalformedSchema: Tool = {
506 ...mockTool,
498 - inputParameters: null as any,
507 + inputParameters: null as unknown,
508 outputParameters: undefined,
509 };
510
@@ -639,7 +648,7 @@ describe('MastraProvider', () => {
648 inputParameters: {
649 type: 'string',
650 description: 'A string parameter',
642 - } as any,
651 + } as unknown,
652 };
653
654 strictProvider.wrapTool(toolWithNonObjectParams, mockExecuteToolFn);
ts/packages/providers/openai-agents/test/openai-agents.test.ts
+2 -2
@@ -7,7 +7,7 @@ import { tool as createOpenAIAgentTool } from '@openai/agents';
7 interface MockedOpenAIAgentTool {
8 name: string;
9 description: string;
10 - parameters: any;
10 + parameters: unknown;
11 execute: Function;
12 _isMockedOpenAIAgentTool: boolean;
13 }
@@ -27,7 +27,7 @@ vi.mock('@openai/agents', () => {
27 describe('OpenAIAgentsProvider', () => {
28 let provider: OpenAIAgentsProvider;
29 let mockTool: Tool;
30 - let mockExecuteToolFn: any;
30 + let mockExecuteToolFn: unknown;
31
32 beforeEach(() => {
33 provider = new OpenAIAgentsProvider();
ts/packages/providers/openai/test/opeanai-responses.test.ts
+2 -2
@@ -28,14 +28,14 @@ interface MockedOpenAITool {
28 type: 'function';
29 name: string;
30 description?: string;
31 - parameters?: any;
31 + parameters?: unknown;
32 strict?: boolean;
33 }
34
35 describe('OpenAIResponsesProvider', () => {
36 let provider: OpenAIResponsesProvider;
37 let mockTool: Tool;
38 - let mockExecuteToolFn: any;
38 + let mockExecuteToolFn: unknown;
39
40 beforeEach(() => {
41 provider = new OpenAIResponsesProvider();
ts/packages/providers/openai/test/openai.test.ts
+2 -2
@@ -37,14 +37,14 @@ interface MockedOpenAIChatCompletionTool {
37 function: {
38 name: string;
39 description?: string;
40 - parameters?: any;
40 + parameters?: unknown;
41 };
42 }
43
44 describe('OpenAIProvider', () => {
45 let provider: OpenAIProvider;
46 let mockTool: Tool;
47 - let mockExecuteToolFn: any;
47 + let mockExecuteToolFn: unknown;
48
49 beforeEach(() => {
50 provider = new OpenAIProvider();
ts/packages/providers/vercel/test/vercel.test.ts
+8 -4
@@ -1,4 +1,4 @@
1 -import { describe, it, expect, vi, beforeEach } from 'vitest';
1 +import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
2 import { VercelProvider } from '../src';
3 import { Tool } from '@composio/core';
4 import { tool } from 'ai';
@@ -6,7 +6,7 @@ import { tool } from 'ai';
6 // Define an interface for our mocked Vercel tool
7 interface MockedVercelTool {
8 description: string;
9 - inputSchema: any;
9 + inputSchema: unknown;
10 execute: Function;
11 _isMockedVercelTool: boolean;
12 }
@@ -27,7 +27,7 @@ vi.mock('ai', () => {
27 describe('VercelProvider', () => {
28 let provider: VercelProvider;
29 let mockTool: Tool;
30 - let mockExecuteToolFn: any;
30 + let mockExecuteToolFn: Mock;
31
32 beforeEach(() => {
33 provider = new VercelProvider();
@@ -114,7 +114,11 @@ describe('VercelProvider', () => {
114 provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedVercelTool;
115
116 // Extract the execute function from the call to tool()
117 - const executeFunction = (tool as any).mock.calls[0][0].execute;
117 + const executeFunction = (
118 + tool as unknown as Mock<
119 + (config: { execute: (input: unknown) => Promise<unknown> }) => unknown
120 + >
121 + ).mock.calls[0][0].execute;
122
123 // Test the execute function with an object parameter
124 const params = { input: 'test-value' };
ts/packages/ts-builders/src/File.ts
+2 -2
@@ -6,8 +6,8 @@ import type { ExportFrom } from './ExportFrom';
6 import type { Import } from './Import';
7 import { Writer } from './Writer';
8
9 -// eslint-disable-next-line @typescript-eslint/no-explicit-any
10 -export type FileItem = AnyDeclarationBuilder | Export<any> | ExportFrom | DocSectionComment;
9 +export type FileItem =
10 + AnyDeclarationBuilder | Export<AnyDeclarationBuilder> | ExportFrom | DocSectionComment;
11 export class File implements BasicBuilder {
12 private imports: Import[] = [];
13 private declarations: FileItem[] = [];