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

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

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

Synced Nov 21, 09:45 UTC

fix(cli): keep drift-tolerant reads lenient and align the agent guidance (#4878)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4853 and the Effect idioms PR stacked on it - reads `logs.tools.list` and `logs.tools.retrieve` without client validation, as https://github.com/ComposioHQ/composio/pull/4853 already does for trigger logs: the client schema fixes `status` to `success|failed` while the formatter renders a dash for anything else - reads `toolRouter.session.search`, `toolRouter.session.toolkits`, `tools.list` and `org.project.list` without client validation: each command consumes a handful of fields, and the schemas carry enum literals (`account_type`, `account_selection`, `webhook_version`) the backend can extend without a CLI release - keeps client decoding for `org.list`, `org.consumer.listConnectedToolkits` and `cli.realtime.credentials`, whose responses are consumed whole and carry no enum literals; the loader table and its test shrink to those three - renames the "Effect safety and migration seams" section of the CLI agent guidance, adds `getProjectToolkits` to the client cache sync list, and makes the `composio-clients.ts`, raw `fetch` and decode-policy sentences match the code ## Context A review of https://github.com/ComposioHQ/composio/pull/4853 found that strict decoding on these reads turns a single drifted row (a new status value, a null account id) into an exit 1 with the `composio upgrade` hint, which contradicts the goal of unchanged command output. The decode policy is now: validate with the client only where the CLI depends on the full response shape. Verified locally: `pnpm typecheck`, the CLI suite (146 files, 1481 passed, 1 skipped), `oxlint` on `ts/packages/cli`, `validate:boundaries`, `validate:agent-skills`, `validate:skill-routing`, `check-examples.mjs`.

Alberto Schiabel committed Oct 15, 2026 at 15:21 UTC 7d14952f17d193fae4fbfb2d095d141adcd0f8f7
14 files changed +278 -81
.agents/skills/cli-command/references/client-cache-sync.md
+1 -1
@@ -1,6 +1,6 @@
1 # Client Cache Sync
2
3 -`ts/packages/cli/src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` from `ts/packages/cli/src/services/composio-clients.ts` and overrides only the methods it caches: `getToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, and `getTools`.
3 +`ts/packages/cli/src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` from `ts/packages/cli/src/services/composio-clients.ts` and overrides only the methods it caches: `getToolkits`, `getProjectToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, and `getTools`.
4
5 Checklist:
6
.agents/skills/effect-v4/references/core-patterns.md
+1 -1
@@ -82,7 +82,7 @@ file), not the bare class name.
82 ## Errors: `Data.TaggedError` (default) and `Schema.TaggedError` (schema-backed)
83
84 The established convention in this repo — stated in `ts/packages/cli/AGENTS.md`'s
85 -"Effect safety and migration seams" section — is: never wrap a plain `Error` in
85 +"Effect safety and migration boundaries" section — is: never wrap a plain `Error` in
86 `Effect.fail` for an expected failure; give it a `Data.TaggedError` with structured
87 fields and a preserved cause, then recover with `catchTag`/`catchTags`. This is
88 unchanged from v3 and is what nearly every error in `src/services/*.ts` uses, e.g.
ts/packages/cli/AGENTS.md
+5 -5
@@ -74,7 +74,7 @@ Named options use `Flag.String()`, `Flag.Boolean()`, `Flag.Int()`, `Flag.Literal
74 | `JsPackageManagerDetector` | Detects npm/pnpm/yarn/bun for install instructions |
75 | `UpgradeBinary` | Fetches latest release from GitHub, downloads and replaces binary |
76
77 -Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with `deprecationNotices: 'off'`, the CLI's own `defaultHeaders` (provenance headers, `x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. `composio-clients.ts` holds only client construction and the two repositories. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `undecoded` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
77 +Every Composio API request goes through an Effect client from `@composio/client/effect`, obtained from `ComposioClientSingleton` (`src/services/composio-clients.ts`). Clients are built with `make`, which never reads the ambient environment: the user key and base URL come from the CLI's own configuration. Each client is built with `deprecationNotices: 'off'`, the CLI's own `defaultHeaders` (provenance headers, `x-user-api-key`, plus `x-org-id`/`x-project-id` when both are known), and a counting `fetch` (`composio-client-metrics.ts`) provided as the transport's `FetchHttpClient.Fetch`. Explicitly configured HTTP base URLs remain supported without an additional environment flag. `composio-clients.ts` holds client construction, the two repositories, and the `collectAll` and `sortBySlug` helpers the catalog fetches share. The repository's auth-config, connected-account, trigger-instance, search, and single-item methods live in `src/services/composio-resource-operations.ts`; the account helpers (`listOrganizations`, `getSessionInfo*`, `resolveConsumerProject`, `createProjectApiKey`, `getLatestToolVersion`, …) in `src/services/composio-account.ts`; toolkit version validation and its errors (`InvalidToolkitsError`, `InvalidToolkitVersionsError`) in `src/services/toolkit-version-validation.ts`; the shared error types (`ClientError`, `HttpDecodingError`, `ComposioClientConfigurationError`) in `src/services/composio-errors.ts`; and the shared `decode` helper and `undecoded` request option in `src/services/composio-request.ts`. There is no CLI error wrapper around a request: the client's tagged errors (`@composio/client/NotFoundError`, `APIConnectionError`, `DecodeError`, …) flow to callers, which recover with `Effect.catchTag` or the client's `isAPIError` guard. Commands that report an API failure and continue with a fallback share one handler, `handleClientApiError` (`src/effects/handle-http-error.ts`), applied with `Effect.catchTag(CLIENT_API_ERROR_TAGS, …)`; the tag list lives in `src/services/composio-errors.ts`. Endpoints the client does not type use the raw `client.get`/`client.post`; `src/services/tool-permissions.ts` reaches them through its own `requestJson`, which raises `services/ToolPermissionsRequestError` because its callers fail closed on that tag. Do not add a raw `fetch` to the Composio backend from `src/commands`, `src/effects`, or `src/services` — the one sanctioned exception is the bundled companion runtime (`run-helpers-runtime.ts`), which runs in the user's spawned process outside the Effect runtime. (`src/services/agents.ts` also calls `fetch`, against the agents service at agents.composio.dev rather than the Composio backend.) oxlint rejects value imports of the `@composio/client` root and `@composio/client/pagination` from CLI `src/`; type-only imports are allowed. Client errors are classified for display by `src/utils/api-error-extraction.ts`.
78
79 Services are `Context.Service` classes that export a `<Name>Shape` type and an explicit `static readonly Default` layer (`Layer.effect` / `Layer.sync`, dependencies provided with `Layer.provide`). Build a test double with `Service.of({ ... })`; there are no generated accessors or constructors.
80
@@ -165,11 +165,11 @@ const cases = pipe(
165
166 Each `Arr.bind` adds one independent axis to the generated cases.
167
168 -### Effect safety and migration seams
168 +### Effect safety and migration boundaries
169
170 - Never branch on an Effect value's internal tag field directly. Use the owning module's public refinement or matcher (`Option`, `Result`, `Exit`, `Cause`, `CliError`), `Match.valueTags` for exhaustive unions, or `Predicate.isTagged` for a single narrowing guard.
171 - Do not wrap a plain `Error` in `Effect.fail` for expected failures. Give the failure a meaningful `Data.TaggedError` type with structured fields and a preserved cause, then recover with `catchTag` / `catchTags`. Reserve `Effect.die` and `Effect.dieMessage` for impossible invariants.
172 -- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls pass `decode: false` and decode with the CLI schema, failing with `services/HttpDecodingError`. The client's generated schema validates every other read, through the loader table in `src/services/composio-schema-loaders.ts`; a mismatch fails with the client's `DecodeError`. Calls that are not reads pass `decode: false`, because failing after the server acted would invite a retry that repeats the side effect, and so do the two endpoints the CLI reads leniently on purpose (`connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). A typed call with no loader and no `decode: false` fails before it is sent, so adding a client-decoded read means adding its loader to the table. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
172 +- Treat `unknown`, JSON, and persisted state as trust boundaries. Decode them with `effect/Schema` or narrow them with `Predicate`; an `as` assertion is not validation, and hand-rolled structural guards (`'x' in obj` / `typeof` chains) are not a substitute for a schema. Each typed API response is validated at most once. The CLI's own schema validates a response the CLI transforms, filters for stdout, or writes to a cache file: the catalog models (`src/models/toolkits.ts`, `tools.ts`, `trigger-types.ts`), the auth-config and connected-account allowlists that keep credential-bearing fields off stdout (including the list responses and the `auth-configs create` response in `src/models/auth-configs.ts` and `connected-accounts.ts`), the `ToolkitSlug` path-safety check, the `Session` `DateTime` transform, and `TriggerInstanceItems`. Those calls pass `decode: false` and decode with the CLI schema, failing with `services/HttpDecodingError`. The client's generated schema validates a read only where the CLI consumes the whole response through the client's types and no field of it may drift: `cli.realtime.credentials` (every field feeds the realtime connection), `org.list` (organization ids and names for login), and `org.consumer.listConnectedToolkits` (a list of slugs). Those three are the loader table in `src/services/composio-schema-loaders.ts`; a mismatch fails with the client's `DecodeError`. Every other typed call passes `undecoded` (`decode: false`): calls that are not reads, because failing after the server acted would invite a retry that repeats the side effect; reads the CLI validates with its own schema; and reads that must tolerate drift because the CLI consumes a few fields of a response whose client schema fixes enums or requires fields the CLI never reads (`logs.tools.*`, `logs.triggers.*`, `tools.list`, `tools.retrieve`, `org.project.list`, `toolRouter.session.search`, `toolRouter.session.toolkits`, `connectedAccounts.list`, which tolerates unknown statuses, and `triggerInstances.listActive`, whose page counts the CLI defaults). A typed call with no loader and no `decode: false` fails before it is sent, so adding a client-decoded read means adding its loader to the table and saying in its doc comment why the CLI cannot tolerate drift there. Responses fetched with the raw `client.get`/`client.post` are untyped and always need a CLI schema (`LatestToolVersionResponse` in `src/models/tools.ts`, and the consumer config and permission payloads in `tool-permissions.ts`). `effect/Schema` is the CLI's schema tool — do not introduce zod here (zod is the convention in the SDK packages and docs).
173 - Do not inspect private `effect/cli` internals (parser state, `HelpDoc` string shapes, `CliError` suggestion machinery). `Command.runWith` renders help and parse/validation errors itself — see the entry-point section above — so command-tree introspection must stay on the public `Command.Any` surface (`name`, `alias`, `subcommands`). `CliError.InvalidValue` takes structured `{ option, value, expected, kind }` fields, not a free-form message — commands that need a custom validation message raise a local `Data.TaggedError` instead (see `src/commands/login.cmd.ts`'s `LoginOptionError`) and let it flow through the existing `effect-errors` pretty-printer, not a hand-built `CliError`.
174 - Prefer `Effect.mapError`, `Effect.matchEffect`, and typed recovery over `Effect.catch` blocks (the v4 name for what was `Effect.catchAll`) that flatten distinct failures into one message-only error.
175
@@ -223,7 +223,7 @@ Use these when adding new commands or making UX decisions.
223
224 ## Client Cache Sync
225
226 -`src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` and overrides only the methods it caches (`getToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, `getTools`). Adding a passthrough method to the repository needs no edit there. Edit the cached file in the same change only when a cached method's signature or result changes, or when a new full-catalog fetch should be cached. Validation, search, single-item, and CRUD methods stay passthrough.
226 +`src/services/composio-clients-cached.ts` spreads the underlying `ComposioToolkitsRepository` and overrides only the methods it caches (`getToolkits`, `getProjectToolkits`, `getToolkitsBySlugs`, `getToolsAsEnums`, `getTriggerTypesAsEnums`, `getTriggerTypes`, `getTools`). Adding a passthrough method to the repository needs no edit there. Edit the cached file in the same change only when a cached method's signature or result changes, or when a new full-catalog fetch should be cached. Validation, search, single-item, and CRUD methods stay passthrough.
227
228 ## Recording CLI Demos
229
@@ -240,7 +240,7 @@ Use the repo-local `cli-release` skill before building or publishing first-party
240
241 - A push to `next` touching CLI paths publishes a rolling beta automatically.
242 - The normal stable path promotes an existing tested beta through the `promote-stable` workflow action.
243 -- `@composio/cli` is ignored by Changesets. Never add a changeset targeting it; it wedges the TypeScript SDK release action. Put human-facing CLI notes in `CHANGELOG.md` directly.
243 +- `@composio/cli` is ignored by Changesets. Never add a changeset targeting it; it stalls the TypeScript SDK release action. Put human-facing CLI notes in `CHANGELOG.md` directly.
244 - `package.json` uses a private development sentinel and is never a
245 binary-release authority. For an intentional minor or major release,
246 dispatch `build-beta` with its optional version input, verify that beta, then
ts/packages/cli/src/commands/logs-cmd/commands/logs.tools.cmd.ts
+13 -9
@@ -3,6 +3,7 @@ import { Data, Effect, Option } from 'effect';
3 import { requireAuth } from 'src/effects/require-auth';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 import { ComposioClientSingleton } from 'src/services/composio-clients';
6 +import { undecoded } from 'src/services/composio-request';
7 import { clampLimit } from 'src/ui/clamp-limit';
8 import { parseCsv } from 'src/commands/triggers/parse-csv';
9 import { formatToolLogInfo, formatToolLogsTable } from '../format';
@@ -190,7 +191,7 @@ export const logsCmd$Tools = Command.make(
191 if (toolLogId) {
192 const toolLog = yield* ui.withSpinner(
193 `Fetching tool log "${toolLogId}"...`,
193 - client.logs.tools.retrieve(toolLogId).pipe(
194 + client.logs.tools.retrieve(toolLogId, undecoded).pipe(
195 Effect.mapError(
196 cause =>
197 new ToolLogsRequestError({
@@ -211,14 +212,17 @@ export const logsCmd$Tools = Command.make(
212 const response = yield* ui.withSpinner(
213 'Fetching tool logs...',
214 client.logs.tools
214 - .list({
215 - cursor: Option.getOrUndefined(cursor) ?? null,
216 - from: Option.getOrUndefined(from),
217 - to: Option.getOrUndefined(to),
218 - limit: clampedLimit,
219 - case_sensitive: caseSensitive,
220 - search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
221 - })
215 + .list(
216 + {
217 + cursor: Option.getOrUndefined(cursor) ?? null,
218 + from: Option.getOrUndefined(from),
219 + to: Option.getOrUndefined(to),
220 + limit: clampedLimit,
221 + case_sensitive: caseSensitive,
222 + search_params: shorthandSearchParams.length > 0 ? shorthandSearchParams : undefined,
223 + },
224 + undecoded
225 + )
226 .pipe(
227 Effect.mapError(
228 cause =>
ts/packages/cli/src/commands/toolkits/commands/toolkits.info.cmd.ts
+3 -1
@@ -2,6 +2,7 @@ import { Argument, Command, Flag } from 'effect/cli';
2 import { Data, Effect, Option } from 'effect';
3 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
4 import { TerminalUI } from 'src/services/terminal-ui';
5 +import { undecoded } from 'src/services/composio-request';
6 import { requireAuth } from 'src/effects/require-auth';
7 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
8 import { extractMessage } from 'src/utils/api-error-extraction';
@@ -94,7 +95,8 @@ export const toolkitsCmd$Info = Command.make(
95 const client = yield* clientSingleton.get();
96 const { sessionId } = yield* resolveToolRouterSession(client, resolvedUserId.value);
97 const sessionToolkits = yield* client.toolRouter.session
97 - .toolkits(sessionId, { toolkits: [slugValue] })
98 + // Only the first item is read, and only a few of its fields.
99 + .toolkits(sessionId, { toolkits: [slugValue] }, undecoded)
100 .pipe(
101 Effect.mapError(
102 cause =>
ts/packages/cli/src/commands/toolkits/commands/toolkits.list.cmd.ts
+12 -5
@@ -5,6 +5,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
5 import { requireAuth } from 'src/effects/require-auth';
6 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
7 import { ComposioClientSingleton, ComposioToolkitsRepository } from 'src/services/composio-clients';
8 +import { undecoded } from 'src/services/composio-request';
9 import { ProjectContext } from 'src/services/project-context';
10 import { ComposioUserContext } from 'src/services/user-context';
11 import { clampLimit } from 'src/ui/clamp-limit';
@@ -130,12 +131,18 @@ export const toolkitsCmd$List = Command.make(
131 let sessionFailed = false;
132 if (sessionContext) {
133 const { client, sessionId } = sessionContext;
134 + // The session items only add connection status to the catalog rows,
135 + // and a failed read is already a silent fallback.
136 sessionItems = yield* client.toolRouter.session
134 - .toolkits(sessionId, {
135 - search: Option.getOrUndefined(query),
136 - limit: clampedLimit,
137 - is_connected: Option.getOrUndefined(connected),
138 - })
137 + .toolkits(
138 + sessionId,
139 + {
140 + search: Option.getOrUndefined(query),
141 + limit: clampedLimit,
142 + is_connected: Option.getOrUndefined(connected),
143 + },
144 + undecoded
145 + )
146 .pipe(
147 Effect.mapError(
148 cause =>
ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+14 -9
@@ -11,6 +11,7 @@ import { formatToolsTable } from '../format';
11 import type { Tool } from 'src/models/tools';
12 import { ComposioUserContext } from 'src/services/user-context';
13 import { ComposioClientSingleton } from 'src/services/composio-clients';
14 +import { undecoded } from 'src/services/composio-request';
15 import {
16 resolveCommandProject,
17 formatResolveCommandProjectError,
@@ -374,15 +375,19 @@ const runToolsSearch = (params: {
375 const searchPayload = {
376 queries: queries.map(query => ({ use_case: query })),
377 };
377 - const searchResponse = yield* client.toolRouter.session.search(sessionId, searchPayload).pipe(
378 - Effect.mapError(
379 - cause =>
380 - new ToolsSearchRequestError({
381 - message: 'Failed to search tools.',
382 - cause,
383 - })
384 - )
385 - );
378 + // The command reads a few of the search response's fields; the rest, enums
379 + // among them, may change without this version of the CLI noticing.
380 + const searchResponse = yield* client.toolRouter.session
381 + .search(sessionId, searchPayload, undecoded)
382 + .pipe(
383 + Effect.mapError(
384 + cause =>
385 + new ToolsSearchRequestError({
386 + message: 'Failed to search tools.',
387 + cause,
388 + })
389 + )
390 + );
391 const customToolSlugsMissingSchemas = Object.entries(searchResponse.tool_schemas)
392 .filter(([slug, schema]) => isRemoteCustomToolSlug(slug) && !schema.input_schema)
393 .map(([slug]) => slug);
ts/packages/cli/src/services/composio-account.ts
+6 -2
@@ -126,6 +126,10 @@ export const listOrganizations = (params: {
126
127 /**
128 * Lists projects for a specific organization.
129 + *
130 + * Project lists are not client-decoded: the CLI reads a project's ids, name,
131 + * and email, while the client schema also fixes `webhook_version` to the
132 + * versions it knew at generation time.
133 */
134 export const listOrganizationProjects = (params: {
135 apiKey: string;
@@ -137,7 +141,7 @@ export const listOrganizationProjects = (params: {
141 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
142 const response = yield* client.org.project.list(
143 { limit: params.limit ?? 50 },
140 - orgScopedOptions(params.orgId)
144 + { ...undecoded, ...orgScopedOptions(params.orgId) }
145 );
146 const projects = response.data.map(
147 (project: OrgProject) =>
@@ -167,7 +171,7 @@ export const listOrgProjects = (params: {
171 const client = yield* clientSingleton.getFor({ userApiKey: params.apiKey });
172 return yield* client.org.project.list(
173 { list_all_org_projects: true, limit: params.limit ?? 50 },
170 - orgScopedOptions(params.orgId)
174 + { ...undecoded, ...orgScopedOptions(params.orgId) }
175 );
176 });
177
ts/packages/cli/src/services/composio-resource-operations.ts
+15 -8
@@ -219,6 +219,10 @@ export const lookupOperations = (client: Effect.Effect<ComposioClientShape, Clie
219 /**
220 * Searches tools with optional filters. Returns a single page of results.
221 * @param params - Search/filter parameters
222 + *
223 + * Not client-decoded: `tools list` prints the slug, name, and description of
224 + * each item and `tools info` suggests slugs from them, so drift in any other
225 + * field of a tool must not fail the listing.
226 */
227 searchTools: (params: {
228 search?: string;
@@ -228,14 +232,17 @@ export const lookupOperations = (client: Effect.Effect<ComposioClientShape, Clie
232 cursor?: string;
233 }) =>
234 Effect.flatMap(client, c =>
231 - c.tools.list({
232 - search: params.search,
233 - toolkit_slug: params.toolkit_slug,
234 - tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
235 - limit: params.limit,
236 - cursor: params.cursor,
237 - toolkit_versions: 'latest',
238 - })
235 + c.tools.list(
236 + {
237 + search: params.search,
238 + toolkit_slug: params.toolkit_slug,
239 + tags: params.tags ? params.tags.split(',').map(t => t.trim()) : undefined,
240 + limit: params.limit,
241 + cursor: params.cursor,
242 + toolkit_versions: 'latest',
243 + },
244 + undecoded
245 + )
246 ),
247 /**
248 * Retrieves detailed info about a single tool by slug.
ts/packages/cli/src/services/composio-schema-loaders.ts
-14
@@ -14,23 +14,9 @@ export const composioSchemaLoaders = {
14 'cli.realtime.credentials': async () =>
15 (await import('@composio/client/effect/schemas/cli/realtime/credentials'))
16 .RealtimeCredentialsResponse,
17 - 'logs.tools.list': async () =>
18 - (await import('@composio/client/effect/schemas/logs/tools/list')).ToolListResponse,
19 - 'logs.tools.retrieve': async () =>
20 - (await import('@composio/client/effect/schemas/logs/tools/retrieve')).ToolRetrieveResponse,
17 'org.consumer.listConnectedToolkits': async () =>
18 (await import('@composio/client/effect/schemas/org/consumer/list-connected-toolkits'))
19 .ConsumerListConnectedToolkitsResponse,
20 'org.list': async () =>
21 (await import('@composio/client/effect/schemas/org/list')).OrgListResponse,
26 - 'org.project.list': async () =>
27 - (await import('@composio/client/effect/schemas/org/project/list')).ProjectListResponse,
28 - 'toolRouter.session.search': async () =>
29 - (await import('@composio/client/effect/schemas/tool-router/session/search'))
30 - .SessionSearchResponse,
31 - 'toolRouter.session.toolkits': async () =>
32 - (await import('@composio/client/effect/schemas/tool-router/session/toolkits'))
33 - .SessionToolkitsResponse,
34 - 'tools.list': async () =>
35 - (await import('@composio/client/effect/schemas/tools/list')).ToolListResponse,
22 } satisfies SchemaLoaders;
ts/packages/cli/test/src/commands/logs-cmd/logs.tools.client.cmd.test.ts
+58 -13
@@ -98,22 +98,67 @@ describe('CLI: composio dev logs tools over the API client', () => {
98 );
99 });
100
101 - layer(testLayer)('[Given] a page in a shape the API contract does not allow', it => {
102 - it.effect('[Then] the command fails naming the operation and suggests an upgrade', () =>
101 + layer(testLayer)('[Given] a page with a log in a shape the API contract does not allow', it => {
102 + it.effect('[Then] the log is listed with dashes for what it lacks', () =>
103 Effect.gen(function* () {
104 - const stub = stubClientResources(['logs'], () =>
105 - // No `nextCursor`, which the API's response schema requires.
106 - Response.json({ data: [] }, { headers: { 'x-request-id': 'req_logs' } })
107 - );
108 - const exit = yield* cli(['dev', 'logs', 'tools']).pipe(
109 - Effect.provide(stub.layer),
110 - Effect.exit
111 - );
112 - const failure = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
104 + // A null status, a missing connected account, a missing execution
105 + // time, and no `nextCursor`: the response schema the client ships
106 + // allows none of that, while the table renders each as a dash.
107 + const driftedPage = {
108 + data: [
109 + {
110 + id: 'log_drift_1',
111 + actionKey: 'GMAIL_SEND_EMAIL',
112 + appKey: 'gmail',
113 + app: { icon: null, name: 'Gmail' },
114 + connectedAccountId: null,
115 + entityId: 'user_1',
116 + status: null,
117 + createdAt: 1767225600000,
118 + },
119 + ],
120 + };
121 + const stub = stubClientResources(['logs'], () => Response.json(driftedPage));
122 + yield* cli(['dev', 'logs', 'tools']).pipe(Effect.provide(stub.layer));
123 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
124
114 - expect(extractErrorDetails(failure).message).toBe(
115 - "Failed to fetch tool logs.\nCaused by: The API response for 'logs.tools.list' is not in the shape this version of the CLI expects (request id: req_logs).\nUpgrade the CLI, then retry:\n> composio upgrade"
125 + expect(lines[1]).toBe(
126 + [
127 + 'Listing 1 tool log',
128 + '',
129 + 'Created At Log Id Status Toolkit Tool Exec Time Connected Account',
130 + '2026-01-01T00:00:00.000Z log_drift_1 - Gmail GMAIL_SEND_EMAIL 0ms -',
131 + ].join('\n')
132 );
133 + expect(lines.at(-1)).toBe(JSON.stringify(driftedPage, null, 2));
134 + })
135 + );
136 + });
137 +
138 + layer(testLayer)('[Given] one tool log in a shape the API contract does not allow', it => {
139 + it.effect('[Then] its details are shown and it is printed as the API returned it', () =>
140 + Effect.gen(function* () {
141 + const driftedLog = {
142 + id: 'log_drift_1',
143 + actionKey: 'GMAIL_SEND_EMAIL',
144 + appKey: 'gmail',
145 + app: { icon: null, name: 'Gmail' },
146 + connectedAccountId: null,
147 + entityId: 'user_1',
148 + status: null,
149 + createdAt: 1767225600000,
150 + payloadReceived: { recipient_email: 'a@b.c' },
151 + response: { id: 'msg_1' },
152 + };
153 + const stub = stubClientResources(['logs'], () => Response.json(driftedLog));
154 + yield* cli(['dev', 'logs', 'tools', 'log_drift_1']).pipe(Effect.provide(stub.layer));
155 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
156 +
157 + expect(lines.join('\n')).toContain('GMAIL_SEND_EMAIL');
158 + expect(lines.at(-1)).toBe(JSON.stringify(driftedLog, null, 2));
159 + expect(stub.requests).toEqual([
160 + { method: 'GET', path: '/api/v3.1/internal/action_execution/log/log_drift_1' },
161 + ]);
162 })
163 );
164 });
ts/packages/cli/test/src/commands/toolkits/toolkits.info.client.cmd.test.ts new
+95
@@ -0,0 +1,95 @@
1 +import { describe, expect, layer } from '@effect/vitest';
2 +import { ConfigProvider, DateTime, Effect } from 'effect';
3 +import type { ToolkitDetailed } from 'src/models/toolkits';
4 +import { cli, MockConsole, TestLive } from 'test/__utils__';
5 +import {
6 + stubClientResources,
7 + type StubRequest,
8 +} from 'test/__utils__/services/stub-composio-client';
9 +
10 +const gmail: ToolkitDetailed = {
11 + name: 'Gmail',
12 + slug: 'gmail',
13 + is_local_toolkit: false,
14 + composio_managed_auth_schemes: ['OAUTH2'],
15 + no_auth: false,
16 + meta: {
17 + description: 'Email service to send and receive emails',
18 + categories: [],
19 + created_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
20 + updated_at: DateTime.makeUnsafe('2024-05-03T11:44:32.061Z'),
21 + available_versions: ['20250101'],
22 + tools_count: 36,
23 + triggers_count: 2,
24 + },
25 + auth_config_details: [],
26 +};
27 +
28 +const testLayer = TestLive({
29 + baseConfigProvider: ConfigProvider.fromEnv({ env: { COMPOSIO_USER_API_KEY: 'test_api_key' } }),
30 + fixture: 'global-test-user-id',
31 + toolkitsData: { detailedToolkits: [gmail] },
32 +});
33 +
34 +const isToolkits = (request: StubRequest) => request.path.includes('/toolkits');
35 +
36 +/** Session toolkit reads answered by `respond`; the session they run in is created normally. */
37 +const toolkitsOver = (respond: () => Response) =>
38 + stubClientResources(['toolRouter'], request =>
39 + isToolkits(request)
40 + ? respond()
41 + : Response.json({
42 + session_id: 'trs_stub_session',
43 + config: { user_id: 'global-default' },
44 + mcp: { type: 'http', url: 'https://mcp.stub.invalid' },
45 + tool_router_tools: [],
46 + })
47 + );
48 +
49 +describe('CLI: composio dev toolkits info over the API client', () => {
50 + layer(testLayer)('[Given] a session toolkit in a shape the API contract does not allow', it => {
51 + it.effect('[Then] the toolkit and its connection are shown', () =>
52 + Effect.gen(function* () {
53 + // No `meta.logo`, no page counts, and a connected account without
54 + // `created_at` or `auth_config`.
55 + const page = {
56 + items: [
57 + {
58 + name: 'Gmail',
59 + slug: 'gmail',
60 + enabled: true,
61 + is_no_auth: false,
62 + composio_managed_auth_schemes: ['OAUTH2'],
63 + meta: { description: 'Email service to send and receive emails' },
64 + connected_account: { id: 'ca_gmail_1', user_id: 'global-default', status: 'ACTIVE' },
65 + },
66 + ],
67 + next_cursor: null,
68 + };
69 + const stub = toolkitsOver(() => Response.json(page));
70 + yield* cli(['dev', 'toolkits', 'info', 'gmail']).pipe(Effect.provide(stub.layer));
71 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
72 + const output = lines.join('\n');
73 +
74 + expect(output).toContain('Connection Status: ACTIVE');
75 + expect(output).toContain('Connected Account ID: ca_gmail_1');
76 + expect(output).toContain('Auth Scheme: -');
77 + expect(JSON.parse(lines.at(-1) ?? '{}')).toMatchObject({
78 + slug: 'gmail',
79 + connected_account: {
80 + status: 'ACTIVE',
81 + id: 'ca_gmail_1',
82 + auth_scheme: null,
83 + is_composio_managed: null,
84 + },
85 + });
86 + expect(stub.requests.filter(isToolkits)).toEqual([
87 + {
88 + method: 'GET',
89 + path: '/api/v3.1/tool_router/session/trs_stub_session/toolkits?toolkits=gmail',
90 + },
91 + ]);
92 + })
93 + );
94 + });
95 +});
ts/packages/cli/test/src/commands/tools/tools.search.client.cmd.test.ts
+29
@@ -150,6 +150,35 @@ describe('CLI: composio search over the API client', () => {
150 );
151 });
152
153 + layer(testLayer)('[Given] a search response in a shape the API contract does not allow', it => {
154 + it.effect('[Then] the tools and connected toolkits are still reported', () =>
155 + Effect.gen(function* () {
156 + // A sharing model the client does not know, no `status_message`, no
157 + // `description`, no `time_info`, and no `session`.
158 + const driftedResponse = {
159 + success: true,
160 + error: null,
161 + results: searchResponse.results,
162 + toolkit_connection_statuses: [
163 + { toolkit: 'gmail', has_active_connection: true, account_type: 'ORG' },
164 + ],
165 + tool_schemas: searchResponse.tool_schemas,
166 + next_steps_guidance: [],
167 + };
168 + const stub = searchingOver(() => Response.json(driftedResponse));
169 + yield* cli(['search', 'send an email']).pipe(Effect.provide(stub.layer));
170 + const lines = yield* MockConsole.getLines({ stripAnsi: true });
171 + const payload = JSON.parse(lines.at(-1) ?? '{}');
172 +
173 + expect(payload.results).toEqual(searchResponse.results);
174 + expect(payload.tool_schemas.primary).toEqual({
175 + GMAIL_SEND_EMAIL: '~/.composio/tool_definitions/GMAIL_SEND_EMAIL.json',
176 + });
177 + expect(payload.connected_toolkits).toEqual(['gmail']);
178 + })
179 + );
180 + });
181 +
182 layer(testLayer)('[Given] the API rejects the search', it => {
183 it.effect('[Then] the command fails with the status and response body as the cause', () =>
184 Effect.gen(function* () {
ts/packages/cli/test/src/services/composio-clients.test.ts
+26 -13
@@ -219,6 +219,21 @@ describe('composio-clients', () => {
219 }).pipe(Effect.provide(withSingleton))
220 );
221
222 + it.effect(
223 + 'listOrgProjects returns a project whose webhook version the client does not know',
224 + () =>
225 + Effect.gen(function* () {
226 + const project = { ...makeOrgProject({ id: 'p1', name: 'One' }), webhook_version: 'V9' };
227 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(
228 + jsonResponse({ data: [project], total_pages: 1, current_page: 1, total_items: 1 })
229 + );
230 +
231 + const result = yield* listOrgProjects({ apiKey: 'uak_test', orgId: 'org_1' });
232 +
233 + expect(result.data).toEqual([project]);
234 + }).pipe(Effect.provide(withSingleton))
235 + );
236 +
237 it.effect('findDeveloperProjectByName rejects a case-insensitive name collision', () =>
238 Effect.gen(function* () {
239 vi.spyOn(globalThis, 'fetch').mockResolvedValue(
@@ -449,23 +464,21 @@ describe('composio-clients', () => {
464 }).pipe(Effect.provide(withRepository))
465 );
466
452 - it.effect('searchTools fails with DecodeError when the page breaks the API contract', () =>
467 + it.effect('searchTools returns a page the API contract does not allow as it arrived', () =>
468 Effect.gen(function* () {
454 - vi.spyOn(globalThis, 'fetch').mockResolvedValue(
455 - // No `total_items`, which the API's response schema requires.
456 - jsonResponse({ items: [], next_cursor: null, total_pages: 1, current_page: 1 }, 200, {
457 - 'x-request-id': 'req_tools',
458 - })
459 - );
469 + // No `total_items`, and an item with only the fields the listing prints.
470 + const page = {
471 + items: [{ slug: 'GMAIL_SEND_EMAIL', name: 'Send Email', description: 'Send an email' }],
472 + next_cursor: null,
473 + total_pages: 1,
474 + current_page: 1,
475 + };
476 + vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse(page));
477 const repository = yield* ComposioToolkitsRepository;
478
462 - const error = yield* repository.searchTools({ search: 'send' }).pipe(Effect.flip);
479 + const result = yield* repository.searchTools({ search: 'send' });
480
464 - expect(error).toMatchObject({
465 - _tag: '@composio/client/DecodeError',
466 - operation: 'tools.list',
467 - requestId: 'req_tools',
468 - });
481 + expect(result).toEqual(page);
482 }).pipe(Effect.provide(withRepository))
483 );
484