Skip to content

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

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

Alberto Schiabel150378635820
diff --git a/.changeset/forbid-explicit-any.md b/.changeset/forbid-explicit-any.md
new file mode 100644
index 000000000..85e188d1e
--- /dev/null
+++ b/.changeset/forbid-explicit-any.md
@@ -0,0 +1,14 @@
+---
+'@composio/core': minor
+---
+
+Replace the loose JSON Schema property type with a recursive, type-safe definition.
+
+`JSONSchemaProperty` (re-exported from `@composio/core` and reachable through
+`Tool.input_parameters` / `Tool.output_parameters`) is now a concrete recursive
+interface instead of effectively `any`. Runtime behavior is unchanged, but
+consumer code that indexed into it without narrowing (for example
+`schema.properties.foo.type` or `schema.default.someField`) may see new type
+errors: `properties` entries are now possibly `undefined` and `default` /
+`enum` values are `unknown`. Narrow with optional chaining or explicit type
+guards when upgrading.
diff --git a/.changeset/type-json-schema-extensions.md b/.changeset/type-json-schema-extensions.md
new file mode 100644
index 000000000..8b7b17bac
--- /dev/null
+++ b/.changeset/type-json-schema-extensions.md
@@ -0,0 +1,5 @@
+---
+'@composio/json-schema-to-zod': patch
+---
+
+Model the parser-supported `min`, `max`, and `example` JSON Schema extensions in the exported recursive schema type.
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 1801ddc7c..598f53f5d 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -16,40 +16,31 @@
"**/.next/**",
"**/dist/**",
"**/site-packages/**",
- "**/__fixtures__/**",
- "**/fixtures/**",
- // New exclusion vs eslint.config.mjs: mock modules are test scaffolding,
- // same as fixtures; the CI gate (pnpm lint → ts/packages) never reached them.
- "**/__mocks__/**",
// The docs site has its own Bun dependency tree and nested oxlint config.
"docs/**",
"ts/vendor/**",
"ts/packages/cli-local-tools/vendor/**",
+ "ts/packages/core/generated/**",
+ "ts/packages/core/pack/generated/**",
+ "ts/packages/slim/generated/**",
"ts/packages/**/.generated/**",
"ts/packages/**/acp-adapters/**",
"node_modules/**",
"ts/examples/**/dist-worker/**",
- "scripts/**",
- "test/**",
- "ts/packages/*/test/**",
- "ts/packages/providers/*/test/**",
- "!ts/packages/cli/test/**",
- "ts/packages/cli/test/__utils__/**",
- // New exclusions vs eslint.config.mjs: the CI gate (pnpm lint) only ever
- // targeted ts/packages, so e2e suites and repo scripts were lint:fix-only
- // surface. Excluded explicitly now that oxlint also runs from the repo root.
- "ts/e2e-tests/**",
- "ts/scripts/**",
+ "ts/examples/cloudflare-wrangler/worker-configuration.d.ts",
// ESLint only linted .ts/.tsx (--ext .ts,.tsx); keep that scope.
"**/*.js",
"**/*.mjs",
"**/*.cjs",
- "**/*.jsx",
- // New exclusion vs eslint.config.mjs (which matched .d.ts via --ext .ts):
- // ambient declarations are type-only surface covered by typecheck.
- "**/*.d.ts"
+ "**/*.jsx"
],
"rules": {
+ // tseslint.configs.recommended rules that oxlint's correctness category
+ // does not enable by default; re-enabled explicitly to keep the migration
+ // behavior-preserving in this direction too.
+ "typescript/no-namespace": "error",
+ "no-array-constructor": "error",
+ "typescript/no-unnecessary-type-constraint": "error",
// Rules oxlint enables by default that the previous ESLint setup did not
// enforce. Turned off to keep the migration behavior-preserving; each is a
// candidate to enable (and burn down) in a follow-up.
@@ -99,6 +90,34 @@
]
},
"overrides": [
+ {
+ // These files still enforce the repository-wide no-any rule, but are
+ // exempt from source-only policies that do not fit test helpers, large
+ // suites, scripts, fixtures, or ambient declarations.
+ "files": [
+ "**/__fixtures__/**/*.{ts,tsx,mts,cts}",
+ "**/__mocks__/**/*.{ts,tsx,mts,cts}",
+ "**/fixtures/**/*.{ts,tsx,mts,cts}",
+ "scripts/**/*.{ts,tsx,mts,cts}",
+ "test/**/*.{ts,tsx,mts,cts}",
+ "ts/e2e-tests/**/*.{ts,tsx,mts,cts}",
+ "ts/packages/**/test/**/*.{ts,tsx,mts,cts}",
+ "ts/packages/**/*.d.ts",
+ "ts/scripts/**/*.{ts,tsx,mts,cts}"
+ ],
+ "rules": {
+ "max-lines-per-function": "off",
+ "no-console": "off",
+ "no-restricted-globals": "off",
+ "no-restricted-imports": "off",
+ "no-unused-vars": "off",
+ "prefer-const": "off",
+ "require-yield": "off",
+ "typescript/ban-ts-comment": "off",
+ "typescript/no-empty-object-type": "off",
+ "typescript/no-namespace": "off"
+ }
+ },
{
"files": ["ts/packages/cli/src/**/*.{ts,tsx}"],
"rules": {
@@ -206,7 +225,6 @@
"files": ["ts/packages/cli/test/src/**/*.{ts,tsx}"],
"rules": {
"max-lines-per-function": "off",
- "typescript/no-explicit-any": "off",
"eslint-js/no-restricted-syntax": [
"error",
{
diff --git a/package.json b/package.json
index 2d6e492f0..296031f46 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,7 @@
"typecheck": "turbo typecheck --filter=./ts/packages/**",
"typecheck:examples": "turbo typecheck --filter='./ts/examples/*'",
"lint:examples": "turbo lint --filter='./ts/examples/*'",
- "lint": "oxlint ts/packages",
+ "lint": "oxlint ts test tsdown.config.base.ts",
"lint:packages": "oxlint ts/packages",
"lint:fix": "oxlint --fix .",
"lint:fix:packages": "oxlint --fix ts/packages",
@@ -96,7 +96,10 @@
"zod": "catalog:"
},
"lint-staged": {
- "ts/packages/**/*.{ts,tsx}": [
+ "{test,ts}/**/*.{ts,tsx,mts,cts}": [
+ "oxlint --fix"
+ ],
+ "tsdown.config.base.ts": [
"oxlint --fix"
],
"ts/packages/**/*.{ts,tsx,js,jsx,json,md}": [
diff --git a/ts/examples/tool-router/package.json b/ts/examples/tool-router/package.json
index 798e6ad77..98c728948 100644
--- a/ts/examples/tool-router/package.json
+++ b/ts/examples/tool-router/package.json
@@ -9,6 +9,8 @@
"dev": "bun --watch src/index.ts",
"preload": "bun src/preload.ts",
"direct-tools": "bun src/direct-tools-preset.ts",
+ "typecheck": "tsc --noEmit -p ./tsconfig.json",
+ "lint": "oxlint -c ../../../.oxlintrc.json src",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
diff --git a/ts/examples/tool-router/src/custom-tools-agent.ts b/ts/examples/tool-router/src/custom-tools-agent.ts
index c51bbf287..c35f1af23 100644
--- a/ts/examples/tool-router/src/custom-tools-agent.ts
+++ b/ts/examples/tool-router/src/custom-tools-agent.ts
@@ -201,12 +201,13 @@ function trunc(obj: unknown): string {
return json.length > MAX ? json.slice(0, MAX) + "\n ... (truncated)" : json;
}
-agent.on("agent_tool_start", (_ctx, tool, details: any) => {
- const input = details.toolCall?.arguments ?? {};
+agent.on("agent_tool_start", (_ctx, tool, details) => {
+ const toolCall = details.toolCall;
+ const input = toolCall && "arguments" in toolCall ? (toolCall.arguments ?? {}) : {};
console.log(`\n ┌─ ${tool.name}`);
console.log(` │ INPUT:\n${trunc(input)}`);
});
-agent.on("agent_tool_end", (_ctx, tool, result: any) => {
+agent.on("agent_tool_end", (_ctx, tool, result: unknown) => {
let output: unknown;
try { output = typeof result === "string" ? JSON.parse(result) : result; } catch { output = result; }
console.log(` │ OUTPUT:\n${trunc(output)}`);
diff --git a/ts/examples/tool-router/src/openai-agents.ts b/ts/examples/tool-router/src/openai-agents.ts
index 9928aad40..64547f224 100644
--- a/ts/examples/tool-router/src/openai-agents.ts
+++ b/ts/examples/tool-router/src/openai-agents.ts
@@ -1,5 +1,5 @@
import { Composio } from '@composio/core';
-import { Agent, hostedMcpTool, run } from '@openai/agents';
+import { Agent, hostedMcpTool, run, type AgentInputItem } from '@openai/agents';
import { createInterface } from 'node:readline/promises';
const composio = new Composio();
@@ -22,10 +22,13 @@ const agent = new Agent({
const rl = createInterface({ input: process.stdin, output: process.stdout });
-for (let input: any = await rl.question('You: '); input !== 'exit';) {
+for (let input: string | AgentInputItem[] = await rl.question('You: '); input !== 'exit';) {
const result = await run(agent, input);
console.log(`Agent: ${result.finalOutput}\n`);
- input = [...result.history, { role: 'user' as const, content: await rl.question('You: ') }];
+ input = [
+ ...result.history,
+ { role: 'user' as const, content: await rl.question('You: ') },
+ ] as AgentInputItem[];
}
rl.close();
diff --git a/ts/packages/cli/test/__utils__/cli.ts b/ts/packages/cli/test/__utils__/cli.ts
index 22cc586ec..7bbfd9911 100644
--- a/ts/packages/cli/test/__utils__/cli.ts
+++ b/ts/packages/cli/test/__utils__/cli.ts
@@ -2,5 +2,5 @@ import { Effect } from 'effect';
import * as Cli from 'src/commands';
// Run CLI in test environment
-export const cli = (args: ReadonlyArray<string>): Effect.Effect<void, unknown, any> =>
+export const cli = (args: ReadonlyArray<string>) =>
Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args]));
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index 1bcc22c4a..2e9a0aa85 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -1,4 +1,5 @@
import * as tempy from 'tempy';
+import { Composio as RawComposioClient } from '@composio/client';
import { CliApp, CliConfig } from '@effect/cli';
import { Command, FetchHttpClient, FileSystem, Path } from '@effect/platform';
import { BunFileSystem, BunContext, BunPath } from '@effect/platform-bun';
@@ -218,7 +219,7 @@ export interface TestLiveInput {
* Layer<RequirementsOut, Error, RequirementsIn>
*/
-type RequiredLayer = Layer.Layer<any, any, never>;
+type RequiredLayer = Layer.Layer<CliApp.CliApp.Environment, unknown, never>;
const ConsumerProjectResolveFetchMock = Layer.scopedDiscard(
Effect.acquireRelease(
@@ -989,7 +990,7 @@ export const TestLayer = (input?: TestLiveInput) =>
};
};
- const mockComposioClient = {
+ const mockComposioClient = Object.assign(new RawComposioClient({ apiKey: 'test' }), {
link: {
create: async (params: { auth_config_id: string; user_id: string }) => {
const response = connectedAccountsData.linkResponse ?? {
@@ -1186,21 +1187,16 @@ export const TestLayer = (input?: TestLiveInput) =>
}),
},
},
- };
+ });
const ComposioClientSingletonTest = Layer.succeed(
ComposioClientSingleton,
new ComposioClientSingleton({
get: Effect.fn(function* () {
- // Partial mock: only implements `toolRouter.session.*` methods used by
- // CLI commands under test. The full Composio client interface is too
- // large to mock completely for unit tests.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return mockComposioClient as any;
+ return mockComposioClient;
}),
getFor: Effect.fn(function* () {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return mockComposioClient as any;
+ return mockComposioClient;
}),
})
);
diff --git a/ts/packages/cli/test/src/commands/run.cmd.test.ts b/ts/packages/cli/test/src/commands/run.cmd.test.ts
index 70648cae0..96958abe6 100644
--- a/ts/packages/cli/test/src/commands/run.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/run.cmd.test.ts
@@ -42,7 +42,7 @@ describe('CLI: composio run', () => {
'[Given] inline code and args [Then] it forwards them to the embedded Bun runtime',
() =>
Effect.gen(function* () {
- const spawn = vi.fn(() => ({ exited: Promise.resolve(7) }));
+ const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(7) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
vi.stubGlobal('Bun', { spawn });
@@ -50,7 +50,7 @@ describe('CLI: composio run', () => {
const output = yield* MockConsole.getLines();
expect(spawn).toHaveBeenCalledTimes(1);
- const spawnConfig = (spawn as any).mock.calls[0][0] as {
+ const spawnConfig = spawn.mock.calls[0][0] as {
cmd: string[];
env: unknown;
stdio: string[];
@@ -81,14 +81,14 @@ describe('CLI: composio run', () => {
'[Given] --acp-only [Then] run accepts the flag and forwards execution normally',
() =>
Effect.gen(function* () {
- const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
+ const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
vi.stubGlobal('Bun', { spawn });
yield* cli(['run', '--acp-only', 'console.log("hi")']);
expect(spawn).toHaveBeenCalledTimes(1);
- const spawnConfig = (spawn as any).mock.calls[0][0] as {
+ const spawnConfig = spawn.mock.calls[0][0] as {
cmd: string[];
};
expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -102,14 +102,14 @@ describe('CLI: composio run', () => {
'[Given] --logs-off [Then] run accepts the flag and forwards execution normally',
() =>
Effect.gen(function* () {
- const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
+ const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
vi.stubGlobal('Bun', { spawn });
yield* cli(['run', '--logs-off', 'console.log("hi")']);
expect(spawn).toHaveBeenCalledTimes(1);
- const spawnConfig = (spawn as any).mock.calls[0][0] as {
+ const spawnConfig = spawn.mock.calls[0][0] as {
cmd: string[];
};
expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -140,14 +140,14 @@ describe('CLI: composio run', () => {
console.log(JSON.stringify(brief));
console.log(JSON.stringify(brief.structuredOutput));
`;
- const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
+ const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
vi.stubGlobal('Bun', { spawn });
yield* cli(['run', '--logs-off', script]);
expect(spawn).toHaveBeenCalledTimes(1);
- const spawnConfig = (spawn as any).mock.calls[0][0] as {
+ const spawnConfig = spawn.mock.calls[0][0] as {
cmd: string[];
};
expect(spawnConfig.cmd[3]).toBe('--eval');
@@ -171,7 +171,7 @@ describe('CLI: composio run', () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-test-'));
const scriptPath = path.join(tempDir, 'script.ts');
fs.writeFileSync(scriptPath, 'const value = 1 + 1;\nvalue * 2;\n', 'utf8');
- const spawn = vi.fn(() => ({ exited: Promise.resolve(0) }));
+ const spawn = vi.fn((_options: unknown) => ({ exited: Promise.resolve(0) }));
const exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
vi.stubGlobal('Bun', { spawn });
@@ -179,7 +179,7 @@ describe('CLI: composio run', () => {
yield* cli(['run', '--file', scriptPath, '--', 'hello']);
expect(spawn).toHaveBeenCalledTimes(1);
- const spawnConfig = (spawn as any).mock.calls[0][0] as {
+ const spawnConfig = spawn.mock.calls[0][0] as {
cmd: string[];
env: unknown;
stdio: string[];
diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
index 687b55d5d..57d064d23 100644
--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.info.cmd.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect } from 'effect';
+import { ConfigProvider, DateTime, Effect } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20250101', '20250601', '20250909'],
tools_count: 36,
triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Execute code in a sandboxed environment',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 1,
triggers_count: 0,
@@ -52,8 +52,8 @@ const detailedToolkits: ToolkitDetailed[] = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20250101', '20250601', '20250909'],
tools_count: 36,
triggers_count: 2,
@@ -110,8 +110,8 @@ const detailedToolkits: ToolkitDetailed[] = [
meta: {
description: 'Execute code snippets',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 5,
triggers_count: 0,
diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
index 1d2598174..a96f374f9 100644
--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.list.cmd.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect } from 'effect';
+import { ConfigProvider, DateTime, Effect } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20250101', '20250909'],
tools_count: 36,
triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Messaging platform for teams',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 42,
triggers_count: 5,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Code hosting and collaboration platform',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20260101'],
tools_count: 50,
triggers_count: 10,
diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
index 0c8f26caf..92fc26114 100644
--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.search.cmd.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect } from 'effect';
+import { ConfigProvider, DateTime, Effect } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -16,8 +16,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20250909'],
tools_count: 36,
triggers_count: 2,
@@ -33,8 +33,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Microsoft email service',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 28,
triggers_count: 1,
@@ -50,8 +50,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Messaging platform for teams',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20250101', '20260101'],
tools_count: 42,
triggers_count: 5,
diff --git a/ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts b/ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
index 059955075..5973797c4 100644
--- a/ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/toolkits/toolkits.version.cmd.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, layer } from '@effect/vitest';
-import { ConfigProvider, Effect } from 'effect';
+import { ConfigProvider, DateTime, Effect } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { cli, TestLive, MockConsole } from 'test/__utils__';
import type { TestLiveInput } from 'test/__utils__/services/test-layer';
@@ -21,8 +21,8 @@ const testToolkits: Toolkits = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: versionHistory,
tools_count: 36,
triggers_count: 2,
@@ -40,8 +40,8 @@ const detailedToolkits: ToolkitDetailed[] = [
meta: {
description: 'Email service to send and receive emails',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: versionHistory,
tools_count: 36,
triggers_count: 2,
diff --git a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
index b34711072..8f628e7c6 100644
--- a/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
@@ -4,7 +4,7 @@ import * as path from 'node:path';
import { HelpDoc, ValidationError } from '@effect/cli';
import { describe, expect, it, layer } from '@effect/vitest';
import { vi, beforeEach, afterEach } from 'vitest';
-import { Config, ConfigProvider, Effect, Option, Predicate } from 'effect';
+import { Config, ConfigProvider, DateTime, Effect, Option, Predicate } from 'effect';
import { extendConfigProvider } from 'src/services/config';
import { ComposioNoActiveConnectionError } from 'src/services/composio-error-overrides';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
@@ -675,8 +675,8 @@ describe('CLI: composio execute', () => {
meta: {
description: 'Email service',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20260115_00', '20260101_00'],
tools_count: 36,
triggers_count: 2,
@@ -745,8 +745,8 @@ describe('CLI: composio execute', () => {
meta: {
description: 'Email service',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20260316_00'],
tools_count: 36,
triggers_count: 2,
@@ -823,8 +823,8 @@ describe('CLI: composio execute', () => {
meta: {
description: 'Email service',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20260115_00', '20260101_00'],
tools_count: 36,
triggers_count: 2,
@@ -1706,8 +1706,8 @@ describe('CLI: composio execute', () => {
meta: {
description: 'Email service',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: ['20260316_00'],
tools_count: 36,
triggers_count: 2,
diff --git a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
index e7a3ab5d7..01381d53a 100644
--- a/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
+++ b/ts/packages/cli/test/src/services/consumer-short-term-cache.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, layer } from '@effect/vitest';
import { vi, beforeEach, afterEach } from 'vitest';
import { FileSystem } from '@effect/platform';
-import { ConfigProvider, Effect, Option } from 'effect';
+import { ConfigProvider, DateTime, Effect, Option } from 'effect';
import path from 'node:path';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { extendConfigProvider } from 'src/services/config';
@@ -83,8 +83,8 @@ describe('consumer short-term cache', () => {
meta: {
description: 'GitHub toolkit',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 0,
triggers_count: 0,
@@ -100,8 +100,8 @@ describe('consumer short-term cache', () => {
meta: {
description: 'No-auth toolkit',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 0,
triggers_count: 0,
@@ -147,8 +147,8 @@ describe('consumer short-term cache', () => {
meta: {
description: 'GitHub toolkit',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 0,
triggers_count: 0,
@@ -164,8 +164,8 @@ describe('consumer short-term cache', () => {
meta: {
description: 'No-auth toolkit',
categories: [],
- created_at: new Date('2024-05-03T11:44:32.061Z') as any,
- updated_at: new Date('2024-05-03T11:44:32.061Z') as any,
+ created_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
+ updated_at: DateTime.unsafeMake('2024-05-03T11:44:32.061Z'),
available_versions: [],
tools_count: 0,
triggers_count: 0,
diff --git a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
index 5fe818509..832d04614 100644
--- a/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
+++ b/ts/packages/cli/test/src/services/tool-file-uploads.test.ts
@@ -5,7 +5,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { FileSystem, Path } from '@effect/platform';
import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { Effect, Layer } from 'effect';
-import type { Composio as RawComposioClient } from '@composio/client';
+import { Composio as RawComposioClient } from '@composio/client';
import { ComposioSensitiveFilePathBlockedError } from '@composio/core';
import { schemaHasFileUploadable, uploadToolInputFiles } from 'src/services/tool-file-uploads';
@@ -19,7 +19,9 @@ const inputSchema = {
};
const makeClient = (createPresignedURL = vi.fn()) =>
- ({ files: { createPresignedURL } }) as unknown as RawComposioClient;
+ Object.assign(new RawComposioClient({ apiKey: 'test' }), {
+ files: { createPresignedURL },
+ });
describe('uploadToolInputFiles — sensitive-path guard (issue #3746)', () => {
afterEach(() => {
diff --git a/ts/packages/core/src/types/tool.types.ts b/ts/packages/core/src/types/tool.types.ts
index b48a55336..20fbe2d85 100644
--- a/ts/packages/core/src/types/tool.types.ts
+++ b/ts/packages/core/src/types/tool.types.ts
@@ -26,10 +26,55 @@ const JSONSchemaType = z.enum([
'array',
'null',
]);
+type JSONSchemaTypeName = z.infer<typeof JSONSchemaType>;
// JSON Schema property definition
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
+export interface JSONSchemaProperty {
+ [key: string]: unknown;
+ type?: JSONSchemaTypeName | JSONSchemaTypeName[];
+ description?: string;
+ anyOf?: JSONSchemaProperty[];
+ oneOf?: JSONSchemaProperty[];
+ allOf?: JSONSchemaProperty[];
+ not?: JSONSchemaProperty;
+ title?: string;
+ default?: unknown;
+ nullable?: boolean;
+ properties?: Record<string, JSONSchemaProperty>;
+ required?: string[];
+ file_uploadable?: boolean;
+ file_downloadable?: boolean;
+ items?: JSONSchemaProperty | JSONSchemaProperty[];
+ enum?: unknown[];
+ const?: unknown;
+ minimum?: number;
+ maximum?: number;
+ exclusiveMinimum?: number;
+ exclusiveMaximum?: number;
+ multipleOf?: number;
+ minLength?: number;
+ maxLength?: number;
+ pattern?: string;
+ format?: string;
+ minItems?: number;
+ maxItems?: number;
+ uniqueItems?: boolean;
+ minProperties?: number;
+ maxProperties?: number;
+ patternProperties?: Record<string, JSONSchemaProperty>;
+ additionalProperties?: boolean | JSONSchemaProperty;
+ examples?: unknown[];
+ readOnly?: boolean;
+ writeOnly?: boolean;
+ if?: JSONSchemaProperty;
+ then?: JSONSchemaProperty;
+ else?: JSONSchemaProperty;
+ $ref?: string;
+ definitions?: Record<string, JSONSchemaProperty>;
+ $defs?: Record<string, JSONSchemaProperty>;
+}
+
+export const JSONSchemaPropertySchema: z.ZodType<JSONSchemaProperty> = z.object({
type: z.union([JSONSchemaType, z.array(JSONSchemaType)]).optional(),
description: z.string().optional(),
anyOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
@@ -37,7 +82,7 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
allOf: z.lazy(() => z.array(JSONSchemaPropertySchema)).optional(),
not: z.lazy(() => JSONSchemaPropertySchema).optional(),
title: z.string().optional(),
- default: z.any().optional(),
+ default: z.unknown().optional(),
nullable: z.boolean().optional(),
properties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
required: z.array(z.string()).optional(),
@@ -46,8 +91,8 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
items: z
.lazy(() => z.union([JSONSchemaPropertySchema, z.array(JSONSchemaPropertySchema)]))
.optional(),
- enum: z.array(z.any()).optional(),
- const: z.any().optional(),
+ enum: z.array(z.unknown()).optional(),
+ const: z.unknown().optional(),
minimum: z.number().optional(),
maximum: z.number().optional(),
exclusiveMinimum: z.number().optional(),
@@ -64,7 +109,7 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
maxProperties: z.number().optional(),
patternProperties: z.lazy(() => z.record(z.string(), JSONSchemaPropertySchema)).optional(),
additionalProperties: z.union([z.boolean(), z.lazy(() => JSONSchemaPropertySchema)]).optional(),
- examples: z.array(z.any()).optional(),
+ examples: z.array(z.unknown()).optional(),
readOnly: z.boolean().optional(),
writeOnly: z.boolean().optional(),
if: z.lazy(() => JSONSchemaPropertySchema).optional(),
@@ -84,7 +129,6 @@ export const JSONSchemaPropertySchema: z.ZodType<any> = z.object({
)
.optional(),
});
-export type JSONSchemaProperty = z.infer<typeof JSONSchemaPropertySchema>;
// Schema for parameters (input/output)
const ParametersSchema = z.preprocess(
@@ -98,7 +142,7 @@ const ParametersSchema = z.preprocess(
properties: z.record(z.string(), JSONSchemaPropertySchema),
required: z.array(z.string()).optional(),
title: z.string().optional(),
- default: z.any().optional(),
+ default: z.unknown().optional(),
nullable: z.boolean().optional(),
description: z.string().optional(),
additionalProperties: z.boolean().default(false).optional(),
diff --git a/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts b/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
index 0f7e2f941..fb0e24386 100644
--- a/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
+++ b/ts/packages/core/src/utils/modifiers/FileToolModifier.node.ts
@@ -39,9 +39,9 @@ import { withCancellation } from '../cancellation';
* whose schema omits the `$defs` target working (see
* https://github.com/ComposioHQ/composio/issues/3307) instead of throwing.
*/
-const resolveFileSchema = (
- schema: JSONSchemaProperty | undefined
-): JSONSchemaProperty | undefined =>
+const resolveFileSchema = <Schema extends JSONSchemaProperty>(
+ schema: Schema | undefined
+): Schema | undefined =>
schema ? dereferenceJsonSchema(schema, { onUnresolved: 'sentinel' }) : schema;
const getSchemaVariants = (schema: JSONSchemaProperty | undefined): JSONSchemaProperty[] => [
diff --git a/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts b/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
index 8bf6925e6..595331de0 100644
--- a/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
+++ b/ts/packages/core/src/utils/modifiers/FileToolModifier.utils.neutral.ts
@@ -59,10 +59,12 @@ const transformSchema = (property: JSONSchemaProperty): JSONSchemaProperty => {
* @param properties - The properties of the tool schema.
* @returns The transformed properties.
*/
-export const transformProperties = (properties: JSONSchemaProperty): JSONSchemaProperty => {
- const newProperties: JSONSchemaProperty = {};
+export const transformProperties = (
+ properties: Record<string, JSONSchemaProperty>
+): Record<string, JSONSchemaProperty> => {
+ const newProperties: Record<string, JSONSchemaProperty> = {};
- for (const [key, property] of Object.entries(properties) as [string, JSONSchemaProperty][]) {
+ for (const [key, property] of Object.entries(properties)) {
newProperties[key] = transformSchema(property);
}
@@ -81,7 +83,7 @@ export const schemaHasFileProperty = (
// Check nested properties
if (schema.properties) {
- for (const prop of Object.values(schema.properties) as JSONSchemaProperty[]) {
+ for (const prop of Object.values(schema.properties)) {
if (schemaHasFileProperty(prop, property)) return true;
}
}
diff --git a/ts/packages/core/test/connectedAccounts/connectedAccountAuthStates.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccountAuthStates.test.ts
index 4b1e43632..8c40a6e6f 100644
--- a/ts/packages/core/test/connectedAccounts/connectedAccountAuthStates.test.ts
+++ b/ts/packages/core/test/connectedAccounts/connectedAccountAuthStates.test.ts
@@ -95,8 +95,7 @@ describe('connectedAccountAuthStates — REVOKED arms', () => {
revoked_at: '2026-05-01T00:00:00Z',
},
},
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any);
+ } as unknown as Parameters<typeof transformConnectedAccountResponse>[0]);
expect(transformed.status).toBe(ConnectionStatuses.REVOKED);
expect(transformed.state).toBeDefined();
@@ -116,8 +115,7 @@ describe('connectedAccountAuthStates — REVOKED arms', () => {
revoked_at: '2026-05-01T00:00:00Z',
},
},
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- } as any);
+ } as unknown as Parameters<typeof transformConnectedAccountResponse>[0]);
expect(transformed.state).toBeDefined();
expect(transformed.state?.authScheme).toBe(AuthSchemeTypes.S2S_OAUTH2);
diff --git a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
index 48ccbf660..f7e9d72e2 100644
--- a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
+++ b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts
@@ -861,7 +861,7 @@ describe('ConnectedAccounts', () => {
const nanoid = 'conn_123';
const invalidOptions = { redirectUrl: 123 };
- await expect(connectedAccounts.refresh(nanoid, invalidOptions as any)).rejects.toThrow(
+ await expect(connectedAccounts.refresh(nanoid, invalidOptions as unknown)).rejects.toThrow(
'Failed to parse connected account refresh options'
);
@@ -1171,7 +1171,7 @@ describe('ConnectedAccounts', () => {
it('should throw ValidationError for invalid params', async () => {
await expect(
- connectedAccounts.update('conn_abc123', { enabled: 'yes' } as any)
+ connectedAccounts.update('conn_abc123', { enabled: 'yes' } as unknown)
).rejects.toThrow('Failed to parse connected account update params');
});
});
@@ -1265,7 +1265,7 @@ describe('ConnectedAccounts', () => {
};
await expect(
- connectedAccounts.link(userId, authConfigId, invalidOptions as any)
+ connectedAccounts.link(userId, authConfigId, invalidOptions as unknown)
).rejects.toThrow('Failed to parse create connected account link options');
// Ensure API was not called with invalid options
diff --git a/ts/packages/core/test/core/session.test.ts b/ts/packages/core/test/core/session.test.ts
index 663fda647..d50f55b9e 100644
--- a/ts/packages/core/test/core/session.test.ts
+++ b/ts/packages/core/test/core/session.test.ts
@@ -112,7 +112,7 @@ describe('Composio Session Management', () => {
it('should expose sessions.create and keep composio.create as a bound alias', async () => {
const composio = new Composio(baseConfig);
- const client = composio.getClient() as any;
+ const client = composio.getClient() as unknown;
client.toolRouter.session.create = vi.fn().mockResolvedValue({
session_id: 'session_123',
mcp: {
@@ -185,7 +185,7 @@ describe('Session Headers Generation', () => {
it('should use fallback source when provider name is undefined', () => {
const mockProvider = {
name: undefined,
- } as any;
+ } as unknown;
const headers = getSessionHeaders(mockProvider);
expect(headers).toEqual({
diff --git a/ts/packages/core/test/core/versions.test.ts b/ts/packages/core/test/core/versions.test.ts
index 75c53e11b..b7a77bd93 100644
--- a/ts/packages/core/test/core/versions.test.ts
+++ b/ts/packages/core/test/core/versions.test.ts
@@ -98,7 +98,7 @@ describe('Version Management', () => {
});
it('should return the string version as-is when user provides specific version', () => {
- const result = getToolkitVersionsFromEnv('20250902_00' as any);
+ const result = getToolkitVersionsFromEnv('20250902_00' as unknown);
expect(result).toBe('20250902_00');
});
@@ -106,7 +106,7 @@ describe('Version Management', () => {
process.env.COMPOSIO_TOOLKIT_VERSION_GITHUB = '20250901_01';
process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
- const result = getToolkitVersionsFromEnv('20250902_00' as any);
+ const result = getToolkitVersionsFromEnv('20250902_00' as unknown);
expect(result).toBe('20250902_00');
});
});
@@ -304,7 +304,7 @@ describe('Version Management', () => {
});
it('should return "latest" when toolkitVersions is null', () => {
- const result = getToolkitVersion('github', null as any);
+ const result = getToolkitVersion('github', null as unknown);
expect(result).toBe('latest');
});
});
@@ -336,7 +336,7 @@ describe('Version Management', () => {
const toolkitVersions = {
github: '20250902_00',
slack: 'latest',
- } as any;
+ } as unknown;
expect(getToolkitVersion('github', toolkitVersions)).toBe('20250902_00');
expect(getToolkitVersion('slack', toolkitVersions)).toBe('latest');
@@ -373,7 +373,7 @@ describe('Version Management', () => {
process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
// User provides global version
- const toolkitVersions = getToolkitVersionsFromEnv('20250902_00' as any);
+ const toolkitVersions = getToolkitVersionsFromEnv('20250902_00' as unknown);
// All toolkits should get the global version
expect(getToolkitVersion('github', toolkitVersions)).toBe('20250902_00');
diff --git a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
index 7d555f004..9ac6c2a3f 100644
--- a/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
+++ b/ts/packages/core/test/models/ToolRouterSessionFilesMount.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import ComposioClient from '@composio/client';
import { ToolRouterSessionFilesMount } from '../../src/models/ToolRouterSessionFileMount';
import { ComposioBlockedInternalUrlError, ValidationError } from '../../src/errors';
import { DEFAULT_TOOL_ROUTER_SESSION_FILES_MOUNT_ID } from '../../src/utils/constants';
@@ -14,18 +15,18 @@ const mockLookup = vi.mocked(lookup);
const sessionId = 'trs_session_123';
-const createMockClient = () => ({
- toolRouter: {
- session: {
- files: {
- list: vi.fn(),
- createUploadURL: vi.fn(),
- createDownloadURL: vi.fn(),
- delete: vi.fn(),
- },
- },
- },
-});
+const createMockClient = () => {
+ const client = new ComposioClient({ apiKey: 'test-api-key' });
+ const files = Object.assign(client.toolRouter.session.files, {
+ list: vi.fn<typeof client.toolRouter.session.files.list>(),
+ createUploadURL: vi.fn<typeof client.toolRouter.session.files.createUploadURL>(),
+ createDownloadURL: vi.fn<typeof client.toolRouter.session.files.createDownloadURL>(),
+ delete: vi.fn<typeof client.toolRouter.session.files.delete>(),
+ });
+ const session = Object.assign(client.toolRouter.session, { files });
+ const toolRouter = Object.assign(client.toolRouter, { session });
+ return Object.assign(client, { toolRouter });
+};
describe('ToolRouterSessionFilesMount', () => {
let mockClient: ReturnType<typeof createMockClient>;
@@ -35,7 +36,7 @@ describe('ToolRouterSessionFilesMount', () => {
vi.clearAllMocks();
mockLookup.mockReset();
mockClient = createMockClient();
- filesMount = new ToolRouterSessionFilesMount(mockClient as any, sessionId);
+ filesMount = new ToolRouterSessionFilesMount(mockClient, sessionId);
});
describe('list', () => {
diff --git a/ts/packages/core/test/models/customTool.test.ts b/ts/packages/core/test/models/customTool.test.ts
index 0ba670bfa..464802038 100644
--- a/ts/packages/core/test/models/customTool.test.ts
+++ b/ts/packages/core/test/models/customTool.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import ComposioClient from '@composio/client';
import { z as z4 } from 'zod';
import { z } from 'zod/v3';
import {
@@ -227,20 +228,20 @@ describe('createCustomTool', () => {
});
it('should throw if inputParams is missing', () => {
- expect(() => createCustomTool('SLUG', { ...baseOptions, inputParams: null as any })).toThrow(
- 'inputParams is required'
- );
+ expect(() =>
+ createCustomTool('SLUG', { ...baseOptions, inputParams: null as unknown })
+ ).toThrow('inputParams is required');
});
it('should throw if execute is not a function', () => {
- expect(() => createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as any })).toThrow(
- 'execute must be a function'
- );
+ expect(() =>
+ createCustomTool('SLUG', { ...baseOptions, execute: 'not-fn' as unknown })
+ ).toThrow('execute must be a function');
});
it('should throw if a Zod v4 input schema is not an object', () => {
expect(() =>
- createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as any })
+ createCustomTool('SLUG', { ...baseOptions, inputParams: z4.string() as unknown })
).toThrow('inputParams must be a z.object() schema');
});
});
@@ -254,7 +255,7 @@ describe('createCustomTool', () => {
execute: noSessionExecute,
});
- const result = await tool.execute({ category: 'test' } as any);
+ const result = await tool.execute({ category: 'test' } as unknown);
expect(result.result).toBe(42);
expect(noSessionExecute).toHaveBeenCalledWith({ category: 'test' });
});
@@ -612,21 +613,20 @@ describe('serializeCustomToolkits', () => {
// ────────────────────────────────────────────────────────────────
describe('SessionContextImpl', () => {
- const mockClient = {
- toolRouter: {
- session: {
- execute: vi.fn(),
- proxyExecute: vi.fn(),
- },
- },
- };
+ const client = new ComposioClient({ apiKey: 'test-api-key' });
+ const session = Object.assign(client.toolRouter.session, {
+ execute: vi.fn<typeof client.toolRouter.session.execute>(),
+ proxyExecute: vi.fn<typeof client.toolRouter.session.proxyExecute>(),
+ });
+ const toolRouter = Object.assign(client.toolRouter, { session });
+ const mockClient = Object.assign(client, { toolRouter });
beforeEach(() => {
vi.clearAllMocks();
});
it('should expose userId', () => {
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
expect(ctx.userId).toBe('user_1');
});
@@ -637,7 +637,7 @@ describe('SessionContextImpl', () => {
log_id: 'log_1',
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
const result = await ctx.execute('GMAIL_SEND_EMAIL', { to: '[email protected]' });
expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
@@ -662,7 +662,7 @@ describe('SessionContextImpl', () => {
log_id: 'log_1',
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', undefined, {
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', undefined, {
custom_tools: [
{
slug: 'GREP',
@@ -694,7 +694,7 @@ describe('SessionContextImpl', () => {
log_id: 'log_2',
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
const result = await ctx.execute('BAD_TOOL', {});
expect(result.logId).toBe('log_2');
@@ -706,7 +706,7 @@ describe('SessionContextImpl', () => {
status: 200,
data: { proxy_result: true },
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
const result = await ctx.proxyExecute({
toolkit: 'github',
@@ -732,9 +732,9 @@ describe('SessionContextImpl', () => {
});
it('should throw on proxyExecute() with invalid params', async () => {
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
await expect(
- ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as any })
+ ctx.proxyExecute({ toolkit: 'github', endpoint: '/test', method: 'INVALID' as unknown })
).rejects.toThrow('Invalid proxy execute parameters');
});
@@ -750,7 +750,7 @@ describe('SessionContextImpl', () => {
}),
]);
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
const result = await ctx.execute('SIBLING_TOOL', { key: 'val' });
expect(siblingExecute).toHaveBeenCalledWith({ key: 'val' }, ctx);
@@ -774,7 +774,7 @@ describe('SessionContextImpl', () => {
log_id: 'log_3',
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1', customToolsMap);
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1', customToolsMap);
const result = await ctx.execute('REMOTE_TOOL', { key: 'val' });
expect(mockClient.toolRouter.session.execute).toHaveBeenCalledWith(
@@ -795,7 +795,7 @@ describe('SessionContextImpl', () => {
log_id: 'log_4',
});
- const ctx = new SessionContextImpl(mockClient as any, 'user_1', 'sess_1');
+ const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
const result = await ctx.execute('ANY_TOOL', {});
expect(mockClient.toolRouter.session.execute).toHaveBeenCalled();
diff --git a/ts/packages/core/test/models/customToolRouting.test.ts b/ts/packages/core/test/models/customToolRouting.test.ts
index ad1ad09b2..5471e172b 100644
--- a/ts/packages/core/test/models/customToolRouting.test.ts
+++ b/ts/packages/core/test/models/customToolRouting.test.ts
@@ -5,8 +5,45 @@ import { ToolRouterSession } from '../../src/models/ToolRouterSession';
import { createCustomTool, buildCustomToolsMap } from '../../src/models/CustomTool';
import { MockProvider } from '../utils/mocks/provider.mock';
import ComposioClient from '@composio/client';
-import { Tools } from '../../src/models/Tools';
-import type { CustomTool } from '../../src/types/customTool.types';
+import type { CustomTool, SessionContext } from '../../src/types/customTool.types';
+import type { ComposioConfig } from '../../src/composio';
+
+type MultiExecuteResultItem = {
+ tool_slug: string;
+ index?: number;
+ response: {
+ successful: boolean;
+ data?: unknown;
+ error?: string;
+ };
+ error?: string;
+};
+
+// Single-tool passthrough responses do not use the results array.
+type MultiExecuteResponse = {
+ data: {
+ results: MultiExecuteResultItem[];
+ total_count?: number;
+ success_count?: number;
+ error_count?: number;
+ [key: string]: unknown;
+ };
+ error: string | null;
+ successful: boolean;
+};
+
+type CapturedExecuteFn = (
+ toolSlug: string,
+ input: Record<string, unknown>
+) => Promise<MultiExecuteResponse>;
+
+type MockedToolsInstance = {
+ executeSessionTool: ReturnType<typeof vi.fn>;
+};
+
+const toolsMockState = vi.hoisted(() => ({
+ latestInstance: undefined as MockedToolsInstance | undefined,
+}));
// Mock telemetry
vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -16,7 +53,7 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
// Mock Tools class
vi.mock('../../src/models/Tools', () => ({
Tools: vi.fn().mockImplementation(function () {
- return {
+ const instance = {
getRawToolRouterSessionTools: vi.fn().mockResolvedValue([
{ slug: 'COMPOSIO_SEARCH_TOOLS', name: 'Search Tools' },
{ slug: 'COMPOSIO_MULTI_EXECUTE_TOOL', name: 'Multi Execute' },
@@ -28,9 +65,24 @@ vi.mock('../../src/models/Tools', () => ({
successful: true,
}),
};
+
+ toolsMockState.latestInstance = instance;
+ return instance;
}),
}));
+const getLatestToolsInstance = (): MockedToolsInstance => {
+ const instance = toolsMockState.latestInstance;
+ if (!instance) {
+ throw new Error('Expected the Tools mock to have been instantiated');
+ }
+ return instance;
+};
+
+beforeEach(() => {
+ toolsMockState.latestInstance = undefined;
+});
+
// ── Fixtures ─────────────────────────────────────────────────────
const createMockClient = () => ({
@@ -83,7 +135,7 @@ const customToolHandle = createCustomTool('GET_USER_CONTEXT', {
execute: localExecute,
});
-const sessionExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => ({
+const sessionExecute = vi.fn().mockImplementation(async (input: unknown, ctx: SessionContext) => ({
userId: ctx.userId,
}));
@@ -114,11 +166,12 @@ const createSessionWithProvider = (
};
const captureExecuteFn = (provider: MockProvider) => {
- provider.wrapTools.mockImplementation((tools: any, executeFn: any) => {
- (provider as any)._capturedExecuteFn = executeFn;
- (provider as any)._capturedTools = tools;
+ let executeFn: CapturedExecuteFn;
+ provider.wrapTools.mockImplementation((_tools: unknown, capturedExecuteFn: unknown) => {
+ executeFn = capturedExecuteFn as CapturedExecuteFn;
return 'wrapped-tools-with-routing';
});
+ return () => executeFn;
};
// ────────────────────────────────────────────────────────────────
@@ -373,10 +426,12 @@ describe('ToolRouterSession execution routing', () => {
});
it('should provide a working execute() on SessionContext for remote tools', async () => {
- const chainedExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
- const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
- return { inner_result: inner.data };
- });
+ const chainedExecute = vi
+ .fn()
+ .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => {
+ const inner = await ctx.execute('GMAIL_SEND_EMAIL', { to: input.to });
+ return { inner_result: inner.data };
+ });
const chainedTool = createCustomTool('CHAINED_TOOL', {
name: 'Chained',
@@ -407,10 +462,12 @@ describe('ToolRouterSession execution routing', () => {
execute: siblingExecute,
});
- const toolAExecute = vi.fn().mockImplementation(async (input: any, ctx: any) => {
- const inner = await ctx.execute('TOOL_B', { key: input.value });
- return { fromA: true, fromB: inner.data };
- });
+ const toolAExecute = vi
+ .fn()
+ .mockImplementation(async (input: Record<string, unknown>, ctx: SessionContext) => {
+ const inner = await ctx.execute('TOOL_B', { key: input.value });
+ return { fromA: true, fromB: inner.data };
+ });
const toolA = createCustomTool('TOOL_A', {
name: 'Tool A',
description: 'Calls sibling tool B',
@@ -452,7 +509,7 @@ describe('ToolRouterSession execution routing', () => {
});
it('should apply Zod defaults when input is missing optional fields', async () => {
- const defaultExecute = vi.fn().mockImplementation(async (input: any) => ({
+ const defaultExecute = vi.fn().mockImplementation(async (input: Record<string, unknown>) => ({
category: input.category,
}));
@@ -505,11 +562,11 @@ describe('ToolRouterSession execution routing', () => {
describe('session.tools() — COMPOSIO_MULTI_EXECUTE_TOOL routing with tools[] array', () => {
it('should route all-local tools[] to in-process execution', async () => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
+ const executeFn = getExecuteFn();
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [{ tool_slug: 'LOCAL_GET_USER_CONTEXT', arguments: { category: 'test' } }],
@@ -525,11 +582,11 @@ describe('ToolRouterSession execution routing', () => {
it('should route local tool by non-prefixed slug in multi-execute', async () => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
+ const executeFn = getExecuteFn();
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [{ tool_slug: 'GET_USER_CONTEXT', arguments: { category: 'no-prefix' } }],
@@ -545,11 +602,11 @@ describe('ToolRouterSession execution routing', () => {
it('should route all-remote tools[] to backend', async () => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
+ const executeFn = getExecuteFn();
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [{ tool_slug: 'GMAIL_SEND_EMAIL', arguments: { to: '[email protected]' } }],
@@ -562,11 +619,11 @@ describe('ToolRouterSession execution routing', () => {
it('should route non-MULTI_EXECUTE session tools to backend', async () => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
+ const executeFn = getExecuteFn();
const result = await executeFn('COMPOSIO_SEARCH_TOOLS', {
queries: [{ use_case: 'send email' }],
@@ -595,16 +652,17 @@ describe('ToolRouterSession execution routing', () => {
customTools: CustomTool[]
) => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(client, provider, customTools);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
- const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
- .value;
+ const executeFn = getExecuteFn();
+ const toolsInstance = getLatestToolsInstance();
return { executeFn, toolsInstance, provider, session };
};
- const backendResponse = (results: Array<{ tool_slug: string; data: any; error?: string }>) => {
+ const backendResponse = (
+ results: Array<{ tool_slug: string; data: unknown; error?: string }>
+ ) => {
const items = results.map((r, i) => ({
response: {
successful: !r.error,
@@ -628,8 +686,8 @@ describe('ToolRouterSession execution routing', () => {
};
};
- const findResult = (results: any[], slug: string) =>
- results.find((r: any) => r.tool_slug === slug);
+ const findResult = (results: MultiExecuteResultItem[], slug: string) =>
+ results.find(r => r.tool_slug === slug);
it('should append local results to remote results array', async () => {
const { executeFn, toolsInstance } = await setupMultiExecute(mockClient, [customToolHandle]);
@@ -649,8 +707,8 @@ describe('ToolRouterSession execution routing', () => {
const { results } = result.data;
expect(results).toHaveLength(2);
- const remote = findResult(results, 'GMAIL_SEND_EMAIL');
- const local = findResult(results, 'LOCAL_GET_USER_CONTEXT');
+ const remote = findResult(results, 'GMAIL_SEND_EMAIL')!;
+ const local = findResult(results, 'LOCAL_GET_USER_CONTEXT')!;
expect(remote.response.data).toEqual({ sent: true });
expect(local.response.data).toEqual({ local_result: true });
expect(local.response.successful).toBe(true);
@@ -714,7 +772,7 @@ describe('ToolRouterSession execution routing', () => {
expect(findResult(results, 'LOCAL_META_ADS_GET_AD_ACCOUNTS')).toBeDefined();
expect(findResult(results, 'GMAIL_SEND_EMAIL')).toBeDefined();
expect(findResult(results, 'SLACK_POST_MESSAGE')).toBeDefined();
- expect(results.map((entry: any) => entry.tool_slug)).toEqual([
+ expect(results.map(entry => entry.tool_slug)).toEqual([
'LOCAL_GET_USER_CONTEXT',
'GMAIL_SEND_EMAIL',
'LOCAL_META_ADS_GET_AD_ACCOUNTS',
@@ -723,7 +781,7 @@ describe('ToolRouterSession execution routing', () => {
const backendTools = toolsInstance.executeSessionTool.mock.calls[0][1].arguments.tools;
expect(backendTools).toHaveLength(2);
- expect(backendTools.map((t: any) => t.tool_slug)).toEqual([
+ expect(backendTools.map((t: { tool_slug: string }) => t.tool_slug)).toEqual([
'GMAIL_SEND_EMAIL',
'SLACK_POST_MESSAGE',
]);
@@ -838,15 +896,15 @@ describe('ToolRouterSession execution routing', () => {
const { results } = result.data;
expect(results).toHaveLength(4);
- const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT');
+ const localOk = findResult(results, 'LOCAL_GET_USER_CONTEXT')!;
expect(localOk.response.successful).toBe(true);
- const localErr = findResult(results, 'LOCAL_MIXED_THROWER');
+ const localErr = findResult(results, 'LOCAL_MIXED_THROWER')!;
expect(localErr.response.successful).toBe(false);
expect(localErr.response.error).toBe('batch-boom');
expect(localErr.error).toBe('batch-boom');
- const remoteErr = findResult(results, 'SLACK_POST_MESSAGE');
+ const remoteErr = findResult(results, 'SLACK_POST_MESSAGE')!;
expect(remoteErr.response.error).toBe('auth failed');
expect(result.successful).toBe(false);
@@ -931,12 +989,11 @@ describe('ToolRouterSession execution routing', () => {
});
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [slowLocalHandle]);
await session.tools();
- const executeFn = (provider as any)._capturedExecuteFn;
- const toolsInstance = (Tools as any).mock.results[(Tools as any).mock.results.length - 1]
- .value;
+ const executeFn = getExecuteFn();
+ const toolsInstance = getLatestToolsInstance();
toolsInstance.executeSessionTool.mockImplementation(async () => {
callOrder.push('remote-start');
@@ -985,14 +1042,12 @@ describe('ToolRouterSession execution routing', () => {
describe('per-tool results — each tool gets its own entry in results[]', () => {
it('should return per-tool results for mixed local+remote batch', async () => {
const provider = new MockProvider();
- captureExecuteFn(provider);
+ const getExecuteFn = captureExecuteFn(provider);
const session = createSessionWithProvider(mockClient, provider, [customToolHandle]);
await session.tools();
- const latestToolsInstance = (Tools as any).mock.results[
- (Tools as any).mock.results.length - 1
- ].value;
+ const latestToolsInstance = getLatestToolsInstance();
latestToolsInstance.executeSessionTool.mockResolvedValueOnce({
data: {
results: [
@@ -1015,7 +1070,7 @@ describe('ToolRouterSession execution routing', () => {
successful: true,
});
- const executeFn = (provider as any)._capturedExecuteFn;
+ const executeFn = getExecuteFn();
const result = await executeFn('COMPOSIO_MULTI_EXECUTE_TOOL', {
tools: [
@@ -1029,9 +1084,9 @@ describe('ToolRouterSession execution routing', () => {
const { results } = result.data;
expect(results).toHaveLength(3);
- const local = results.find((r: any) => r.tool_slug === 'LOCAL_GET_USER_CONTEXT');
- const gmail = results.find((r: any) => r.tool_slug === 'GMAIL_SEND_EMAIL');
- const slack = results.find((r: any) => r.tool_slug === 'SLACK_POST_MESSAGE');
+ const local = results.find(r => r.tool_slug === 'LOCAL_GET_USER_CONTEXT')!;
+ const gmail = results.find(r => r.tool_slug === 'GMAIL_SEND_EMAIL')!;
+ const slack = results.find(r => r.tool_slug === 'SLACK_POST_MESSAGE')!;
expect(local.response.data).toEqual({ local_result: true });
expect(gmail.response.data).toEqual({ message_id: 'msg_1' });
@@ -1045,7 +1100,7 @@ describe('ToolRouterSession execution routing', () => {
const session = new ToolRouterSession(
mockClient as unknown as ComposioClient,
- { apiKey: 'key' } as any,
+ { apiKey: 'key' } as unknown as ComposioConfig<MockProvider>,
'sess_123',
{ type: 'http' as const, url: 'https://mcp.example.com/sess_123' },
undefined,
diff --git a/ts/packages/core/test/models/mcp.test.ts b/ts/packages/core/test/models/mcp.test.ts
index eae5cc435..e98c71092 100644
--- a/ts/packages/core/test/models/mcp.test.ts
+++ b/ts/packages/core/test/models/mcp.test.ts
@@ -120,7 +120,9 @@ describe('MCP', () => {
});
it('should validate configuration', async () => {
- await expect(mcp.create('test', { toolkits: null as any })).rejects.toThrow(ValidationError);
+ await expect(mcp.create('test', { toolkits: null as unknown })).rejects.toThrow(
+ ValidationError
+ );
});
});
@@ -198,7 +200,7 @@ describe('MCP', () => {
});
it('should handle validation errors', async () => {
- await expect(mcp.list({ page: 'invalid' as any })).rejects.toThrow(ValidationError);
+ await expect(mcp.list({ page: 'invalid' as unknown })).rejects.toThrow(ValidationError);
});
});
@@ -287,7 +289,7 @@ describe('MCP', () => {
});
it('should validate update parameters', async () => {
- await expect(mcp.update('mcp_123', { toolkits: 'invalid' as any })).rejects.toThrow(
+ await expect(mcp.update('mcp_123', { toolkits: 'invalid' as unknown })).rejects.toThrow(
ValidationError
);
});
@@ -369,7 +371,7 @@ describe('MCP', () => {
mockClient.mcp.retrieve.mockResolvedValueOnce(mockRetrieveResponse);
await expect(
- mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as any })
+ mcp.generate('user123', 'mcp_123', { manuallyManageConnections: 'invalid' as unknown })
).rejects.toThrow(ValidationError);
});
});
diff --git a/ts/packages/core/test/models/toolRouter.test.ts b/ts/packages/core/test/models/toolRouter.test.ts
index 1725a05f5..290fd8737 100644
--- a/ts/packages/core/test/models/toolRouter.test.ts
+++ b/ts/packages/core/test/models/toolRouter.test.ts
@@ -1814,7 +1814,7 @@ describe('ToolRouter', () => {
it('should throw error for invalid configuration', async () => {
const invalidConfig = {
toolkits: 'invalid-toolkits', // Should be array or object
- } as any;
+ } as unknown;
await expect(toolRouter.create(userId, invalidConfig)).rejects.toThrow();
});
@@ -2673,7 +2673,7 @@ describe('ToolRouter', () => {
beforeEach(() => {
// Reset the Tools mock before each test
vi.clearAllMocks();
- (Tools as any).mockImplementation(function () {
+ vi.mocked(Tools).mockImplementation(function () {
return {
getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
getRawToolRouterSessionTools: vi
@@ -2695,7 +2695,7 @@ describe('ToolRouter', () => {
apiKey: 'test-api-key',
});
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
undefined,
@@ -2724,7 +2724,7 @@ describe('ToolRouter', () => {
const session = await toolRouter.create(userId);
const tools = await session.tools(modifiers);
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
{ modifySchema: modifiers.modifySchema },
@@ -2747,7 +2747,7 @@ describe('ToolRouter', () => {
},
});
- (Tools as any).mockImplementation(function () {
+ vi.mocked(Tools).mockImplementation(function () {
return {
getRawComposioTools: vi.fn().mockResolvedValue([{ slug: 'GMAIL_FETCH_EMAILS' }]),
getRawToolRouterSessionTools: vi
@@ -2766,7 +2766,7 @@ describe('ToolRouter', () => {
});
const tools = await session.tools();
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.wrapToolsForToolRouter).toHaveBeenCalledWith(
sessionId,
[
@@ -2849,7 +2849,7 @@ describe('ToolRouter', () => {
error: null,
successful: true,
});
- (Tools as any).mockImplementation(function () {
+ vi.mocked(Tools).mockImplementation(function () {
return {
getRawToolRouterSessionTools: vi
.fn()
@@ -2910,7 +2910,7 @@ describe('ToolRouter', () => {
successful: true,
});
const multiExecuteTool = { slug: 'COMPOSIO_MULTI_EXECUTE_TOOL' };
- (Tools as any).mockImplementation(function () {
+ vi.mocked(Tools).mockImplementation(function () {
return {
getRawToolRouterSessionTools: vi
.fn()
@@ -3028,7 +3028,7 @@ describe('ToolRouter', () => {
it('should handle tools fetching errors', async () => {
mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
- (Tools as any).mockImplementation(function () {
+ vi.mocked(Tools).mockImplementation(function () {
return {
getRawComposioTools: vi.fn().mockRejectedValue(new Error('Failed to fetch tools')),
getRawToolRouterSessionTools: vi
@@ -3058,7 +3058,7 @@ describe('ToolRouter', () => {
expect(Tools).toHaveBeenCalledTimes(2);
- const firstToolsInstance = (Tools as any).mock.results[0].value;
+ const firstToolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(firstToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
{ modifySchema: modifier1.modifySchema },
@@ -3070,7 +3070,7 @@ describe('ToolRouter', () => {
modifier1
);
- const secondToolsInstance = (Tools as any).mock.results[1].value;
+ const secondToolsInstance = vi.mocked(Tools).mock.results[1].value;
expect(secondToolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
{ modifySchema: modifier2.modifySchema },
@@ -3099,7 +3099,7 @@ describe('ToolRouter', () => {
provider: mockProvider,
apiKey: 'test-api-key',
});
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
'custom_session_123',
undefined,
@@ -3128,7 +3128,7 @@ describe('ToolRouter', () => {
provider: mockProvider,
apiKey: 'test-api-key',
});
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
'empty_session_123',
undefined,
@@ -3381,7 +3381,7 @@ describe('ToolRouter', () => {
expect(tools).toBe('mocked-wrapped-tools');
expect(Tools).toHaveBeenCalled();
- const toolsInstance = (Tools as any).mock.results[0].value;
+ const toolsInstance = vi.mocked(Tools).mock.results[0].value;
expect(toolsInstance.getRawToolRouterSessionTools).toHaveBeenCalledWith(
sessionId,
undefined,
diff --git a/ts/packages/core/test/models/toolkits.test.ts b/ts/packages/core/test/models/toolkits.test.ts
index 2657d3f3c..772333bfe 100644
--- a/ts/packages/core/test/models/toolkits.test.ts
+++ b/ts/packages/core/test/models/toolkits.test.ts
@@ -5,6 +5,7 @@ import { telemetry } from '../../src/telemetry/Telemetry';
import { ComposioAuthConfigNotFoundError } from '../../src/errors/AuthConfigErrors';
import { AuthSchemeTypes } from '../../src/types/authConfigs.types';
import { APIError } from '@composio/client';
+import type { ToolkitListParams } from '../../src/types/toolkit.types';
// Mock dependencies
vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -13,6 +14,12 @@ vi.mock('../../src/telemetry/Telemetry', () => ({
},
}));
+// Minimal structural shape for overriding `Toolkits.prototype.getToolkitBySlug`
+// (a protected method) with a mock implementation in tests.
+type ToolkitsPrototypeOverride = {
+ getToolkitBySlug: unknown;
+};
+
// Create mock client with toolkit-related methods
const createMockClient = () => ({
baseURL: 'https://api.composio.dev',
@@ -222,7 +229,7 @@ describe('Toolkits', () => {
});
it('should throw ValidationError for invalid list query', async () => {
- const promise = toolkits.get({ category: 123 } as any);
+ const promise = toolkits.get({ category: 123 } as unknown as ToolkitListParams);
await expect(promise).rejects.toThrowError('Failed to fetch toolkits');
});
@@ -552,7 +559,9 @@ describe('Toolkits', () => {
};
beforeEach(() => {
- vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
+ vi.spyOn(Toolkits.prototype as unknown, 'getToolkitBySlug').mockResolvedValue(
+ mockToolkit as unknown
+ );
});
it('returns all fields when requiredOnly is false', async () => {
@@ -617,7 +626,9 @@ describe('Toolkits', () => {
},
],
};
- (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
+ (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
+ .fn()
+ .mockResolvedValueOnce(multiToolkit);
const result = await toolkits.getAuthConfigCreationFields(
toolkitSlug,
AuthSchemeTypes.API_KEY,
@@ -629,7 +640,9 @@ describe('Toolkits', () => {
});
it('throws if no authConfigDetails', async () => {
- (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
+ (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
+ .fn()
+ .mockResolvedValueOnce({});
await expect(
toolkits.getAuthConfigCreationFields(toolkitSlug, AuthSchemeTypes.API_KEY, {
requiredOnly: true,
@@ -660,7 +673,9 @@ describe('Toolkits', () => {
};
beforeEach(() => {
- vi.spyOn(Toolkits.prototype as any, 'getToolkitBySlug').mockResolvedValue(mockToolkit as any);
+ vi.spyOn(Toolkits.prototype as unknown, 'getToolkitBySlug').mockResolvedValue(
+ mockToolkit as unknown
+ );
});
it('returns all fields when requiredOnly is false', async () => {
@@ -713,7 +728,9 @@ describe('Toolkits', () => {
},
],
};
- (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce(multiToolkit);
+ (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
+ .fn()
+ .mockResolvedValueOnce(multiToolkit);
const result = await toolkits.getConnectedAccountInitiationFields(
toolkitSlug,
AuthSchemeTypes.API_KEY,
@@ -725,7 +742,9 @@ describe('Toolkits', () => {
});
it('throws if no authConfigDetails', async () => {
- (Toolkits.prototype as any).getToolkitBySlug = vi.fn().mockResolvedValueOnce({});
+ (Toolkits.prototype as unknown as ToolkitsPrototypeOverride).getToolkitBySlug = vi
+ .fn()
+ .mockResolvedValueOnce({});
await expect(
toolkits.getConnectedAccountInitiationFields(toolkitSlug, AuthSchemeTypes.API_KEY, {
requiredOnly: true,
diff --git a/ts/packages/core/test/models/triggers.test.ts b/ts/packages/core/test/models/triggers.test.ts
index 1747653e4..0fc81664d 100644
--- a/ts/packages/core/test/models/triggers.test.ts
+++ b/ts/packages/core/test/models/triggers.test.ts
@@ -205,7 +205,7 @@ const mockIncomingTriggerPayload: IncomingTriggerPayload = {
};
describe('Triggers', () => {
- let triggers: Triggers<any>;
+ let triggers: Triggers<unknown>;
let mockClient: ReturnType<typeof createMockClient>;
let mockPusherService: {
subscribe: Mock;
@@ -547,7 +547,7 @@ describe('Triggers', () => {
triggerConfig: null,
};
- await expect(triggers.create(userId, slug, invalidBody as any)).rejects.toThrow(
+ await expect(triggers.create(userId, slug, invalidBody as unknown)).rejects.toThrow(
ValidationError
);
expect(mockClient.triggerInstances.upsert).not.toHaveBeenCalled();
@@ -753,7 +753,7 @@ describe('Triggers', () => {
});
it('should throw error if function is not provided', async () => {
- await expect(triggers.subscribe(null as any)).rejects.toThrow(
+ await expect(triggers.subscribe(null as unknown)).rejects.toThrow(
'Function is required for trigger subscription'
);
});
diff --git a/ts/packages/core/test/models/verifyWebhook.integration.test.ts b/ts/packages/core/test/models/verifyWebhook.integration.test.ts
index a6135abec..14253568b 100644
--- a/ts/packages/core/test/models/verifyWebhook.integration.test.ts
+++ b/ts/packages/core/test/models/verifyWebhook.integration.test.ts
@@ -112,7 +112,7 @@ function computeSignature(id: string, timestamp: string, payload: string, secret
}
describe('Triggers.verifyWebhook - Integration Tests', () => {
- let triggers: Triggers<any>;
+ let triggers: Triggers<unknown>;
let mockClient: ReturnType<typeof createMockClient>;
const fixtures = loadFixtures();
const goldenSignatures = loadGoldenSignatures();
diff --git a/ts/packages/core/test/models/verifyWebhook.test.ts b/ts/packages/core/test/models/verifyWebhook.test.ts
index b401c39c2..863282e8d 100644
--- a/ts/packages/core/test/models/verifyWebhook.test.ts
+++ b/ts/packages/core/test/models/verifyWebhook.test.ts
@@ -7,12 +7,21 @@ import {
WebhookPayloadV2,
WebhookPayloadV3,
WebhookVersions,
+ VerifyWebhookParams,
} from '../../src/types/triggers.types';
import { ValidationError } from '../../src/errors';
import {
ComposioWebhookSignatureVerificationError,
ComposioWebhookPayloadError,
} from '../../src/errors/TriggerErrors';
+import type { BaseComposioProvider } from '../../src/provider/BaseProvider';
+
+/** Shape of the `cause` payload attached to {@link ComposioWebhookPayloadError} when no version schema matches. */
+type WebhookVersionMismatchCause = {
+ v1Error: string;
+ v2Error: string;
+ v3Error: string;
+};
// Mock dependencies
vi.mock('../../src/utils/logger');
@@ -105,7 +114,7 @@ const createMockV3Payload = (overrides: Partial<WebhookPayloadV3> = {}): Webhook
});
describe('Triggers.verifyWebhook', () => {
- let triggers: Triggers<any>;
+ let triggers: Triggers<BaseComposioProvider<unknown, unknown, unknown>>;
let mockClient: ReturnType<typeof createMockClient>;
const testSecret = 'test-webhook-secret-12345';
const testWebhookId = 'msg_test123';
@@ -556,9 +565,10 @@ describe('Triggers.verifyWebhook', () => {
const webhookError = error as ComposioWebhookPayloadError;
expect(webhookError.cause).toBeDefined();
// The cause should contain v1Error, v2Error, and v3Error with schema validation messages
- expect((webhookError.cause as any).v1Error).toBeDefined();
- expect((webhookError.cause as any).v2Error).toBeDefined();
- expect((webhookError.cause as any).v3Error).toBeDefined();
+ const cause = webhookError.cause as unknown as WebhookVersionMismatchCause;
+ expect(cause.v1Error).toBeDefined();
+ expect(cause.v2Error).toBeDefined();
+ expect(cause.v3Error).toBeDefined();
}
});
});
@@ -650,7 +660,7 @@ describe('Triggers.verifyWebhook', () => {
secret: testSecret,
webhookId: testWebhookId,
webhookTimestamp: testTimestamp,
- } as any)
+ } as unknown as VerifyWebhookParams)
).rejects.toThrow(ValidationError);
});
@@ -661,7 +671,7 @@ describe('Triggers.verifyWebhook', () => {
secret: testSecret,
webhookId: testWebhookId,
webhookTimestamp: testTimestamp,
- } as any)
+ } as unknown as VerifyWebhookParams)
).rejects.toThrow(ValidationError);
});
@@ -672,7 +682,7 @@ describe('Triggers.verifyWebhook', () => {
signature: 'v1,sig',
webhookId: testWebhookId,
webhookTimestamp: testTimestamp,
- } as any)
+ } as unknown as VerifyWebhookParams)
).rejects.toThrow(ValidationError);
});
@@ -683,7 +693,7 @@ describe('Triggers.verifyWebhook', () => {
signature: 'v1,sig',
secret: testSecret,
webhookTimestamp: testTimestamp,
- } as any)
+ } as unknown as VerifyWebhookParams)
).rejects.toThrow(ValidationError);
});
@@ -694,7 +704,7 @@ describe('Triggers.verifyWebhook', () => {
signature: 'v1,sig',
secret: testSecret,
webhookId: testWebhookId,
- } as any)
+ } as unknown as VerifyWebhookParams)
).rejects.toThrow(ValidationError);
});
@@ -706,7 +716,7 @@ describe('Triggers.verifyWebhook', () => {
secret: testSecret,
id: testWebhookId,
timestamp: testTimestamp,
- tolerance: 'invalid' as any,
+ tolerance: 'invalid' as unknown as number,
})
).rejects.toThrow(ValidationError);
});
diff --git a/ts/packages/core/test/provider/openai-provider.test.ts b/ts/packages/core/test/provider/openai-provider.test.ts
index 930b93e91..e9c0a94be 100644
--- a/ts/packages/core/test/provider/openai-provider.test.ts
+++ b/ts/packages/core/test/provider/openai-provider.test.ts
@@ -22,7 +22,7 @@ vi.mock('openai/streaming', () => {
describe('OpenAIProvider', () => {
let provider: OpenAIProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
// Sample tool data
beforeEach(() => {
@@ -632,7 +632,7 @@ describe('OpenAIProvider', () => {
client.beta.threads.runs.retrieve = vi.fn().mockResolvedValue(finalRun);
// Collect the yielded events
- const collectedEvents: any[] = [];
+ const collectedEvents: unknown[] = [];
for await (const event of provider.waitAndHandleAssistantStreamToolCalls(
userId,
client,
diff --git a/ts/packages/core/test/telemetry/TelemetryService.test.ts b/ts/packages/core/test/telemetry/TelemetryService.test.ts
index 80a8ebb61..94925277c 100644
--- a/ts/packages/core/test/telemetry/TelemetryService.test.ts
+++ b/ts/packages/core/test/telemetry/TelemetryService.test.ts
@@ -281,7 +281,7 @@ describe('BatchProcessor', () => {
const batchesProcessed: number[][] = [];
let resolvers: (() => void)[] = [];
- const asyncCallback = vi.fn().mockImplementation((batch: any[]) => {
+ const asyncCallback = vi.fn().mockImplementation((batch: unknown[]) => {
return new Promise<void>(resolve => {
resolvers.push(resolve);
}).then(() => {
@@ -317,8 +317,8 @@ describe('BatchProcessor', () => {
describe('TelemetryTransport', () => {
let transport: TelemetryTransport;
- let sendMetricSpy: any;
- let sendErrorLogSpy: any;
+ let sendMetricSpy: unknown;
+ let sendErrorLogSpy: unknown;
const metadata: TelemetryMetadata = {
apiKey: 'test-key',
baseUrl: 'http://localhost',
@@ -329,8 +329,8 @@ describe('TelemetryTransport', () => {
};
beforeEach(async () => {
- sendMetricSpy = vi.spyOn(TelemetryService, 'sendMetric').mockResolvedValue({} as any);
- sendErrorLogSpy = vi.spyOn(TelemetryService, 'sendErrorLog').mockResolvedValue({} as any);
+ sendMetricSpy = vi.spyOn(TelemetryService, 'sendMetric').mockResolvedValue({} as unknown);
+ sendErrorLogSpy = vi.spyOn(TelemetryService, 'sendErrorLog').mockResolvedValue({} as unknown);
transport = new TelemetryTransport();
transport.setup(metadata);
await transport.flush();
@@ -391,7 +391,7 @@ describe('TelemetryTransport', () => {
sendErrorLogSpy.mockImplementationOnce(
() =>
new Promise(resolve => {
- resolveTelemetry = () => resolve({} as any);
+ resolveTelemetry = () => resolve({} as unknown);
})
);
diff --git a/ts/packages/core/test/tools/fileModifiers.test.ts b/ts/packages/core/test/tools/fileModifiers.test.ts
index f2de10c2a..fb3e557bf 100644
--- a/ts/packages/core/test/tools/fileModifiers.test.ts
+++ b/ts/packages/core/test/tools/fileModifiers.test.ts
@@ -2088,7 +2088,7 @@ describe('Tools with dangerouslyAllowAutoUploadDownloadFiles', () => {
mockClient.tools.execute.mockResolvedValueOnce(mockResponse);
// Mock transformToolExecuteResponse to return the same data structure
- vi.spyOn(context.tools as any, 'transformToolExecuteResponse').mockReturnValue({
+ vi.spyOn(context.tools as unknown, 'transformToolExecuteResponse').mockReturnValue({
data: mockResponse.data,
error: mockResponse.error,
successful: mockResponse.successful,
diff --git a/ts/packages/core/test/tools/modifiers.test.ts b/ts/packages/core/test/tools/modifiers.test.ts
index 0f2442561..334d4fba3 100644
--- a/ts/packages/core/test/tools/modifiers.test.ts
+++ b/ts/packages/core/test/tools/modifiers.test.ts
@@ -214,8 +214,8 @@ describe('Tools Modifiers', () => {
};
getRawComposioToolBySlugSpy.mockResolvedValueOnce(mockTool);
- const createExecuteToolFnSpy = vi.spyOn(context.tools as any, 'createExecuteToolFn');
- const executeWithModifiers = async (params: any) => {
+ const createExecuteToolFnSpy = vi.spyOn(context.tools as unknown, 'createExecuteToolFn');
+ const executeWithModifiers = async (params: unknown) => {
// Apply beforeExecute modifier
const modifiedParams = await executionModifiers.beforeExecute({
toolSlug: slug,
diff --git a/ts/packages/core/test/tools/tools.test.ts b/ts/packages/core/test/tools/tools.test.ts
index 0641ecb4c..c19ca5ed2 100644
--- a/ts/packages/core/test/tools/tools.test.ts
+++ b/ts/packages/core/test/tools/tools.test.ts
@@ -2,8 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mockClient } from '../utils/mocks/client.mock';
import { toolMocks } from '../utils/mocks/data.mock';
import { Tool, ToolListParams, ToolExecuteParams } from '../../src/types/tool.types';
+import { ExecuteToolFn } from '../../src/types/provider.types';
import { Tools } from '../../src/models/Tools';
-import ComposioClient from '@composio/client';
import {
createTestContext,
setupTest,
@@ -13,19 +13,33 @@ import {
import { MockProvider } from '../utils/mocks/provider.mock';
import { ValidationError } from '../../src/errors/ValidationErrors';
+// Minimal structural shape for a ComposioError-like value (possibly wrapping
+// another error as its `cause`), used to narrow `catch (error: unknown)`
+// blocks that assert on `.code` / `.message` / `.possibleFixes`.
+type ErrorWithPossibleFixes = {
+ code?: string;
+ message?: string;
+ possibleFixes?: string[];
+ cause?: {
+ code?: string;
+ message?: string;
+ possibleFixes?: string[];
+ };
+};
+
describe('Tools', () => {
const context = createTestContext();
setupTest(context);
describe('constructor', () => {
it('should throw an error if client is not provided', () => {
- expect(() => new Tools(null as any, { provider: context.mockProvider })).toThrow(
+ expect(() => new Tools(null as unknown, { provider: context.mockProvider })).toThrow(
'ComposioClient is required'
);
});
it('should throw an error if provider is not provided', () => {
- expect(() => new Tools(mockClient as unknown as ComposioClient, null as any)).toThrow(
+ expect(() => new Tools(mockClient, null as unknown)).toThrow(
'Provider not passed into Tools instance'
);
});
@@ -296,7 +310,7 @@ describe('Tools', () => {
it('should throw a validation error when scopes are provided without toolkits', async () => {
const invalidQuery = {
scopes: ['task:add'],
- } as any;
+ } as unknown;
await expect(context.tools.getRawComposioTools(invalidQuery)).rejects.toThrow(
'Invalid tool list parameters'
@@ -335,7 +349,7 @@ describe('Tools', () => {
});
it('should throw an error if schema modifier is not a function', async () => {
- const invalidModifier = 'not a function' as any;
+ const invalidModifier = 'not a function' as unknown;
mockClient.tools.list.mockResolvedValueOnce({
items: [toolMocks.rawTool],
@@ -356,7 +370,7 @@ describe('Tools', () => {
const invalidQuery = {
tools: ['TOOL1'],
toolkits: ['github'],
- } as any;
+ } as unknown;
await expect(context.tools.getRawComposioTools(invalidQuery)).rejects.toThrow(
'Invalid tool list parameters'
@@ -364,7 +378,7 @@ describe('Tools', () => {
});
it('should throw a validation error when no required parameters are provided', async () => {
- const emptyQuery = {} as any;
+ const emptyQuery = {} as unknown;
await expect(context.tools.getRawComposioTools(emptyQuery)).rejects.toThrow(ValidationError);
});
@@ -493,7 +507,7 @@ describe('Tools', () => {
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
// Create a Tools instance with SDK-level toolkitVersions as mapping object
- const toolsWithVersions = new Tools(mockClient as any, {
+ const toolsWithVersions = new Tools(mockClient, {
provider: context.mockProvider,
toolkitVersions: versionMapping,
});
@@ -533,7 +547,7 @@ describe('Tools', () => {
const explicitVersion = '20250909_00';
// Create a Tools instance with SDK-level toolkitVersions
- const toolsWithVersions = new Tools(mockClient as any, {
+ const toolsWithVersions = new Tools(mockClient, {
provider: context.mockProvider,
toolkitVersions: { github: explicitVersion },
});
@@ -1226,7 +1240,7 @@ describe('Tools', () => {
it('should throw validation error for invalid parameters', async () => {
const invalidProxyParams = {
endpoint: '/api/test',
- method: 'INVALID_METHOD' as any,
+ method: 'INVALID_METHOD' as unknown,
parameters: [
{
in: 'header' as const,
@@ -1322,7 +1336,7 @@ describe('Tools', () => {
const invalidBody = {
// missing sessionId
arguments: { query: 'test' },
- } as any;
+ } as unknown;
await expect(
context.tools.executeSessionTool('COMPOSIO_TOOL', invalidBody)
@@ -1508,7 +1522,10 @@ describe('Tools', () => {
it('should create execute function that calls executeSessionTool', async () => {
const tools = [toolMocks.transformedTool as unknown as Tool];
- let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
+ let capturedExecuteFn: (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ) => Promise<unknown>;
context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
capturedExecuteFn = executeFn;
@@ -1552,7 +1569,10 @@ describe('Tools', () => {
})),
};
- let capturedExecuteFn: (toolSlug: string, input: Record<string, unknown>) => Promise<any>;
+ let capturedExecuteFn: (
+ toolSlug: string,
+ input: Record<string, unknown>
+ ) => Promise<unknown>;
context.mockProvider.wrapTools.mockImplementation((tools, executeFn) => {
capturedExecuteFn = executeFn;
@@ -1633,9 +1653,9 @@ describe('Tools', () => {
it('should pass global version string when configured', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
- toolkitVersions: '20251201_03' as any,
+ toolkitVersions: '20251201_03' as unknown,
});
mockClient.tools.list.mockResolvedValueOnce({
@@ -1657,7 +1677,7 @@ describe('Tools', () => {
it('should pass toolkit-specific versions when configured as object', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -1689,7 +1709,7 @@ describe('Tools', () => {
it('should pass versions when fetching tools by tool slugs', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -1719,7 +1739,7 @@ describe('Tools', () => {
it('should pass versions when searching tools', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: 'latest',
});
@@ -1760,9 +1780,9 @@ describe('Tools', () => {
it('should pass global version when retrieving single tool', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
- toolkitVersions: '20251201_03' as any,
+ toolkitVersions: '20251201_03' as unknown,
});
mockClient.tools.retrieve.mockResolvedValueOnce(toolMocks.rawTool);
@@ -1780,7 +1800,7 @@ describe('Tools', () => {
it('should pass toolkit-specific versions when retrieving single tool', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -1838,9 +1858,9 @@ describe('Tools', () => {
it('should use global version when configured', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
- toolkitVersions: '20251201_03' as any,
+ toolkitVersions: '20251201_03' as unknown,
});
const spies = await mockToolExecution(tools);
@@ -1869,7 +1889,7 @@ describe('Tools', () => {
it('should use toolkit-specific version when configured as object', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
'test-toolkit': '20251201_01', // Use the actual toolkit slug from mock
@@ -1914,7 +1934,7 @@ describe('Tools', () => {
it('should use fallback to "latest" when toolkit not in version mapping', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -1957,7 +1977,7 @@ describe('Tools', () => {
it('should prioritize explicit version parameter over configured versions', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -1993,7 +2013,7 @@ describe('Tools', () => {
it('should handle tool without toolkit gracefully', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_01',
@@ -2054,7 +2074,7 @@ describe('Tools', () => {
const mockProvider = new MockProvider();
// Pass the processed environment variables to the Tools constructor
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_08',
@@ -2088,7 +2108,7 @@ describe('Tools', () => {
process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
github: '20251201_04', // should override env
@@ -2122,9 +2142,9 @@ describe('Tools', () => {
process.env.COMPOSIO_TOOLKIT_VERSION_SLACK = 'latest';
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
- toolkitVersions: '20251201_09' as any, // global version overrides everything
+ toolkitVersions: '20251201_09' as unknown, // global version overrides everything
});
mockClient.tools.list.mockResolvedValueOnce({
@@ -2207,7 +2227,7 @@ describe('Tools', () => {
it('should succeed when executing with a specific version (not "latest") without dangerouslySkipVersionCheck', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
'test-toolkit': '20251201_01',
@@ -2280,7 +2300,7 @@ describe('Tools', () => {
it('should throw error when explicit version parameter is "latest" without dangerouslySkipVersionCheck', async () => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, {
+ const tools = new Tools(mockClient, {
provider: mockProvider,
toolkitVersions: {
'test-toolkit': '20251201_01', // specific version in config
@@ -2319,7 +2339,8 @@ describe('Tools', () => {
try {
await context.tools.execute('GITHUB_CREATE_ISSUE', executeParams);
expect.fail('Should have thrown an error');
- } catch (error: any) {
+ } catch (rawError: unknown) {
+ const error = rawError as unknown as ErrorWithPossibleFixes;
// The error should be wrapped in ComposioToolExecutionError
expect(error).toBeDefined();
@@ -2364,17 +2385,15 @@ describe('Tools', () => {
);
// Mock provider wrapping
- context.mockProvider.wrapTools.mockImplementation((tools, executeToolFn) => {
- // Store the execute function so we can test it
- (context as any).storedExecuteToolFn = executeToolFn;
+ let storedExecuteToolFn: ExecuteToolFn | undefined;
+ context.mockProvider.wrapTools.mockImplementation((_tools, executeToolFn) => {
+ storedExecuteToolFn = executeToolFn;
return 'wrapped-tools-collection';
});
// Get the tool (this will internally create the execute tool function)
await context.tools.get(userId, 'GITHUB_CREATE_ISSUE');
- // Now call the stored execute function (simulating agentic provider calling it)
- const storedExecuteToolFn = (context as any).storedExecuteToolFn;
expect(storedExecuteToolFn).toBeDefined();
// Setup mocks for the actual execution
@@ -2382,7 +2401,7 @@ describe('Tools', () => {
// Call the execute function that was passed to the provider
// This should succeed because createExecuteToolFn sets dangerouslySkipVersionCheck: true
- const result = await storedExecuteToolFn('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });
+ const result = await storedExecuteToolFn!('GITHUB_CREATE_ISSUE', { title: 'Test Issue' });
expect(result).toEqual(toolMocks.toolExecuteResponse);
expect(mockClient.tools.execute).toHaveBeenCalledWith(
diff --git a/ts/packages/core/test/utils/fileUtils.test.ts b/ts/packages/core/test/utils/fileUtils.test.ts
index e33db5d47..241edb3b1 100644
--- a/ts/packages/core/test/utils/fileUtils.test.ts
+++ b/ts/packages/core/test/utils/fileUtils.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
import * as path from 'node:path';
import { getFileDataAfterUploadingToS3, downloadFileFromS3 } from '../../src/utils/fileUtils.node';
import ComposioClient from '@composio/client';
@@ -85,7 +85,7 @@ describe('fileUtils', () => {
mockFetch.mockResolvedValue(fetchedFileResponse());
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValue({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValue({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -199,7 +199,7 @@ describe('fileUtils', () => {
mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -225,7 +225,7 @@ describe('fileUtils', () => {
mockFetch.mockResolvedValueOnce(fetchedFileResponse('text/plain; charset=utf-8'));
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -260,7 +260,7 @@ describe('fileUtils', () => {
mockFetch.mockResolvedValueOnce(fetchedFileResponse(mimeType));
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -286,7 +286,7 @@ describe('fileUtils', () => {
mockFetch.mockResolvedValueOnce(fetchedFileResponse('application/custom-format'));
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -410,7 +410,7 @@ describe('fileUtils', () => {
vi.clearAllMocks();
// Mock successful S3 upload
- (mockClient.files.createPresignedURL as any).mockResolvedValueOnce({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValueOnce({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -479,7 +479,7 @@ describe('fileUtils', () => {
it('should handle S3 upload errors', async () => {
mockFetch.mockResolvedValueOnce(fetchedFileResponse());
- (mockClient.files.createPresignedURL as any).mockResolvedValue({
+ (mockClient.files.createPresignedURL as unknown as Mock).mockResolvedValue({
key: 'test-key',
type: 'new',
new_presigned_url: 'https://s3.example.com/upload',
@@ -502,7 +502,7 @@ describe('fileUtils', () => {
it('should handle invalid file types', async () => {
await expect(
- getFileDataAfterUploadingToS3(123 as any, {
+ getFileDataAfterUploadingToS3(123 as unknown as string, {
toolSlug: 'test-tool',
toolkitSlug: 'test-toolkit',
client: mockClient,
diff --git a/ts/packages/core/test/utils/jsonSchema.test.ts b/ts/packages/core/test/utils/jsonSchema.test.ts
index 120e49245..76d593efc 100644
--- a/ts/packages/core/test/utils/jsonSchema.test.ts
+++ b/ts/packages/core/test/utils/jsonSchema.test.ts
@@ -227,8 +227,7 @@ describe('dereferenceJsonSchema', () => {
v: { $ref: '#/$defs/User' },
},
$defs: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- User: { type: 'object', __proto__: { polluted: true } } as any,
+ User: { type: 'object', __proto__: { polluted: true } },
},
} as Record<string, unknown>);
diff --git a/ts/packages/core/test/utils/mocks/client.mock.ts b/ts/packages/core/test/utils/mocks/client.mock.ts
index 2c4b366b6..d59dc60c5 100644
--- a/ts/packages/core/test/utils/mocks/client.mock.ts
+++ b/ts/packages/core/test/utils/mocks/client.mock.ts
@@ -1,50 +1,55 @@
import { vi } from 'vitest';
+import ComposioClient from '@composio/client';
-const mockClientBase = {
- tools: {
- list: vi.fn(),
- retrieve: vi.fn(),
- execute: vi.fn(),
- retrieveEnum: vi.fn(),
- getInput: vi.fn(),
- proxy: vi.fn(),
- },
- connectedAccounts: {
- list: vi.fn(),
- get: vi.fn(),
- retrieve: vi.fn(),
- delete: vi.fn(),
- refresh: vi.fn(),
- updateStatus: vi.fn(),
- },
- toolkits: {
- list: vi.fn(),
- retrieve: vi.fn(),
- retrieveCategories: vi.fn(),
- },
- authConfigs: {
- list: vi.fn(),
- create: vi.fn(),
- retrieve: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
- updateStatus: vi.fn(),
- },
- toolRouter: {
- session: {
- execute: vi.fn(),
- tools: vi.fn(),
- },
- },
-};
-
-// `withOptions` returns the same mock so chained calls (e.g.
-// `client.withOptions({ maxRetries: 0 }).tools.execute(...)`) still record on
-// the same spies. Mirrors the real client's `withOptions`.
-//
-// This implementation is load-bearing: tests rely on `vi.clearAllMocks()`
-// (which preserves implementations), not `vi.resetAllMocks()` (which would wipe
-// it and make chained `.tools.*` calls throw on `undefined`).
-export const mockClient = Object.assign(mockClientBase, {
- withOptions: vi.fn(() => mockClientBase),
+const client = new ComposioClient({ apiKey: 'test-api-key' });
+
+const tools = Object.assign(client.tools, {
+ list: vi.fn<typeof client.tools.list>(),
+ retrieve: vi.fn<typeof client.tools.retrieve>(),
+ execute: vi.fn<typeof client.tools.execute>(),
+ retrieveEnum: vi.fn<typeof client.tools.retrieveEnum>(),
+ getInput: vi.fn<typeof client.tools.getInput>(),
+ proxy: vi.fn<typeof client.tools.proxy>(),
+});
+
+const connectedAccounts = Object.assign(client.connectedAccounts, {
+ list: vi.fn<typeof client.connectedAccounts.list>(),
+ create: vi.fn<typeof client.connectedAccounts.create>(),
+ retrieve: vi.fn<typeof client.connectedAccounts.retrieve>(),
+ delete: vi.fn<typeof client.connectedAccounts.delete>(),
+ refresh: vi.fn<typeof client.connectedAccounts.refresh>(),
+ updateStatus: vi.fn<typeof client.connectedAccounts.updateStatus>(),
+});
+
+const toolkits = Object.assign(client.toolkits, {
+ list: vi.fn<typeof client.toolkits.list>(),
+ retrieve: vi.fn<typeof client.toolkits.retrieve>(),
+ retrieveCategories: vi.fn<typeof client.toolkits.retrieveCategories>(),
+});
+
+const authConfigs = Object.assign(client.authConfigs, {
+ list: vi.fn<typeof client.authConfigs.list>(),
+ create: vi.fn<typeof client.authConfigs.create>(),
+ retrieve: vi.fn<typeof client.authConfigs.retrieve>(),
+ update: vi.fn<typeof client.authConfigs.update>(),
+ delete: vi.fn<typeof client.authConfigs.delete>(),
+ updateStatus: vi.fn<typeof client.authConfigs.updateStatus>(),
+});
+
+const session = Object.assign(client.toolRouter.session, {
+ execute: vi.fn<typeof client.toolRouter.session.execute>(),
+ tools: vi.fn<typeof client.toolRouter.session.tools>(),
});
+const toolRouter = Object.assign(client.toolRouter, { session });
+const withOptions = vi.fn<typeof client.withOptions>();
+
+export const mockClient = Object.assign(client, {
+ tools,
+ connectedAccounts,
+ toolkits,
+ authConfigs,
+ toolRouter,
+ withOptions,
+});
+
+withOptions.mockReturnValue(mockClient);
diff --git a/ts/packages/core/test/utils/pusher.test.ts b/ts/packages/core/test/utils/pusher.test.ts
index 588b1976d..a72c33258 100644
--- a/ts/packages/core/test/utils/pusher.test.ts
+++ b/ts/packages/core/test/utils/pusher.test.ts
@@ -4,7 +4,7 @@ import { PusherUtils } from '../../src/utils/pusher';
// Capture the options passed to the Pusher constructor so the
// channelAuthorization.customHandler can be exercised in isolation.
const { constructorCalls } = vi.hoisted(() => ({
- constructorCalls: [] as Array<{ key: string; options: Record<string, any> }>,
+ constructorCalls: [] as Array<{ key: string; options: Record<string, unknown> }>,
}));
vi.mock('pusher-js', () => {
@@ -13,7 +13,7 @@ vi.mock('pusher-js', () => {
subscribe = vi.fn();
unsubscribe = vi.fn();
bind = vi.fn();
- constructor(key: string, options: Record<string, any>) {
+ constructor(key: string, options: Record<string, unknown>) {
constructorCalls.push({ key, options });
}
}
diff --git a/ts/packages/core/test/utils/toolExecuteUtils.ts b/ts/packages/core/test/utils/toolExecuteUtils.ts
index 21e0037c1..158f3c8d7 100644
--- a/ts/packages/core/test/utils/toolExecuteUtils.ts
+++ b/ts/packages/core/test/utils/toolExecuteUtils.ts
@@ -3,7 +3,6 @@ import { Tools } from '../../src/models/Tools';
import { mockClient } from './mocks/client.mock';
import { MockProvider } from './mocks/provider.mock';
import { connectedAccountMocks, toolkitMocks, toolMocks } from './mocks/data.mock';
-import ComposioClient from '@composio/client';
import { Tool, ToolExecuteResponse, ToolExecuteParams } from '../../src/types/tool.types';
export type TestTools = Tools<Tool[], Tool, MockProvider>;
@@ -15,7 +14,7 @@ export interface TestContext {
export const createTestContext = (): TestContext => {
const mockProvider = new MockProvider();
- const tools = new Tools(mockClient as unknown as ComposioClient, { provider: mockProvider });
+ const tools = new Tools(mockClient, { provider: mockProvider });
return { tools, mockProvider };
};
@@ -23,7 +22,7 @@ export const setupTest = (context: TestContext) => {
beforeEach(() => {
vi.clearAllMocks();
context.mockProvider = new MockProvider();
- context.tools = new Tools(mockClient as unknown as ComposioClient, {
+ context.tools = new Tools(mockClient, {
provider: context.mockProvider,
});
});
diff --git a/ts/packages/core/test/utils/transform.test.ts b/ts/packages/core/test/utils/transform.test.ts
index 843e068f5..1618975b9 100644
--- a/ts/packages/core/test/utils/transform.test.ts
+++ b/ts/packages/core/test/utils/transform.test.ts
@@ -43,7 +43,7 @@ describe('transform', () => {
const result = transform({ name: 'Alice', extra: 'field' })
.with(schema)
- .using(raw => raw as any);
+ .using(raw => raw as unknown);
expect(result).toEqual({ name: 'Alice' });
expect(result).not.toHaveProperty('extra');
@@ -57,7 +57,7 @@ describe('transform', () => {
const result = transform({ name: 123, age: 'not a number' })
.with(schema)
- .using(raw => raw as any);
+ .using(raw => raw as unknown);
expect(result).toEqual({ name: 123, age: 'not a number' });
@@ -75,7 +75,7 @@ describe('transform', () => {
transform({ id: 42 })
.with(schema)
- .using(raw => raw as any, { label: 'ConnectedAccount' });
+ .using(raw => raw as unknown, { label: 'ConnectedAccount' });
expect(mockLogger.warn).toHaveBeenCalledTimes(1);
const warnMessage = mockLogger.warn.mock.calls[0][0] as string;
@@ -87,7 +87,7 @@ describe('transform', () => {
const result = transform({ id: 'abc' })
.with(schema)
- .using(raw => raw as any);
+ .using(raw => raw as unknown);
expect(result).toEqual({ id: 'abc' });
expect(mockLogger.warn).not.toHaveBeenCalled();
@@ -103,7 +103,7 @@ describe('transform', () => {
const result = transform({ user: { email: 'not-an-email' } })
.with(schema)
- .using(raw => raw as any);
+ .using(raw => raw as unknown);
expect(result).toEqual({ user: { email: 'not-an-email' } });
expect(mockLogger.warn).toHaveBeenCalledTimes(1);
diff --git a/ts/packages/core/test/utils/transformers/mcp.test.ts b/ts/packages/core/test/utils/transformers/mcp.test.ts
index 5a6542e93..f14e7f866 100644
--- a/ts/packages/core/test/utils/transformers/mcp.test.ts
+++ b/ts/packages/core/test/utils/transformers/mcp.test.ts
@@ -18,7 +18,7 @@ describe('MCP Transformers', () => {
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-02T00:00:00Z',
status: 'active',
- } as any;
+ } as unknown;
const result = transformMcpCreateResponse(snakeCaseResponse);
@@ -35,7 +35,7 @@ describe('MCP Transformers', () => {
const minimalResponse = {
id: 'mcp_123',
name: 'test-server',
- } as any;
+ } as unknown;
const result = transformMcpCreateResponse(minimalResponse);
@@ -49,7 +49,7 @@ describe('MCP Transformers', () => {
const invalidResponse = {
id: '', // Empty ID should fail validation
name: 'test-server',
- } as any;
+ } as unknown;
expect(() => transformMcpCreateResponse(invalidResponse)).toThrow(ValidationError);
expect(() => transformMcpCreateResponse(invalidResponse)).toThrow(
@@ -77,7 +77,7 @@ describe('MCP Transformers', () => {
status: 'inactive',
},
],
- } as any;
+ } as unknown;
const result = transformMcpListResponse(snakeCaseResponse);
@@ -104,7 +104,7 @@ describe('MCP Transformers', () => {
it('should handle empty items array', () => {
const emptyResponse = {
items: [],
- } as any;
+ } as unknown;
const result = transformMcpListResponse(emptyResponse);
@@ -114,7 +114,7 @@ describe('MCP Transformers', () => {
});
it('should handle missing items', () => {
- const noItemsResponse = {} as any;
+ const noItemsResponse = {} as unknown;
const result = transformMcpListResponse(noItemsResponse);
@@ -141,7 +141,7 @@ describe('MCP Transformers', () => {
cursor: 'cursor-command',
windsurf: 'windsurf-command',
},
- } as any;
+ } as unknown;
const result = transformMcpRetrieveResponse(snakeCaseResponse);
@@ -173,7 +173,7 @@ describe('MCP Transformers', () => {
cursor: 'cursor-command',
windsurf: 'windsurf-command',
},
- } as any;
+ } as unknown;
const result = transformMcpRetrieveResponse(minimalResponse);
@@ -193,7 +193,7 @@ describe('MCP Transformers', () => {
const invalidResponse = {
id: 'mcp_123',
// Missing required 'name' field
- } as any;
+ } as unknown;
expect(() => transformMcpRetrieveResponse(invalidResponse)).toThrow(ValidationError);
});
@@ -205,7 +205,7 @@ describe('MCP Transformers', () => {
id: 'mcp_123',
deleted: true,
message: 'Server deleted successfully',
- } as any;
+ } as unknown;
const result = transformMcpDeleteResponse(snakeCaseResponse);
@@ -219,7 +219,7 @@ describe('MCP Transformers', () => {
it('should handle response without optional fields', () => {
const minimalResponse = {
id: 'mcp_123',
- } as any;
+ } as unknown;
const result = transformMcpDeleteResponse(minimalResponse);
@@ -239,7 +239,7 @@ describe('MCP Transformers', () => {
status: 'active',
toolkits: ['gmail', 'slack'],
tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE'],
- } as any;
+ } as unknown;
const result = transformMcpUpdateResponse(snakeCaseResponse);
@@ -258,7 +258,7 @@ describe('MCP Transformers', () => {
const minimalResponse = {
id: 'mcp_123',
name: 'updated-server',
- } as any;
+ } as unknown;
const result = transformMcpUpdateResponse(minimalResponse);
@@ -272,7 +272,7 @@ describe('MCP Transformers', () => {
const invalidResponse = {
id: 'mcp_123',
name: '', // Empty name should fail validation
- } as any;
+ } as unknown;
expect(() => transformMcpUpdateResponse(invalidResponse)).toThrow(ValidationError);
expect(() => transformMcpUpdateResponse(invalidResponse)).toThrow(
@@ -362,7 +362,7 @@ describe('MCP Transformers', () => {
created_at: null,
updated_at: null,
status: null,
- } as any;
+ } as unknown;
const result = transformMcpCreateResponse(responseWithNulls);
@@ -382,7 +382,7 @@ describe('MCP Transformers', () => {
created_at: undefined,
updated_at: undefined,
status: undefined,
- } as any;
+ } as unknown;
const result = transformMcpCreateResponse(responseWithUndefined);
@@ -399,7 +399,7 @@ describe('MCP Transformers', () => {
created_at: '2024-01-01T00:00:00Z',
some_unknown_field: 'value',
nested_object: { key: 'value' },
- } as any;
+ } as unknown;
const result = transformMcpCreateResponse(responseWithExtraFields);
diff --git a/ts/packages/core/type-tests/json-schema-property.test-d.ts b/ts/packages/core/type-tests/json-schema-property.test-d.ts
new file mode 100644
index 000000000..ff7203e19
--- /dev/null
+++ b/ts/packages/core/type-tests/json-schema-property.test-d.ts
@@ -0,0 +1,35 @@
+import type { JSONSchemaProperty, Tool } from '../src';
+
+const recursiveSchema: JSONSchemaProperty = {
+ type: 'object',
+ properties: {
+ filters: {
+ anyOf: [
+ { type: 'string', enum: ['active', 'archived'] },
+ {
+ type: 'array',
+ items: { type: 'integer', minimum: 1 },
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ default: { filters: 'active' },
+ 'x-composio-metadata': { source: 'type-test' },
+};
+
+const defaultValue: unknown = recursiveSchema.default;
+void defaultValue;
+
+declare const tool: Tool;
+const inputProperties: Record<string, JSONSchemaProperty> | undefined =
+ tool.inputParameters?.properties;
+void inputProperties;
+
+// @ts-expect-error known JSON Schema keywords keep their concrete types
+const invalidType: JSONSchemaProperty = { type: 'date' };
+void invalidType;
+
+// @ts-expect-error recursive properties must contain JSON Schema nodes
+const invalidProperty: JSONSchemaProperty = { properties: { query: 'string' } };
+void invalidProperty;
diff --git a/ts/packages/json-schema-to-zod/src/parsers/parse-array.ts b/ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
index 1d965e95d..8a9983991 100644
--- a/ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
+++ b/ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
@@ -7,8 +7,7 @@ import { its } from '../utils/its';
import type { JSONSchema7TypeName } from 'json-schema';
type MetadataFields =
- | keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'>
- | 'examples';
+ keyof Pick<JsonSchemaObject, 'default' | 'description' | 'title'> | 'examples';
export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, refs: Refs) => {
// Handle anyOf pattern first
@@ -84,26 +83,20 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
);
// Handle generic 'min' property as alias for 'minItems'
- if (
- typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
- typeof jsonSchema.minItems !== 'number'
- ) {
+ if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minItems !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, minItems: (jsonSchema as unknown as { min?: number }).min },
+ { ...jsonSchema, minItems: jsonSchema.min },
'minItems',
(zs, minItems, errorMessage) => zs.min(minItems, errorMessage)
);
}
// Handle generic 'max' property as alias for 'maxItems'
- if (
- typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
- typeof jsonSchema.maxItems !== 'number'
- ) {
+ if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maxItems !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, maxItems: (jsonSchema as unknown as { max?: number }).max },
+ { ...jsonSchema, maxItems: jsonSchema.max },
'maxItems',
(zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage)
);
diff --git a/ts/packages/json-schema-to-zod/src/parsers/parse-number.ts b/ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
index dd37aff75..ab9ede834 100644
--- a/ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
+++ b/ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
@@ -85,26 +85,20 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
}
// Handle generic 'min' property as alias for 'minimum'
- if (
- typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
- typeof jsonSchema.minimum !== 'number'
- ) {
+ if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minimum !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, minimum: (jsonSchema as unknown as { min?: number }).min },
+ { ...jsonSchema, minimum: jsonSchema.min },
'minimum',
(zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
);
}
// Handle generic 'max' property as alias for 'maximum'
- if (
- typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
- typeof jsonSchema.maximum !== 'number'
- ) {
+ if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maximum !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, maximum: (jsonSchema as unknown as { max?: number }).max },
+ { ...jsonSchema, maximum: jsonSchema.max },
'maximum',
(zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
);
diff --git a/ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts b/ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
index ffaf01401..e983d6981 100644
--- a/ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
+++ b/ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
@@ -29,15 +29,12 @@ const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.
}
// Append example(s) if they exist
- if ((jsonSchema as unknown as { example?: unknown }).example !== undefined) {
- const exampleText = `Example: ${JSON.stringify((jsonSchema as unknown as { example?: unknown }).example)}`;
+ if (jsonSchema.example !== undefined) {
+ const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
description = description ? `${description}\n${exampleText}` : exampleText;
- } else if (
- (jsonSchema as unknown as { examples?: unknown[] }).examples !== undefined &&
- Array.isArray((jsonSchema as unknown as { examples?: unknown[] }).examples)
- ) {
- const examples = (jsonSchema as unknown as { examples?: unknown[] }).examples;
- if (examples && examples.length && examples.length > 0) {
+ } else if (jsonSchema.examples !== undefined && Array.isArray(jsonSchema.examples)) {
+ const examples = jsonSchema.examples;
+ if (examples.length > 0) {
const exampleText =
examples.length === 1
? `Example: ${JSON.stringify(examples[0])}`
@@ -69,7 +66,7 @@ const addDefaults = (
inAnyOfOrOneOf &&
jsonSchema.type &&
jsonSchema.type !== 'null' &&
- // @ts-ignore: `nullable` is not publicly available in Zod 4
+ // @ts-expect-error: `nullable` is not publicly available in Zod 4
!jsonSchema.nullable
) {
return zodSchema;
diff --git a/ts/packages/json-schema-to-zod/src/parsers/parse-string.ts b/ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
index 369130de8..60575fff0 100644
--- a/ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
+++ b/ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
@@ -55,26 +55,20 @@ export const parseString = (jsonSchema: JsonSchemaObject & { type: 'string' }) =
);
// Handle generic 'min' property as alias for 'minLength'
- if (
- typeof (jsonSchema as unknown as { min?: number }).min === 'number' &&
- typeof jsonSchema.minLength !== 'number'
- ) {
+ if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minLength !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, minLength: (jsonSchema as unknown as { min?: number }).min },
+ { ...jsonSchema, minLength: jsonSchema.min },
'minLength',
(zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
);
}
// Handle generic 'max' property as alias for 'maxLength'
- if (
- typeof (jsonSchema as unknown as { max?: number }).max === 'number' &&
- typeof jsonSchema.maxLength !== 'number'
- ) {
+ if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maxLength !== 'number') {
zodSchema = extendSchemaWithMessage(
zodSchema,
- { ...jsonSchema, maxLength: (jsonSchema as unknown as { max?: number }).max },
+ { ...jsonSchema, maxLength: jsonSchema.max },
'maxLength',
(zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
);
diff --git a/ts/packages/json-schema-to-zod/src/types.ts b/ts/packages/json-schema-to-zod/src/types.ts
index bbbced698..86de6f259 100644
--- a/ts/packages/json-schema-to-zod/src/types.ts
+++ b/ts/packages/json-schema-to-zod/src/types.ts
@@ -2,15 +2,54 @@ import type { ZodTypeAny } from 'zod/v3';
import type { JSONSchema7 } from 'json-schema';
export type Serializable =
- | { [key: string]: Serializable }
- | Serializable[]
- | string
- | number
- | boolean
- | null;
+ { [key: string]: Serializable } | Serializable[] | string | number | boolean | null;
export type JsonSchema = JsonSchemaObject | boolean;
-export type JsonSchemaObject = JSONSchema7;
+
+type JsonSchemaDefinitions = Record<string, JsonSchema>;
+
+export interface JsonSchemaObject extends Omit<
+ JSONSchema7,
+ | '$defs'
+ | 'items'
+ | 'additionalItems'
+ | 'contains'
+ | 'properties'
+ | 'patternProperties'
+ | 'additionalProperties'
+ | 'dependencies'
+ | 'propertyNames'
+ | 'if'
+ | 'then'
+ | 'else'
+ | 'allOf'
+ | 'anyOf'
+ | 'oneOf'
+ | 'not'
+ | 'definitions'
+> {
+ min?: number;
+ max?: number;
+ example?: Serializable;
+
+ $defs?: JsonSchemaDefinitions;
+ definitions?: JsonSchemaDefinitions;
+ items?: JsonSchema | JsonSchema[];
+ additionalItems?: JsonSchema;
+ contains?: JsonSchema;
+ properties?: JsonSchemaDefinitions;
+ patternProperties?: JsonSchemaDefinitions;
+ additionalProperties?: JsonSchema;
+ dependencies?: Record<string, JsonSchema | string[]>;
+ propertyNames?: JsonSchema;
+ if?: JsonSchema;
+ then?: JsonSchema;
+ else?: JsonSchema;
+ allOf?: JsonSchema[];
+ anyOf?: JsonSchema[];
+ oneOf?: JsonSchema[];
+ not?: JsonSchema;
+}
export type ParserSelector = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny;
export type ParserOverride = (schema: JsonSchemaObject, refs: Refs) => ZodTypeAny | undefined;
diff --git a/ts/packages/json-schema-to-zod/test/comprehensive-edge-case-tests.ts b/ts/packages/json-schema-to-zod/test/comprehensive-edge-case-tests.ts
index 2d10676fb..af0d80250 100644
--- a/ts/packages/json-schema-to-zod/test/comprehensive-edge-case-tests.ts
+++ b/ts/packages/json-schema-to-zod/test/comprehensive-edge-case-tests.ts
@@ -163,7 +163,7 @@ const complexNestedSchema: JsonSchema = {
format: 'email',
nullable: true,
default: null,
- } as any,
+ } as JsonSchema,
},
required: ['name'],
default: { id: 'user-123', name: 'Anonymous', email: null },
@@ -209,7 +209,7 @@ const complexNestedSchema: JsonSchema = {
type: 'string',
nullable: true,
default: null,
- } as any,
+ } as JsonSchema,
},
default: {
settings: { theme: 'light', notifications: true },
diff --git a/ts/packages/json-schema-to-zod/test/json-to-zod.test.ts b/ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
index 8b9f85a1b..045d9a72f 100644
--- a/ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
+++ b/ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
@@ -125,11 +125,11 @@ describe('jsonSchemaToZod', () => {
});
it('should handle generic min and max properties for numbers', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'number',
min: 0,
max: 100,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse(50)).toBe(50);
expect(() => zodSchema.parse(-1)).toThrow();
@@ -137,13 +137,13 @@ describe('jsonSchemaToZod', () => {
});
it('should prioritize minimum/maximum over min/max for numbers', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'number',
minimum: 10,
maximum: 90,
min: 0,
max: 100,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse(50)).toBe(50);
expect(zodSchema.parse(10)).toBe(10);
@@ -155,11 +155,11 @@ describe('jsonSchemaToZod', () => {
describe('String Validations', () => {
it('should handle generic min and max properties for strings', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
min: 3,
max: 10,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse('hello')).toBe('hello');
expect(() => zodSchema.parse('hi')).toThrow();
@@ -167,13 +167,13 @@ describe('jsonSchemaToZod', () => {
});
it('should prioritize minLength/maxLength over min/max for strings', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
minLength: 5,
maxLength: 8,
min: 3,
max: 10,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse('hello')).toBe('hello');
expect(zodSchema.parse('testing')).toBe('testing');
@@ -183,6 +183,28 @@ describe('jsonSchemaToZod', () => {
});
describe('Object Schemas', () => {
+ it('should support extension keywords in nested schemas', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ username: {
+ type: 'string',
+ min: 3,
+ max: 10,
+ example: 'john_doe',
+ },
+ },
+ required: ['username'],
+ } satisfies JsonSchema;
+
+ const zodSchema = jsonSchemaToZod(schema) as z.ZodObject<z.ZodRawShape>;
+
+ expect(zodSchema.parse({ username: 'john_doe' })).toEqual({ username: 'john_doe' });
+ expect(() => zodSchema.parse({ username: 'ab' })).toThrow();
+ expect(() => zodSchema.parse({ username: 'a very long username' })).toThrow();
+ expect(zodSchema.shape.username.description).toBe('Example: "john_doe"');
+ });
+
it('should validate required properties', () => {
const schema: JsonSchema = {
type: 'object',
@@ -514,12 +536,12 @@ describe('jsonSchemaToZod', () => {
});
it('should handle generic min and max properties for arrays', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'array',
items: { type: 'string' },
min: 1,
max: 3,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse(['one'])).toEqual(['one']);
expect(zodSchema.parse(['one', 'two', 'three'])).toEqual(['one', 'two', 'three']);
@@ -528,14 +550,14 @@ describe('jsonSchemaToZod', () => {
});
it('should prioritize minItems/maxItems over min/max for arrays', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'array',
items: { type: 'string' },
minItems: 2,
maxItems: 4,
min: 1,
max: 3,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.parse(['one', 'two'])).toEqual(['one', 'two']);
expect(zodSchema.parse(['one', 'two', 'three', 'four'])).toEqual([
@@ -994,55 +1016,55 @@ describe('jsonSchemaToZod', () => {
});
// Test property description
- const shape = (zodSchema as any)._def.shape();
+ const shape = (zodSchema as z.ZodObject<z.ZodRawShape>).shape;
expect(shape.username.description).toBe('The username of the Hacker News user to retrieve.');
});
it('should append example to description', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
description: 'User name',
example: 'john_doe',
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('User name\nExample: "john_doe"');
});
it('should handle example without description', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'number',
example: 42,
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('Example: 42');
});
it('should handle example with title but no description', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'object',
title: 'User Object',
example: { name: 'John', age: 30 },
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('User Object\nExample: {"name":"John","age":30}');
});
it('should handle single example in examples array', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
description: 'Property name',
examples: ['lifecyclestage'],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('Property name\nExample: "lifecyclestage"');
});
it('should handle multiple examples in examples array', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'array',
description: 'List of property names',
examples: ["['lifecyclestage', 'hs_lead_status']", "['hubspot_owner_id']"],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe(
"List of property names\nExamples:\n \"['lifecyclestage', 'hs_lead_status']\"\n \"['hubspot_owner_id']\""
@@ -1050,28 +1072,28 @@ describe('jsonSchemaToZod', () => {
});
it('should prioritize example over examples', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
description: 'Property name',
example: 'single_example',
examples: ['example1', 'example2'],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('Property name\nExample: "single_example"');
});
it('should handle empty examples array', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
description: 'Property name',
examples: [],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('Property name');
});
it('should preserve array structure in examples', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'array',
description: 'Property combinations',
examples: [
@@ -1079,7 +1101,7 @@ describe('jsonSchemaToZod', () => {
['hubspot_owner_id'],
['created_date', 'modified_date', 'status'],
],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe(
'Property combinations\nExamples:\n ["lifecyclestage","hs_lead_status"]\n ["hubspot_owner_id"]\n ["created_date","modified_date","status"]'
@@ -1087,11 +1109,11 @@ describe('jsonSchemaToZod', () => {
});
it('should handle primitive types in examples array', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'string',
description: 'Status values',
examples: ['active', 'inactive', 'pending'],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe(
'Status values\nExamples:\n "active"\n "inactive"\n "pending"'
@@ -1099,11 +1121,11 @@ describe('jsonSchemaToZod', () => {
});
it('should handle mixed primitive types in examples array', () => {
- const schema: JsonSchema = {
+ const schema = {
type: 'number',
description: 'Various numbers',
examples: [42, 3.14, 0, -5],
- } as any;
+ } satisfies JsonSchema;
const zodSchema = jsonSchemaToZod(schema);
expect(zodSchema.description).toBe('Various numbers\nExamples:\n 42\n 3.14\n 0\n -5');
});
diff --git a/ts/packages/providers/anthropic/test/anthropic.test.ts b/ts/packages/providers/anthropic/test/anthropic.test.ts
index 14ca50c52..1e6b69d5c 100644
--- a/ts/packages/providers/anthropic/test/anthropic.test.ts
+++ b/ts/packages/providers/anthropic/test/anthropic.test.ts
@@ -28,7 +28,7 @@ vi.mock('@anthropic-ai/sdk', () => {
describe('AnthropicProvider', () => {
let provider: AnthropicProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new AnthropicProvider();
diff --git a/ts/packages/providers/anthropic/test/sanitize-keys.test.ts b/ts/packages/providers/anthropic/test/sanitize-keys.test.ts
index e7553e1c1..4e1d01ca2 100644
--- a/ts/packages/providers/anthropic/test/sanitize-keys.test.ts
+++ b/ts/packages/providers/anthropic/test/sanitize-keys.test.ts
@@ -14,6 +14,13 @@ vi.mock('@anthropic-ai/sdk', () => ({
const ANTHROPIC_KEY_RE = /^[a-zA-Z0-9_.-]{1,64}$/;
+/**
+ * Minimal structural shape for a JSON-schema node carrying a `properties` bag,
+ * used to dereference `sanitizeSchemaPropertyKeys` output (typed loosely as the
+ * generic input schema) in test assertions without weakening the cast to `any`.
+ */
+type SchemaWithProperties = { properties: Record<string, unknown>; required?: string[] };
+
describe('sanitizeSchemaPropertyKeys', () => {
it('leaves already-valid keys untouched and reports no mapping', () => {
const schema = {
@@ -121,7 +128,7 @@ describe('sanitizeSchemaPropertyKeys', () => {
};
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
- const nested = (out.properties as any).options;
+ const nested = (out.properties as unknown as { options: SchemaWithProperties }).options;
expect(nested.properties).toHaveProperty('dollar_skip');
expect(nested.required).toEqual(['dollar_skip']);
@@ -162,7 +169,8 @@ describe('sanitizeSchemaPropertyKeys', () => {
};
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
- const itemSchema = (out.properties as any).rows.items;
+ const itemSchema = (out.properties as unknown as { rows: { items: SchemaWithProperties } }).rows
+ .items;
expect(itemSchema.properties).toHaveProperty('dollar_top');
expect(itemSchema.properties).not.toHaveProperty('$top');
@@ -188,7 +196,11 @@ describe('sanitizeSchemaPropertyKeys', () => {
};
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
- const [first, second] = (out.properties as any).pair.items;
+ const [first, second] = (
+ out.properties as unknown as {
+ pair: { items: [SchemaWithProperties, SchemaWithProperties] };
+ }
+ ).pair.items;
expect(first.properties).toHaveProperty('dollar_top');
expect(second.properties).toHaveProperty('plain');
@@ -285,7 +297,13 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
expectNoIllegalPropertyKeys(out);
- expect((out.properties as any).foo.anyOf[0].properties).toHaveProperty('dollar_top');
+ expect(
+ (
+ out.properties as unknown as {
+ foo: { anyOf: SchemaWithProperties[] };
+ }
+ ).foo.anyOf[0].properties
+ ).toHaveProperty('dollar_top');
// The branch rename folds into `foo`'s value level, so restoration finds it.
expect(restoreOriginalKeys({ foo: { dollar_top: 5 } }, mapping)).toEqual({ foo: { $top: 5 } });
@@ -342,7 +360,10 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
// 400-prevention: the alias is emitted so Anthropic accepts the schema.
- expect((out as any).additionalProperties.properties).toHaveProperty('dollar_top');
+ expect(
+ (out as unknown as { additionalProperties: SchemaWithProperties }).additionalProperties
+ .properties
+ ).toHaveProperty('dollar_top');
// Documented limitation: dynamic-key values are not restored — the alias
// reaches the backend rather than being silently (mis)mapped at every level.
expect(restoreOriginalKeys({ anyKey: { dollar_top: 1 } }, mapping)).toEqual({
@@ -358,7 +379,9 @@ describe('sanitizeSchemaPropertyKeys composition coverage', () => {
});
expectNoIllegalPropertyKeys(out);
- expect((out as any).$defs.Foo.properties).toHaveProperty('dollar_top');
+ expect(
+ (out as unknown as { $defs: { Foo: SchemaWithProperties } }).$defs.Foo.properties
+ ).toHaveProperty('dollar_top');
});
it('sanitizes and restores `prefixItems` tuples', () => {
@@ -450,7 +473,9 @@ describe('restoreOriginalKeys', () => {
const { schema: out, mapping } = sanitizeSchemaPropertyKeys(schema);
expect(out.properties).toHaveProperty('dollar_top');
- expect((out.properties as any).filters.properties).toHaveProperty('dollar_top');
+ expect(
+ (out.properties as unknown as { filters: SchemaWithProperties }).filters.properties
+ ).toHaveProperty('dollar_top');
const restored = restoreOriginalKeys(
{ dollar_top: 10, filters: { dollar_top: 'keep-me' } },
@@ -676,8 +701,11 @@ describe('AnthropicProvider key sanitization', () => {
const wrapped = provider.wrapTool(refTool) as AnthropicTool;
// The $ref is inlined, `$defs` removed, and the nested `$top` sanitized.
- expect((wrapped.input_schema.properties as any).filter.properties).toHaveProperty('dollar_top');
- expect((wrapped.input_schema as any).$defs).toBeUndefined();
+ expect(
+ (wrapped.input_schema.properties as unknown as { filter: SchemaWithProperties }).filter
+ .properties
+ ).toHaveProperty('dollar_top');
+ expect((wrapped.input_schema as unknown as { $defs?: unknown }).$defs).toBeUndefined();
await provider.executeToolCall('user-1', {
type: 'tool_use',
diff --git a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
index e8157d263..f0c76026f 100644
--- a/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
+++ b/ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
@@ -1,5 +1,5 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { Tool } from '@composio/core';
+import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
+import { Tool, GlobalExecuteToolFn } from '@composio/core';
import { ClaudeAgentSDKProvider } from '../src';
// Mock the claude-agent-sdk module
@@ -24,15 +24,46 @@ import { tool } from '@anthropic-ai/claude-agent-sdk';
interface MockedClaudeAgentTool {
name: string;
description: string;
- schema: any;
+ schema: unknown;
handler: Function;
_isMockedClaudeAgentTool: boolean;
}
+// Minimal structural type for a zod-like raw shape value, matching only the member these
+// tests dereference (`safeParse`).
+type MinimalZodSchema = {
+ safeParse: (value: unknown) => { success: boolean };
+};
+
+// The handler captured off the mocked `tool()` call. Some tests intentionally pass a raw
+// (possibly malformed) JSON string instead of an object to exercise the stringified-input
+// normalization path (issue #2406), so the parameter is typed `unknown` here rather than the
+// stricter `Record<string, unknown>` used by the real `wrapTool` handler signature.
+type MockedToolHandler = (
+ args: unknown
+) => Promise<{ content: Array<{ type: string; text: string }> }>;
+
+type MockedToolFn = Mock<
+ (
+ name: string,
+ description: string | undefined,
+ schema: Record<string, MinimalZodSchema>,
+ handler: MockedToolHandler
+ ) => unknown
+>;
+
+// `mockExecuteToolFn` is declared against the real `GlobalExecuteToolFn` contract, which always
+// resolves with a `ToolExecuteResponse`. A couple of tests deliberately stub it with a plain
+// string / `undefined` to exercise the wrapTool handler's defensive "stringify anything" branch,
+// so those specific stubbing calls need a widened, minimal view of just the method they use.
+type MockResolvableWithAnyValue = {
+ mockResolvedValueOnce: (value: unknown) => void;
+};
+
describe('ClaudeAgentSDKProvider', () => {
let provider: ClaudeAgentSDKProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: Mock<GlobalExecuteToolFn>;
beforeEach(() => {
provider = new ClaudeAgentSDKProvider();
@@ -111,7 +142,7 @@ describe('ClaudeAgentSDKProvider', () => {
it('should pass a raw Zod shape to the Claude Agent SDK', () => {
provider.wrapTool(mockTool, mockExecuteToolFn);
- const schemaShape = (tool as any).mock.calls[0][2];
+ const schemaShape = (tool as unknown as MockedToolFn).mock.calls[0][2];
expect(Object.keys(schemaShape)).toEqual(['to', 'subject', 'body']);
expect(schemaShape.to.safeParse('[email protected]').success).toBe(true);
expect(schemaShape.to.safeParse(123).success).toBe(false);
@@ -161,7 +192,7 @@ describe('ClaudeAgentSDKProvider', () => {
provider.wrapTool(mockTool, mockExecuteToolFn);
// Extract the handler function from the call to tool()
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
// Test the handler
const params = { to: '[email protected]', subject: 'Test', body: 'Hello' };
@@ -184,7 +215,7 @@ describe('ClaudeAgentSDKProvider', () => {
it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
provider.wrapTool(mockTool, mockExecuteToolFn);
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
const params = { to: '[email protected]', subject: 'Test', body: 'Hello' };
await handler(JSON.stringify(params));
@@ -194,7 +225,7 @@ describe('ClaudeAgentSDKProvider', () => {
it('should surface a typed error for a malformed-JSON string input (issue #2406)', async () => {
provider.wrapTool(mockTool, mockExecuteToolFn);
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
const result = await handler('{"to":');
@@ -206,10 +237,12 @@ describe('ClaudeAgentSDKProvider', () => {
});
it('should handle string results from tool execution', async () => {
- mockExecuteToolFn.mockResolvedValueOnce('Simple string result');
+ (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(
+ 'Simple string result'
+ );
provider.wrapTool(mockTool, mockExecuteToolFn);
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
const result = await handler({ to: '[email protected]', subject: 'Test', body: 'Hello' });
expect(result).toEqual({
@@ -223,10 +256,10 @@ describe('ClaudeAgentSDKProvider', () => {
});
it('should handle undefined results from tool execution and convert to "null" string', async () => {
- mockExecuteToolFn.mockResolvedValueOnce(undefined);
+ (mockExecuteToolFn as unknown as MockResolvableWithAnyValue).mockResolvedValueOnce(undefined);
provider.wrapTool(mockTool, mockExecuteToolFn);
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
const result = await handler({ to: '[email protected]', subject: 'Test', body: 'Hello' });
// text should always be a string, never undefined
@@ -239,7 +272,7 @@ describe('ClaudeAgentSDKProvider', () => {
mockExecuteToolFn.mockRejectedValueOnce(testError);
provider.wrapTool(mockTool, mockExecuteToolFn);
- const handler = (tool as any).mock.calls[0][3];
+ const handler = (tool as unknown as MockedToolFn).mock.calls[0][3];
const result = await handler({ to: '[email protected]', subject: 'Test', body: 'Hello' });
expect(result.content[0].type).toBe('text');
diff --git a/ts/packages/providers/cloudflare/test/cloudflare.test.ts b/ts/packages/providers/cloudflare/test/cloudflare.test.ts
index d1f377866..06a8e5355 100644
--- a/ts/packages/providers/cloudflare/test/cloudflare.test.ts
+++ b/ts/packages/providers/cloudflare/test/cloudflare.test.ts
@@ -6,7 +6,7 @@ import { Tool } from '@composio/core';
interface AiTextGenerationFunction {
name: string;
description: string;
- parameters: any;
+ parameters: unknown;
}
interface MockedCloudflareToolInput {
@@ -14,7 +14,7 @@ interface MockedCloudflareToolInput {
function: {
name: string;
description?: string;
- parameters?: any;
+ parameters?: unknown;
};
}
@@ -26,7 +26,7 @@ vi.mock('@cloudflare/workers-types', () => {
describe('CloudflareProvider', () => {
let provider: CloudflareProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new CloudflareProvider();
diff --git a/ts/packages/providers/google/test/google.test.ts b/ts/packages/providers/google/test/google.test.ts
index 4b3e7f006..acac45059 100644
--- a/ts/packages/providers/google/test/google.test.ts
+++ b/ts/packages/providers/google/test/google.test.ts
@@ -5,7 +5,7 @@ import { Tool } from '@composio/core';
describe('GoogleProvider', () => {
let provider: GoogleProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new GoogleProvider();
diff --git a/ts/packages/providers/langchain/test/langchain.test.ts b/ts/packages/providers/langchain/test/langchain.test.ts
index 1446fc719..b6578261e 100644
--- a/ts/packages/providers/langchain/test/langchain.test.ts
+++ b/ts/packages/providers/langchain/test/langchain.test.ts
@@ -6,7 +6,7 @@ import { DynamicStructuredTool } from '@langchain/core/tools';
describe('LangchainProvider', () => {
let provider: LangchainProvider;
let sampleTool: Tool;
- let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<any>;
+ let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<unknown>;
beforeEach(() => {
provider = new LangchainProvider();
diff --git a/ts/packages/providers/llamaindex/test/llamaindex.test.ts b/ts/packages/providers/llamaindex/test/llamaindex.test.ts
index 99f8d9211..07eaf745c 100644
--- a/ts/packages/providers/llamaindex/test/llamaindex.test.ts
+++ b/ts/packages/providers/llamaindex/test/llamaindex.test.ts
@@ -23,7 +23,7 @@ vi.mock('llamaindex', () => {
describe('LlamaindexProvider', () => {
let provider: LlamaindexProvider;
let sampleTool: Tool;
- let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<any>;
+ let executeToolFn: (toolSlug: string, params: Record<string, unknown>) => Promise<unknown>;
beforeEach(() => {
provider = new LlamaindexProvider();
diff --git a/ts/packages/providers/mastra/test/mastra.test.ts b/ts/packages/providers/mastra/test/mastra.test.ts
index 910fdeed7..bfbc88a10 100644
--- a/ts/packages/providers/mastra/test/mastra.test.ts
+++ b/ts/packages/providers/mastra/test/mastra.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import { MastraProvider } from '../src';
import { Tool } from '@composio/core';
import { createTool } from '@mastra/core/tools';
@@ -7,12 +7,21 @@ import { createTool } from '@mastra/core/tools';
interface MockedMastraTool {
id: string;
description: string;
- inputSchema?: any;
- outputSchema?: any;
+ inputSchema?: unknown;
+ outputSchema?: unknown;
execute: Function;
_isMockedMastraTool: boolean;
}
+// Minimal shape of the config object the wrapped tool's `execute` closure is
+// pulled off of, i.e. the argument the mocked `createTool` factory (below) was
+// called with. Only `execute` is dereferenced at the `.mock.calls[...][0]`
+// call sites in this file, so that's all this type declares.
+type CreateToolMockConfig = { execute: (...args: unknown[]) => unknown };
+type CreateToolMock = Mock<(config: CreateToolMockConfig) => unknown>;
+const getCreatedToolExecute = () =>
+ (createTool as unknown as CreateToolMock).mock.calls[0][0].execute;
+
// Mock the @mastra/core/tools module
vi.mock('@mastra/core/tools', () => {
return {
@@ -61,7 +70,7 @@ const RELAXED_MOCK_OUTPUT_SCHEMA = {
describe('MastraProvider', () => {
let provider: MastraProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: Mock;
beforeEach(() => {
provider = new MastraProvider();
@@ -226,7 +235,7 @@ describe('MastraProvider', () => {
provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
// Extract the execute function from the call to createTool()
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
// Test the execute function
const inputData = { input: 'test-value' };
@@ -245,7 +254,7 @@ describe('MastraProvider', () => {
provider.wrapTool(toolWithVersion, mockExecuteToolFn) as unknown as MockedMastraTool;
// Extract the execute function from the call to createTool()
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
// Test that the version is passed correctly
const inputData = { input: 'version-test' };
@@ -259,7 +268,7 @@ describe('MastraProvider', () => {
provider.wrapTool(toolWithoutVersion, mockExecuteToolFn) as unknown as MockedMastraTool;
// Extract the execute function from the call to createTool()
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
// Test that undefined version is passed correctly
const inputData = { input: 'no-version-test' };
@@ -272,7 +281,7 @@ describe('MastraProvider', () => {
provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
// Extract the execute function from the call to createTool()
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
// Test the execute function with empty input
const result = await executeFunction({});
@@ -289,7 +298,7 @@ describe('MastraProvider', () => {
provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
// Extract the execute function from the call to createTool()
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
// Test the execute function without any parameters: a missing payload is
// normalized to an empty object rather than forwarded as undefined (issue #2406).
@@ -487,7 +496,7 @@ describe('MastraProvider', () => {
mockTool,
errorExecuteToolFn
) as unknown as MockedMastraTool;
- const executeFunction = (createTool as any).mock.calls[0][0].execute;
+ const executeFunction = getCreatedToolExecute();
await expect(executeFunction({ input: 'test' })).rejects.toThrow('Execution failed');
});
@@ -495,7 +504,7 @@ describe('MastraProvider', () => {
it('should handle tools with malformed schemas', () => {
const toolWithMalformedSchema: Tool = {
...mockTool,
- inputParameters: null as any,
+ inputParameters: null as unknown,
outputParameters: undefined,
};
@@ -639,7 +648,7 @@ describe('MastraProvider', () => {
inputParameters: {
type: 'string',
description: 'A string parameter',
- } as any,
+ } as unknown,
};
strictProvider.wrapTool(toolWithNonObjectParams, mockExecuteToolFn);
diff --git a/ts/packages/providers/openai-agents/test/openai-agents.test.ts b/ts/packages/providers/openai-agents/test/openai-agents.test.ts
index 09cc097da..49d8a5bfc 100644
--- a/ts/packages/providers/openai-agents/test/openai-agents.test.ts
+++ b/ts/packages/providers/openai-agents/test/openai-agents.test.ts
@@ -7,7 +7,7 @@ import { tool as createOpenAIAgentTool } from '@openai/agents';
interface MockedOpenAIAgentTool {
name: string;
description: string;
- parameters: any;
+ parameters: unknown;
execute: Function;
_isMockedOpenAIAgentTool: boolean;
}
@@ -27,7 +27,7 @@ vi.mock('@openai/agents', () => {
describe('OpenAIAgentsProvider', () => {
let provider: OpenAIAgentsProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new OpenAIAgentsProvider();
diff --git a/ts/packages/providers/openai/test/opeanai-responses.test.ts b/ts/packages/providers/openai/test/opeanai-responses.test.ts
index a3a747d56..63b1ab58e 100644
--- a/ts/packages/providers/openai/test/opeanai-responses.test.ts
+++ b/ts/packages/providers/openai/test/opeanai-responses.test.ts
@@ -28,14 +28,14 @@ interface MockedOpenAITool {
type: 'function';
name: string;
description?: string;
- parameters?: any;
+ parameters?: unknown;
strict?: boolean;
}
describe('OpenAIResponsesProvider', () => {
let provider: OpenAIResponsesProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new OpenAIResponsesProvider();
diff --git a/ts/packages/providers/openai/test/openai.test.ts b/ts/packages/providers/openai/test/openai.test.ts
index 02501d1a5..3473c0bcc 100644
--- a/ts/packages/providers/openai/test/openai.test.ts
+++ b/ts/packages/providers/openai/test/openai.test.ts
@@ -37,14 +37,14 @@ interface MockedOpenAIChatCompletionTool {
function: {
name: string;
description?: string;
- parameters?: any;
+ parameters?: unknown;
};
}
describe('OpenAIProvider', () => {
let provider: OpenAIProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: unknown;
beforeEach(() => {
provider = new OpenAIProvider();
diff --git a/ts/packages/providers/vercel/test/vercel.test.ts b/ts/packages/providers/vercel/test/vercel.test.ts
index 160893afb..4545aecf6 100644
--- a/ts/packages/providers/vercel/test/vercel.test.ts
+++ b/ts/packages/providers/vercel/test/vercel.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import { VercelProvider } from '../src';
import { Tool } from '@composio/core';
import { tool } from 'ai';
@@ -6,7 +6,7 @@ import { tool } from 'ai';
// Define an interface for our mocked Vercel tool
interface MockedVercelTool {
description: string;
- inputSchema: any;
+ inputSchema: unknown;
execute: Function;
_isMockedVercelTool: boolean;
}
@@ -27,7 +27,7 @@ vi.mock('ai', () => {
describe('VercelProvider', () => {
let provider: VercelProvider;
let mockTool: Tool;
- let mockExecuteToolFn: any;
+ let mockExecuteToolFn: Mock;
beforeEach(() => {
provider = new VercelProvider();
@@ -114,7 +114,11 @@ describe('VercelProvider', () => {
provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedVercelTool;
// Extract the execute function from the call to tool()
- const executeFunction = (tool as any).mock.calls[0][0].execute;
+ const executeFunction = (
+ tool as unknown as Mock<
+ (config: { execute: (input: unknown) => Promise<unknown> }) => unknown
+ >
+ ).mock.calls[0][0].execute;
// Test the execute function with an object parameter
const params = { input: 'test-value' };
diff --git a/ts/packages/ts-builders/src/File.ts b/ts/packages/ts-builders/src/File.ts
index 784d83c40..b1e0a55d4 100644
--- a/ts/packages/ts-builders/src/File.ts
+++ b/ts/packages/ts-builders/src/File.ts
@@ -6,8 +6,8 @@ import type { ExportFrom } from './ExportFrom';
import type { Import } from './Import';
import { Writer } from './Writer';
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type FileItem = AnyDeclarationBuilder | Export<any> | ExportFrom | DocSectionComment;
+export type FileItem =
+ AnyDeclarationBuilder | Export<AnyDeclarationBuilder> | ExportFrom | DocSectionComment;
export class File implements BasicBuilder {
private imports: Import[] = [];
private declarations: FileItem[] = [];