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.

feat(cli): add local tools foundation (#3340)

Rahul Tarak79ac22053fa7
diff --git a/.changeset/beeper-imessage-local-tools.md b/.changeset/beeper-imessage-local-tools.md
new file mode 100644
index 000000000..9724368fc
--- /dev/null
+++ b/.changeset/beeper-imessage-local-tools.md
@@ -0,0 +1,5 @@
+---
+'@composio/cli-local-tools': patch
+---
+
+Add the Beeper iMessage local toolkit, rebuildable sidecar binaries from the ComposioHQ platform-imessage submodule, and higher-level wrappers for compact thread discovery, contact-aware thread search, send verification, and primary-instance reaction preparation.
diff --git a/.changeset/chrome-devtools-local-tools.md b/.changeset/chrome-devtools-local-tools.md
new file mode 100644
index 000000000..27c3fb227
--- /dev/null
+++ b/.changeset/chrome-devtools-local-tools.md
@@ -0,0 +1,5 @@
+---
+'@composio/cli-local-tools': patch
+---
+
+Add first-class Chrome DevTools local tools backed by the official `chrome-devtools-mcp` package and its stateful `chrome-devtools` CLI daemon.
diff --git a/.changeset/cli-local-tools.md b/.changeset/cli-local-tools.md
new file mode 100644
index 000000000..53da4d77f
--- /dev/null
+++ b/.changeset/cli-local-tools.md
@@ -0,0 +1,6 @@
+---
+'@composio/cli': patch
+'@composio/cli-local-tools': patch
+---
+
+Scaffold the CLI local-tools foundation package, wire it into Tool Router search/execute sessions, and expose `composio local-tools list|doctor|configure|meta` for discovery, readiness checks, setup hints, and local metadata state. Concrete app integrations are added in follow-up stack PRs.
diff --git a/.changeset/peekaboo-local-tools.md b/.changeset/peekaboo-local-tools.md
new file mode 100644
index 000000000..c6784ff89
--- /dev/null
+++ b/.changeset/peekaboo-local-tools.md
@@ -0,0 +1,5 @@
+---
+'@composio/cli-local-tools': patch
+---
+
+Add first-class Peekaboo macOS local tools backed by a bundled darwin-arm64 Peekaboo CLI binary.
diff --git a/.github/workflows/build-cli-binaries.yml b/.github/workflows/build-cli-binaries.yml
index c96dcd1fa..4b861fb1c 100644
--- a/.github/workflows/build-cli-binaries.yml
+++ b/.github/workflows/build-cli-binaries.yml
@@ -198,18 +198,26 @@ jobs:
name: Build ${{ matrix.artifact }}
needs: prepare
if: needs.prepare.result == 'success'
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.runner }}
strategy:
matrix:
include:
- target: bun-linux-x64
artifact: composio-linux-x64
+ runner: ubuntu-latest
+ local_tools_target: ''
- target: bun-linux-arm64
artifact: composio-linux-aarch64
+ runner: ubuntu-latest
+ local_tools_target: ''
- target: bun-darwin-x64
artifact: composio-darwin-x64
+ runner: macos-15-intel
+ local_tools_target: darwin-x64
- target: bun-darwin-arm64
artifact: composio-darwin-aarch64
+ runner: macos-15
+ local_tools_target: darwin-arm64
steps:
- name: Checkout
@@ -226,6 +234,16 @@ jobs:
- name: Build packages
run: pnpm build:packages
+ - name: Build local-tool sidecar binaries
+ if: matrix.local_tools_target != ''
+ run: pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target ${{ matrix.local_tools_target }}
+
+ - name: Verify local-tool sidecars
+ if: matrix.local_tools_target != ''
+ run: |
+ test -x ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/${{ matrix.local_tools_target }}/imessage-cli
+ test -x ts/packages/cli-local-tools/local-tools-binaries/peekaboo/${{ matrix.local_tools_target }}/peekaboo
+
- name: Cross-compile CLI binary
working-directory: ts/packages/cli
run: pnpm build:binary:cross --target ${{ matrix.target }}
diff --git a/.gitmodules b/.gitmodules
index 9b715c76d..3f40b0b10 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -5,3 +5,10 @@
[submodule "ts/vendor/clack"]
path = ts/vendor/clack
url = https://github.com/bombshell-dev/clack.git
+[submodule "ts/packages/cli-local-tools/vendor/platform-imessage"]
+ path = ts/packages/cli-local-tools/vendor/platform-imessage
+ url = https://github.com/ComposioHQ/platform-imessage
+ branch = main
+[submodule "ts/packages/cli-local-tools/vendor/peekaboo"]
+ path = ts/packages/cli-local-tools/vendor/peekaboo
+ url = https://github.com/steipete/Peekaboo
diff --git a/package.json b/package.json
index e9e1b31aa..2a681a37c 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,8 @@
"ts/packages/core",
"ts/packages/json-schema-to-zod",
"ts/packages/cli",
+ "ts/packages/cli-keyring",
+ "ts/packages/cli-local-tools",
"ts/packages/providers/*"
],
"scripts": {
@@ -53,6 +55,7 @@
"@arethetypeswrong/cli": "catalog:",
"@changesets/cli": "^2.29.8",
"@composio/anthropic": "workspace:*",
+ "@composio/cli-local-tools": "workspace:*",
"@composio/core": "workspace:*",
"@composio/openai": "workspace:*",
"@types/bun": "^1.3.6",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 87376f1dc..95e9858ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -115,6 +115,9 @@ importers:
'@composio/anthropic':
specifier: workspace:*
version: link:ts/packages/providers/anthropic
+ '@composio/cli-local-tools':
+ specifier: workspace:*
+ version: link:ts/packages/cli-local-tools
'@composio/core':
specifier: workspace:*
version: link:ts/packages/core
@@ -719,16 +722,16 @@ importers:
version: link:../../packages/providers/llamaindex
'@llamaindex/openai':
specifier: ^0.4.20
- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
'@llamaindex/workflow':
specifier: ^1.1.24
- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
dotenv:
specifier: ^16.4.1
version: 16.6.1
llamaindex:
specifier: ^0.12.0
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -1071,6 +1074,9 @@ importers:
'@composio/cli-keyring':
specifier: workspace:*
version: link:../cli-keyring
+ '@composio/cli-local-tools':
+ specifier: workspace:*
+ version: link:../cli-local-tools
'@composio/client':
specifier: 'catalog:'
version: 0.1.0-alpha.68
@@ -1205,6 +1211,34 @@ importers:
specifier: 'catalog:'
+ ts/packages/cli-local-tools:
+ dependencies:
+ '@modelcontextprotocol/sdk':
+ specifier: ^1.26.0
+ version: 1.26.0(@cfworker/[email protected])([email protected])
+ zod:
+ specifier: 'catalog:'
+ version: 4.3.6
+ zod-to-json-schema:
+ specifier: 'catalog:'
+ version: 3.25.1([email protected])
+ devDependencies:
+ '@types/node':
+ specifier: ^24.0.1
+ version: 24.10.13
+ chrome-devtools-mcp:
+ specifier: 0.24.0
+ version: 0.24.0
+ tsdown:
+ specifier: 'catalog:'
+ version: 0.18.4(@arethetypeswrong/[email protected])(@typescript/[email protected])([email protected])([email protected])
+ typescript:
+ specifier: 'catalog:'
+ version: 5.9.3
+ vitest:
+ specifier: 'catalog:'
+
ts/packages/core:
dependencies:
'@composio/client':
@@ -1382,7 +1416,7 @@ importers:
dependencies:
llamaindex:
specifier: ^0.12.0
devDependencies:
'@composio/core':
specifier: workspace:*
@@ -4183,6 +4217,11 @@ packages:
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
engines: {node: '>= 16'}
+ resolution: {integrity: sha512-eN7YZH05pTYCjgPj/rT0vqYjhOwGrqZX3wK7I8suljRMZ30L8YPlr/MqyYSDOf7fe3s9G0E7SqSNX2xXov6ZPw==}
+ engines: {node: ^20.19.0 || ^22.12.0 || >=23}
+ hasBin: true
+
resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==}
engines: {node: '>=8'}
@@ -8008,26 +8047,43 @@ snapshots:
tree-sitter: 0.22.4
web-tree-sitter: 0.24.7
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
transitivePeerDependencies:
- ws
- zod
optionalDependencies:
- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])
+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])
hono: 4.11.9
+ zod: 3.25.76
+
+ optionalDependencies:
zod: 4.3.6
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ transitivePeerDependencies:
+ - '@modelcontextprotocol/sdk'
+ - hono
+ - next
+ - p-retry
+ - rxjs
+ - zod
+
+ dependencies:
+ '@llamaindex/core': 0.6.22
+ '@llamaindex/env': 0.1.30
+ '@llamaindex/workflow-core': 1.3.3([email protected])
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- hono
@@ -8236,7 +8292,7 @@ snapshots:
zod: 3.25.76
zod-from-json-schema: 0.5.2
zod-from-json-schema-v3: [email protected]
- zod-to-json-schema: 3.25.1([email protected])
+ zod-to-json-schema: 3.25.2([email protected])
dependencies:
@@ -8244,7 +8300,7 @@ snapshots:
zod: 4.3.6
zod-from-json-schema: 0.5.2
zod-from-json-schema-v3: [email protected]
- zod-to-json-schema: 3.25.1([email protected])
+ zod-to-json-schema: 3.25.2([email protected])
'@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])':
dependencies:
@@ -9045,6 +9101,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 3.2.4
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
'@vitest/[email protected]':
dependencies:
tinyrainbow: 2.0.0
@@ -9074,7 +9138,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.15
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -9371,6 +9435,8 @@ snapshots:
+
@@ -10524,12 +10590,34 @@ snapshots:
rfdc: 1.4.1
wrap-ansi: 9.0.2
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ '@types/lodash': 4.17.23
+ '@types/node': 24.10.13
+ lodash: 4.17.23
+ magic-bytes.js: 1.13.0
+ transitivePeerDependencies:
+ - '@huggingface/transformers'
+ - '@modelcontextprotocol/sdk'
+ - gpt-tokenizer
+ - hono
+ - next
+ - p-retry
+ - rxjs
+ - tree-sitter
+ - web-tree-sitter
+ - zod
+
+ dependencies:
+ '@llamaindex/core': 0.6.22
+ '@llamaindex/env': 0.1.30
+ '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])
'@types/lodash': 4.17.23
'@types/node': 24.10.13
lodash: 4.17.23
@@ -10813,6 +10901,11 @@ snapshots:
is-inside-container: 1.0.0
wsl-utils: 0.1.0
+ optionalDependencies:
+ ws: 8.20.0
+ zod: 3.25.76
+
optionalDependencies:
ws: 8.20.0
@@ -11911,7 +12004,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.3
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 49b9f0bf6..1f7fa9fd4 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -8,6 +8,7 @@ packages:
- ts/examples/*
- ts/packages/cli
- ts/packages/cli-keyring
+ - ts/packages/cli-local-tools
- ts/packages/core
- ts/packages/json-schema-to-zod
- ts/packages/providers/*
@@ -52,6 +53,7 @@ minimumReleaseAge: 4320
minimumReleaseAgeExclude:
- '@composio/client'
+ - chrome-devtools-mcp
overrides:
qs@<6.14.1: '>=6.14.1'
diff --git a/ts/packages/cli-keyring/tsdown.config.ts b/ts/packages/cli-keyring/tsdown.config.ts
index 42109e243..bfbbdca73 100644
--- a/ts/packages/cli-keyring/tsdown.config.ts
+++ b/ts/packages/cli-keyring/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../tsdown.config.base';
+import { baseConfig } from '../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/.gitignore b/ts/packages/cli-local-tools/local-tools-binaries/.gitignore
new file mode 100644
index 000000000..e3291444d
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/.gitignore
@@ -0,0 +1,4 @@
+# Local tool binaries are generated during CLI binary builds/release jobs.
+# Keep notices/licenses in git, but never commit generated executables.
+/beeper-imessage/darwin-*/imessage-cli
+/peekaboo/darwin-*/peekaboo
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/README.md b/ts/packages/cli-local-tools/local-tools-binaries/README.md
new file mode 100644
index 000000000..834bb8601
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/README.md
@@ -0,0 +1,19 @@
+# Local tool binary assets
+
+Platform-specific executable and dynamic-library assets for first-party local tool integrations are generated into this directory during local-tool binary builds.
+
+Do not commit generated executables. Keep notices/licenses in git, pin source with git submodules under `ts/packages/cli-local-tools/vendor/`, and regenerate binaries in CLI release jobs before packaging artifacts.
+
+Current native binary sources:
+
+- Beeper iMessage: `vendor/platform-imessage` (`https://github.com/ComposioHQ/platform-imessage`)
+- Peekaboo: `vendor/peekaboo` (`https://github.com/steipete/Peekaboo`)
+
+Build macOS sidecars for the current host/target with:
+
+```bash
+pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target darwin-arm64
+pnpm --filter @composio/cli-local-tools build:local-tool-binaries -- --target darwin-x64
+```
+
+Linux CLI artifacts skip these native sidecars. Chrome DevTools is an npm/npx-based integration and does not use this directory.
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/LICENSE.txt b/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/LICENSE.txt
new file mode 100644
index 000000000..71a33688a
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/LICENSE.txt
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2020-2023 Texts.com, 2023- Automattic Inc
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/NOTICE.md b/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/NOTICE.md
new file mode 100644
index 000000000..fa4e526fd
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/beeper-imessage/NOTICE.md
@@ -0,0 +1,14 @@
+# Beeper platform-imessage CLI binary
+
+These `imessage-cli` binaries are built from the Composio fork of Beeper platform-imessage.
+
+- Upstream fork: `https://github.com/ComposioHQ/platform-imessage`
+- Upstream version: `0.21.0`
+- Upstream submodule commit: `364445a1b3089ad9fe293d5951efe160c5677c42`
+- License: MIT (`license.txt` in the upstream repository)
+- Build command: `pnpm --filter @composio/cli-local-tools build:beeper-imessage -- --target <darwin-arm64|darwin-x64>`
+- Underlying Swift build commands:
+ - `swift build -c release --product imessage-cli --arch arm64`
+ - `swift build -c release --product imessage-cli --arch x86_64`
+
+The binaries are stripped release builds for macOS arm64 and x64. They require local macOS Messages data and may prompt for Messages Data, Accessibility, Contacts, and Automation permissions depending on the command.
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/LICENSE.txt b/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/LICENSE.txt
new file mode 100644
index 000000000..f7b526698
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Peter Steinberger
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/NOTICE.md b/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/NOTICE.md
new file mode 100644
index 000000000..e606762d5
--- /dev/null
+++ b/ts/packages/cli-local-tools/local-tools-binaries/peekaboo/NOTICE.md
@@ -0,0 +1,12 @@
+# Peekaboo CLI binary
+
+These `peekaboo` binaries are built from the upstream Peekaboo repository.
+
+- Upstream repository: `https://github.com/steipete/Peekaboo`
+- Upstream version: `3.0.0-beta4`
+- Upstream submodule commit: `31e66e8d02656141d18f60bf3b46b24c2b9bc785`
+- License: MIT (`LICENSE` in the upstream repository)
+- Build command: `pnpm --filter @composio/cli-local-tools build:peekaboo -- --target <darwin-arm64|darwin-x64>`
+- Underlying Swift build command: `swift build --arch <arm64|x86_64> -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip` from `Apps/CLI`
+
+The binaries are release builds for macOS. Peekaboo requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility/Automation permissions for GUI control tools.
diff --git a/ts/packages/cli-local-tools/package.json b/ts/packages/cli-local-tools/package.json
new file mode 100644
index 000000000..2c6918799
--- /dev/null
+++ b/ts/packages/cli-local-tools/package.json
@@ -0,0 +1,58 @@
+{
+ "name": "@composio/cli-local-tools",
+ "version": "0.0.1",
+ "description": "Local tool and toolkit declarations for the Composio CLI.",
+ "type": "module",
+ "main": "dist/index.mjs",
+ "module": "dist/index.mjs",
+ "types": "dist/index.d.mts",
+ "exports": {
+ ".": {
+ "import": {
+ "types": "./dist/index.d.mts",
+ "default": "./dist/index.mjs"
+ },
+ "require": {
+ "types": "./dist/index.d.cts",
+ "default": "./dist/index.cjs"
+ },
+ "default": {
+ "types": "./dist/index.d.cts",
+ "default": "./dist/index.cjs"
+ }
+ }
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/ComposioHQ/composio.git",
+ "directory": "ts/packages/cli-local-tools"
+ },
+ "license": "ISC",
+ "files": [
+ "dist",
+ "local-tools-binaries"
+ ],
+ "sideEffects": false,
+ "scripts": {
+ "clean": "git clean -xdf node_modules",
+ "build": "pnpm exec tsdown",
+ "build:beeper-imessage": "bun run ./scripts/build-beeper-imessage-binaries.ts",
+ "build:peekaboo": "bun run ./scripts/build-peekaboo-binaries.ts",
+ "build:local-tool-binaries": "bun run ./scripts/build-local-tool-binaries.ts",
+ "test": "vitest run",
+ "typecheck": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json",
+ "typecheck:tsc": "tsc --noEmit -p ./tsconfig.src.json"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.26.0",
+ "zod": "catalog:",
+ "zod-to-json-schema": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "^24.0.1",
+ "chrome-devtools-mcp": "0.24.0",
+ "tsdown": "catalog:",
+ "typescript": "catalog:",
+ "vitest": "catalog:"
+ }
+}
diff --git a/ts/packages/cli-local-tools/scripts/build-beeper-imessage-binaries.ts b/ts/packages/cli-local-tools/scripts/build-beeper-imessage-binaries.ts
new file mode 100755
index 000000000..08a48d54d
--- /dev/null
+++ b/ts/packages/cli-local-tools/scripts/build-beeper-imessage-binaries.ts
@@ -0,0 +1,164 @@
+#!/usr/bin/env bun
+
+import { $ } from 'bun';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const packageRoot = path.resolve(scriptDir, '..');
+const repoRoot = path.resolve(packageRoot, '../../..');
+const submodulePath = path.join(packageRoot, 'vendor/platform-imessage');
+const submoduleRelativePath = path.relative(repoRoot, submodulePath);
+const outputRoot = path.join(packageRoot, 'local-tools-binaries/beeper-imessage');
+
+const upstreamRepository = 'https://github.com/ComposioHQ/platform-imessage';
+
+const targets = [
+ {
+ platform: 'darwin-arm64',
+ swiftArch: 'arm64',
+ buildPath: '.build/arm64-apple-macosx/release/imessage-cli',
+ },
+ {
+ platform: 'darwin-x64',
+ swiftArch: 'x86_64',
+ buildPath: '.build/x86_64-apple-macosx/release/imessage-cli',
+ },
+] as const;
+
+type Target = (typeof targets)[number];
+
+const exists = async (filePath: string): Promise<boolean> =>
+ fs
+ .access(filePath)
+ .then(() => true)
+ .catch(() => false);
+
+const readJson = async <T>(filePath: string): Promise<T> =>
+ JSON.parse(await fs.readFile(filePath, 'utf8')) as T;
+
+const ensurePlatform = () => {
+ if (process.platform !== 'darwin') {
+ throw new Error(
+ 'Building Beeper iMessage local-tool binaries requires macOS and the Swift toolchain.'
+ );
+ }
+};
+
+const ensureSubmodule = async () => {
+ if (await exists(path.join(submodulePath, 'Package.swift'))) return;
+
+ console.log(`Initializing ${submoduleRelativePath} submodule...`);
+ await $`git submodule update --init --recursive -- ${submoduleRelativePath}`.cwd(repoRoot);
+
+ if (!(await exists(path.join(submodulePath, 'Package.swift')))) {
+ throw new Error(
+ `Missing platform-imessage submodule at ${submoduleRelativePath}. Run: git submodule update --init --recursive -- ${submoduleRelativePath}`
+ );
+ }
+};
+
+const getSubmoduleCommit = async (): Promise<string> =>
+ (await $`git rev-parse HEAD`.cwd(submodulePath).text()).trim();
+
+const getSubmoduleVersion = async (): Promise<string> => {
+ const packageJson = await readJson<{ version?: string }>(
+ path.join(submodulePath, 'package.json')
+ );
+ return packageJson.version ?? 'unknown';
+};
+
+const copyLicense = async () => {
+ const licenseCandidates = ['license.txt', 'LICENSE.txt', 'LICENSE', 'LICENSE.md'];
+ for (const candidate of licenseCandidates) {
+ const sourcePath = path.join(submodulePath, candidate);
+ if (await exists(sourcePath)) {
+ await fs.copyFile(sourcePath, path.join(outputRoot, 'LICENSE.txt'));
+ return;
+ }
+ }
+ throw new Error('No upstream license file found in platform-imessage submodule.');
+};
+
+const buildTarget = async (target: Target) => {
+ console.log(`Building imessage-cli for ${target.platform} (${target.swiftArch})...`);
+ await $`swift build -c release --product imessage-cli --arch ${target.swiftArch}`.cwd(
+ submodulePath
+ );
+
+ const builtBinary = path.join(submodulePath, target.buildPath);
+ if (!(await exists(builtBinary))) {
+ throw new Error(`Swift build completed but ${target.buildPath} was not produced.`);
+ }
+
+ const targetDir = path.join(outputRoot, target.platform);
+ const outputBinary = path.join(targetDir, 'imessage-cli');
+ await fs.mkdir(targetDir, { recursive: true });
+ await fs.copyFile(builtBinary, outputBinary);
+ await fs.chmod(outputBinary, 0o755);
+ console.log(`Wrote ${path.relative(repoRoot, outputBinary)}`);
+};
+
+const writeNotice = async (params: { version: string; commit: string }) => {
+ const notice = `# Beeper platform-imessage CLI binary
+
+These \`imessage-cli\` binaries are built from the Composio fork of Beeper platform-imessage.
+
+- Upstream fork: \`${upstreamRepository}\`
+- Upstream version: \`${params.version}\`
+- Upstream submodule commit: \`${params.commit}\`
+- License: MIT (\`license.txt\` in the upstream repository)
+- Build command: \`pnpm --filter @composio/cli-local-tools build:beeper-imessage -- --target <darwin-arm64|darwin-x64>\`
+- Underlying Swift build commands:
+ - \`swift build -c release --product imessage-cli --arch arm64\`
+ - \`swift build -c release --product imessage-cli --arch x86_64\`
+
+The binaries are stripped release builds for macOS arm64 and x64. They require local macOS Messages data and may prompt for Messages Data, Accessibility, Contacts, and Automation permissions depending on the command.
+`;
+ await fs.writeFile(path.join(outputRoot, 'NOTICE.md'), notice, 'utf8');
+};
+
+const parseTargets = (): ReadonlyArray<Target> => {
+ const rawArgs = process.argv.slice(2).filter(arg => arg !== '--');
+ const targetIndex = rawArgs.indexOf('--target');
+ const args =
+ targetIndex >= 0 && rawArgs[targetIndex + 1]
+ ? [rawArgs[targetIndex + 1]!]
+ : rawArgs.filter(arg => !arg.startsWith('--'));
+
+ if (args.length === 0 || args.includes('all')) return targets;
+
+ const selected = targets.filter(target => args.includes(target.platform));
+ const unknown = args.filter(arg => !targets.some(target => target.platform === arg));
+ if (unknown.length > 0) {
+ throw new Error(
+ `Unknown target(s): ${unknown.join(', ')}. Expected one of: all, ${targets
+ .map(target => target.platform)
+ .join(', ')}`
+ );
+ }
+ return selected;
+};
+
+const main = async () => {
+ ensurePlatform();
+ await ensureSubmodule();
+
+ await fs.mkdir(outputRoot, { recursive: true });
+ const selectedTargets = parseTargets();
+ for (const target of selectedTargets) {
+ await buildTarget(target);
+ }
+
+ await copyLicense();
+ await writeNotice({
+ version: await getSubmoduleVersion(),
+ commit: await getSubmoduleCommit(),
+ });
+};
+
+main().catch(error => {
+ console.error(error instanceof Error ? error.message : error);
+ process.exit(1);
+});
diff --git a/ts/packages/cli-local-tools/scripts/build-local-tool-binaries.ts b/ts/packages/cli-local-tools/scripts/build-local-tool-binaries.ts
new file mode 100644
index 000000000..98ee2ce7d
--- /dev/null
+++ b/ts/packages/cli-local-tools/scripts/build-local-tool-binaries.ts
@@ -0,0 +1,77 @@
+#!/usr/bin/env bun
+
+import { $ } from 'bun';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const packageRoot = path.resolve(scriptDir, '..');
+
+const targetAliases = new Map<string, string>([
+ ['bun-darwin-arm64', 'darwin-arm64'],
+ ['bun-darwin-aarch64', 'darwin-arm64'],
+ ['composio-darwin-aarch64', 'darwin-arm64'],
+ ['darwin-aarch64', 'darwin-arm64'],
+ ['darwin-arm64', 'darwin-arm64'],
+ ['bun-darwin-x64', 'darwin-x64'],
+ ['composio-darwin-x64', 'darwin-x64'],
+ ['darwin-x64', 'darwin-x64'],
+ ['bun-linux-x64', 'linux-x64'],
+ ['composio-linux-x64', 'linux-x64'],
+ ['linux-x64', 'linux-x64'],
+ ['bun-linux-arm64', 'linux-arm64'],
+ ['bun-linux-aarch64', 'linux-arm64'],
+ ['composio-linux-aarch64', 'linux-arm64'],
+ ['linux-aarch64', 'linux-arm64'],
+ ['linux-arm64', 'linux-arm64'],
+]);
+
+const parseTargetArg = (): string | undefined => {
+ const args = process.argv.slice(2).filter(arg => arg !== '--');
+ const targetIndex = args.indexOf('--target');
+ if (targetIndex >= 0) return args[targetIndex + 1];
+ return args.find(arg => !arg.startsWith('--'));
+};
+
+const detectHostTarget = (): string => {
+ if (process.platform === 'darwin') {
+ return process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64';
+ }
+ if (process.platform === 'linux') {
+ return process.arch === 'arm64' ? 'linux-arm64' : 'linux-x64';
+ }
+ return `${process.platform}-${process.arch}`;
+};
+
+const normalizeTarget = (target?: string): string => {
+ const value = target ?? detectHostTarget();
+ return targetAliases.get(value) ?? value;
+};
+
+const runScript = async (scriptName: string, target: string) => {
+ await $`bun run ${path.join('scripts', scriptName)} --target ${target}`.cwd(packageRoot);
+};
+
+const main = async () => {
+ const target = normalizeTarget(parseTargetArg());
+
+ if (!target.startsWith('darwin-')) {
+ console.log(`Skipping native local-tool binary build for non-macOS target: ${target}`);
+ return;
+ }
+
+ if (process.platform !== 'darwin') {
+ throw new Error(
+ `Building native local-tool binaries for ${target} requires a macOS runner with the Swift toolchain.`
+ );
+ }
+
+ console.log(`Building native local-tool binaries for ${target}...`);
+ await runScript('build-beeper-imessage-binaries.ts', target);
+ await runScript('build-peekaboo-binaries.ts', target);
+};
+
+main().catch(error => {
+ console.error(error instanceof Error ? error.message : error);
+ process.exit(1);
+});
diff --git a/ts/packages/cli-local-tools/scripts/build-peekaboo-binaries.ts b/ts/packages/cli-local-tools/scripts/build-peekaboo-binaries.ts
new file mode 100644
index 000000000..f35bf443f
--- /dev/null
+++ b/ts/packages/cli-local-tools/scripts/build-peekaboo-binaries.ts
@@ -0,0 +1,172 @@
+#!/usr/bin/env bun
+
+import { $ } from 'bun';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const packageRoot = path.resolve(scriptDir, '..');
+const repoRoot = path.resolve(packageRoot, '../../..');
+const submodulePath = path.join(packageRoot, 'vendor/peekaboo');
+const submoduleRelativePath = path.relative(repoRoot, submodulePath);
+const cliPackagePath = path.join(submodulePath, 'Apps/CLI');
+const outputRoot = path.join(packageRoot, 'local-tools-binaries/peekaboo');
+
+const upstreamRepository = 'https://github.com/steipete/Peekaboo';
+
+const targets = [
+ {
+ platform: 'darwin-arm64',
+ swiftArch: 'arm64',
+ buildPath: 'Apps/CLI/.build/arm64-apple-macosx/release/peekaboo',
+ },
+ {
+ platform: 'darwin-x64',
+ swiftArch: 'x86_64',
+ buildPath: 'Apps/CLI/.build/x86_64-apple-macosx/release/peekaboo',
+ },
+] as const;
+
+type Target = (typeof targets)[number];
+
+const exists = async (filePath: string): Promise<boolean> =>
+ fs
+ .access(filePath)
+ .then(() => true)
+ .catch(() => false);
+
+const readJson = async <T>(filePath: string): Promise<T> =>
+ JSON.parse(await fs.readFile(filePath, 'utf8')) as T;
+
+const ensurePlatform = () => {
+ if (process.platform !== 'darwin') {
+ throw new Error(
+ 'Building Peekaboo local-tool binaries requires macOS and the Swift toolchain.'
+ );
+ }
+};
+
+const ensureSubmodule = async () => {
+ if (!(await exists(path.join(submodulePath, 'Apps/CLI/Package.swift')))) {
+ console.log(`Initializing ${submoduleRelativePath} submodule...`);
+ await $`git submodule update --init --recursive -- ${submoduleRelativePath}`.cwd(repoRoot);
+ }
+
+ if (!(await exists(path.join(submodulePath, 'Apps/CLI/Package.swift')))) {
+ throw new Error(
+ `Missing Peekaboo submodule at ${submoduleRelativePath}. Run: git submodule update --init --recursive -- ${submoduleRelativePath}`
+ );
+ }
+
+ if (!(await exists(path.join(submodulePath, 'Commander/Package.swift')))) {
+ console.log(`Initializing nested Peekaboo submodules...`);
+ await $`git submodule update --init --recursive`.cwd(submodulePath);
+ }
+
+ if (!(await exists(path.join(submodulePath, 'Commander/Package.swift')))) {
+ throw new Error('Missing nested Peekaboo submodules after initialization.');
+ }
+};
+
+const getSubmoduleCommit = async (): Promise<string> =>
+ (await $`git rev-parse HEAD`.cwd(submodulePath).text()).trim();
+
+const getSubmoduleVersion = async (): Promise<string> => {
+ const versionJson = await readJson<{ version?: string }>(
+ path.join(submodulePath, 'version.json')
+ );
+ return versionJson.version ?? 'unknown';
+};
+
+const copyLicense = async () => {
+ const licenseCandidates = ['LICENSE', 'LICENSE.txt', 'LICENSE.md'];
+ for (const candidate of licenseCandidates) {
+ const sourcePath = path.join(submodulePath, candidate);
+ if (await exists(sourcePath)) {
+ await fs.copyFile(sourcePath, path.join(outputRoot, 'LICENSE.txt'));
+ return;
+ }
+ }
+ throw new Error('No upstream license file found in Peekaboo submodule.');
+};
+
+const buildTarget = async (target: Target) => {
+ console.log(`Building peekaboo for ${target.platform} (${target.swiftArch})...`);
+ await $`swift build --arch ${target.swiftArch} -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip`.cwd(
+ cliPackagePath
+ );
+
+ const builtBinary = path.join(submodulePath, target.buildPath);
+ if (!(await exists(builtBinary))) {
+ throw new Error(`Swift build completed but ${target.buildPath} was not produced.`);
+ }
+
+ const targetDir = path.join(outputRoot, target.platform);
+ const outputBinary = path.join(targetDir, 'peekaboo');
+ await fs.mkdir(targetDir, { recursive: true });
+ await fs.copyFile(builtBinary, outputBinary);
+ await fs.chmod(outputBinary, 0o755);
+ console.log(`Wrote ${path.relative(repoRoot, outputBinary)}`);
+};
+
+const writeNotice = async (params: { version: string; commit: string }) => {
+ const notice = `# Peekaboo CLI binary
+
+These \`peekaboo\` binaries are built from the upstream Peekaboo repository.
+
+- Upstream repository: \`${upstreamRepository}\`
+- Upstream version: \`${params.version}\`
+- Upstream submodule commit: \`${params.commit}\`
+- License: MIT (\`LICENSE\` in the upstream repository)
+- Build command: \`pnpm --filter @composio/cli-local-tools build:peekaboo -- --target <darwin-arm64|darwin-x64>\`
+- Underlying Swift build command: \`swift build --arch <arm64|x86_64> -c release -Xswiftc -Osize -Xswiftc -wmo -Xlinker -dead_strip\` from \`Apps/CLI\`
+
+The binaries are release builds for macOS. Peekaboo requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility/Automation permissions for GUI control tools.
+`;
+ await fs.writeFile(path.join(outputRoot, 'NOTICE.md'), notice, 'utf8');
+};
+
+const parseTargets = (): ReadonlyArray<Target> => {
+ const rawArgs = process.argv.slice(2).filter(arg => arg !== '--');
+ const targetIndex = rawArgs.indexOf('--target');
+ const args =
+ targetIndex >= 0 && rawArgs[targetIndex + 1]
+ ? [rawArgs[targetIndex + 1]!]
+ : rawArgs.filter(arg => !arg.startsWith('--'));
+
+ if (args.length === 0 || args.includes('all')) return targets;
+
+ const selected = targets.filter(target => args.includes(target.platform));
+ const unknown = args.filter(arg => !targets.some(target => target.platform === arg));
+ if (unknown.length > 0) {
+ throw new Error(
+ `Unknown target(s): ${unknown.join(', ')}. Expected one of: all, ${targets
+ .map(target => target.platform)
+ .join(', ')}`
+ );
+ }
+ return selected;
+};
+
+const main = async () => {
+ ensurePlatform();
+ await ensureSubmodule();
+
+ await fs.mkdir(outputRoot, { recursive: true });
+ const selectedTargets = parseTargets();
+ for (const target of selectedTargets) {
+ await buildTarget(target);
+ }
+
+ await copyLicense();
+ await writeNotice({
+ version: await getSubmoduleVersion(),
+ commit: await getSubmoduleCommit(),
+ });
+};
+
+main().catch(error => {
+ console.error(error instanceof Error ? error.message : error);
+ process.exit(1);
+});
diff --git a/ts/packages/cli-local-tools/src/bun-ffi.d.ts b/ts/packages/cli-local-tools/src/bun-ffi.d.ts
new file mode 100644
index 000000000..610d58f2f
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/bun-ffi.d.ts
@@ -0,0 +1,7 @@
+declare module 'bun:ffi' {
+ export const FFIType: Record<string, unknown>;
+ export function dlopen(
+ path: string,
+ symbols: Record<string, { args: ReadonlyArray<unknown>; returns: unknown }>
+ ): { symbols: Record<string, (...args: ReadonlyArray<unknown>) => unknown> };
+}
diff --git a/ts/packages/cli-local-tools/src/bundled-binaries.test.ts b/ts/packages/cli-local-tools/src/bundled-binaries.test.ts
new file mode 100644
index 000000000..5a1d369d1
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/bundled-binaries.test.ts
@@ -0,0 +1,92 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+import { z } from 'zod/v3';
+import { detectCliPlatform } from './platform';
+import { checkLocalToolkitsReadiness } from './readiness';
+import { normalizeLocalToolSlug } from './registry';
+import { executeLocalTool } from './runtime';
+import type { LocalToolkitDeclaration } from './types';
+
+const tempDirs: string[] = [];
+const originalBinDir = process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR;
+
+afterEach(async () => {
+ if (originalBinDir === undefined) {
+ delete process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR;
+ } else {
+ process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR = originalBinDir;
+ }
+ await Promise.all(tempDirs.splice(0).map(dir => fs.rm(dir, { force: true, recursive: true })));
+});
+
+const createExecutable = async (relativePath: string, source: string): Promise<string> => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-local-tools-bin-'));
+ tempDirs.push(root);
+ const absolutePath = path.join(root, relativePath);
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
+ await fs.writeFile(absolutePath, source, 'utf8');
+ await fs.chmod(absolutePath, 0o755);
+ process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR = root;
+ return absolutePath;
+};
+
+describe('@composio/cli-local-tools bundled binaries', () => {
+ it('resolves and executes platform-specific bundled command binaries', async () => {
+ const platform = detectCliPlatform();
+ const relativePath = path.join(platform, 'fixture-tool');
+ const executablePath = await createExecutable(
+ relativePath,
+ '#!/usr/bin/env bash\nprintf \'{"ok":true,"value":"%s"}\' "$1"\n'
+ );
+
+ const toolkit: LocalToolkitDeclaration = {
+ slug: 'FIXTURE_APP',
+ name: 'Fixture App',
+ description: 'Fixture local toolkit for bundled binary tests.',
+ platforms: [platform],
+ bundledBinaries: [
+ {
+ id: 'fixture-tool',
+ targets: [{ platforms: [platform], path: relativePath }],
+ },
+ ],
+ tools: [
+ {
+ slug: 'RUN_BUNDLED',
+ name: 'Run bundled command',
+ description: 'Runs the bundled fixture executable.',
+ platforms: [platform],
+ inputParams: z.object({ value: z.string() }),
+ execution: {
+ kind: 'command',
+ command: { bundledBinary: 'fixture-tool' },
+ args: input => [String(input.value)],
+ parseJson: true,
+ },
+ },
+ ],
+ };
+ const tool = toolkit.tools[0]!;
+ const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
+
+ const readiness = await checkLocalToolkitsReadiness({
+ currentPlatform: platform,
+ declarations: [toolkit],
+ metaOptions: {
+ path: path.join(os.tmpdir(), `composio-local-tools-test-${Date.now()}.json`),
+ },
+ });
+ expect(readiness.toolkits[0]?.tools[0]?.command?.path).toBe(executablePath);
+
+ const result = await executeLocalTool(
+ tool.execution,
+ { value: 'hello' },
+ { toolkit, tool, finalSlug, platform }
+ );
+
+ expect(result.command).toBe(executablePath);
+ expect(result.parsed).toEqual({ ok: true, value: 'hello' });
+ });
+});
diff --git a/ts/packages/cli-local-tools/src/bundled-binaries.ts b/ts/packages/cli-local-tools/src/bundled-binaries.ts
new file mode 100644
index 000000000..486023c23
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/bundled-binaries.ts
@@ -0,0 +1,126 @@
+import fsSync from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { detectCliPlatform, supportsCliPlatform } from './platform';
+import type {
+ LocalBundledBinaryDeclaration,
+ LocalBundledBinaryRef,
+ LocalCliPlatform,
+ LocalToolkitDeclaration,
+} from './types';
+
+const DEFAULT_BUNDLE_DIR = 'local-tools-binaries';
+
+export interface LocalBundledBinaryResolution {
+ readonly id: string;
+ readonly path: string;
+ readonly platform: LocalCliPlatform;
+ readonly exists: boolean;
+ readonly source: 'bundled' | 'fallback';
+}
+
+export const getLocalToolsBundleRootCandidates = (): ReadonlyArray<string> => {
+ if (process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR?.trim()) {
+ return [process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR.trim()];
+ }
+
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
+ const candidates = [
+ // Bundled CLI JS / unpacked CLI binary sidecar location.
+ path.join(moduleDir, DEFAULT_BUNDLE_DIR),
+ // Package-root asset location when @composio/cli-local-tools is consumed as
+ // a normal dependency and its JS lives under dist/.
+ path.resolve(moduleDir, '..', DEFAULT_BUNDLE_DIR),
+ // Standalone Bun executable zip/install layout: assets live next to the
+ // compiled executable, not inside the virtual module directory.
+ path.join(path.dirname(process.execPath), DEFAULT_BUNDLE_DIR),
+ ];
+
+ return [...new Set(candidates)];
+};
+
+export const getLocalToolsBundleRoot = (): string => {
+ const candidates = getLocalToolsBundleRootCandidates();
+ return candidates.find(candidate => fsSync.existsSync(candidate)) ?? candidates[0];
+};
+
+const hasPathSeparator = (value: string): boolean => value.includes('/') || value.includes('\\');
+
+const binaryExists = async (filePath: string): Promise<boolean> => {
+ try {
+ await fs.access(filePath);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const findDeclaration = (
+ toolkit: LocalToolkitDeclaration,
+ id: string
+): LocalBundledBinaryDeclaration | undefined =>
+ toolkit.bundledBinaries?.find(binary => binary.id === id);
+
+const resolveBundledPaths = (
+ declaration: LocalBundledBinaryDeclaration,
+ platform: LocalCliPlatform
+): ReadonlyArray<string> => {
+ const target = declaration.targets.find(candidate =>
+ supportsCliPlatform(candidate.platforms, platform)
+ );
+ if (!target) return [];
+ return getLocalToolsBundleRootCandidates().map(root => path.resolve(root, target.path));
+};
+
+export const resolveBundledBinary = async (
+ toolkit: LocalToolkitDeclaration,
+ ref: LocalBundledBinaryRef,
+ options: { readonly currentPlatform?: LocalCliPlatform } = {}
+): Promise<LocalBundledBinaryResolution | undefined> => {
+ const currentPlatform = options.currentPlatform ?? detectCliPlatform();
+ const declaration = findDeclaration(toolkit, ref.bundledBinary);
+ const bundledPaths = declaration ? resolveBundledPaths(declaration, currentPlatform) : [];
+ for (const bundledPath of bundledPaths) {
+ if (await binaryExists(bundledPath)) {
+ return {
+ id: ref.bundledBinary,
+ path: bundledPath,
+ platform: currentPlatform,
+ exists: true,
+ source: 'bundled',
+ };
+ }
+ }
+
+ if (
+ ref.fallbackCommand &&
+ hasPathSeparator(ref.fallbackCommand) &&
+ (await binaryExists(ref.fallbackCommand))
+ ) {
+ return {
+ id: ref.bundledBinary,
+ path: ref.fallbackCommand,
+ platform: currentPlatform,
+ exists: true,
+ source: 'fallback',
+ };
+ }
+
+ return bundledPaths[0]
+ ? {
+ id: ref.bundledBinary,
+ path: bundledPaths[0],
+ platform: currentPlatform,
+ exists: false,
+ source: 'bundled',
+ }
+ : undefined;
+};
+
+export const ensureBundledBinaryExecutable = async (filePath: string): Promise<void> => {
+ if (process.platform === 'win32') return;
+ const stat = await fs.stat(filePath);
+ if ((stat.mode & 0o111) !== 0) return;
+ await fs.chmod(filePath, stat.mode | 0o755);
+};
diff --git a/ts/packages/cli-local-tools/src/index.ts b/ts/packages/cli-local-tools/src/index.ts
new file mode 100644
index 000000000..d32edee22
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/index.ts
@@ -0,0 +1,7 @@
+export * from './types';
+export * from './platform';
+export * from './meta';
+export * from './runtime';
+export * from './bundled-binaries';
+export * from './readiness';
+export * from './registry';
diff --git a/ts/packages/cli-local-tools/src/meta.ts b/ts/packages/cli-local-tools/src/meta.ts
new file mode 100644
index 000000000..a64cfabaa
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/meta.ts
@@ -0,0 +1,158 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+export const LOCAL_TOOLS_META_VERSION = 1;
+
+export interface LocalToolMetaEntry {
+ readonly authenticated?: boolean;
+ readonly auth?: {
+ readonly type?: string;
+ readonly account?: string;
+ readonly env?: Record<string, string>;
+ readonly data?: Record<string, unknown>;
+ };
+ readonly installation?: {
+ /** Override the command/binary used by CLI-backed local tools. */
+ readonly command?: string;
+ readonly path?: string;
+ readonly version?: string;
+ };
+ readonly disabled?: boolean;
+ readonly notes?: string;
+ readonly updatedAt?: string;
+ readonly metadata?: Record<string, unknown>;
+}
+
+export type LocalToolkitMetaEntry = LocalToolMetaEntry;
+
+export interface LocalToolsMetaFile {
+ readonly version: number;
+ readonly updatedAt?: string;
+ readonly tools: Record<string, LocalToolMetaEntry>;
+ readonly toolkits: Record<string, LocalToolkitMetaEntry>;
+}
+
+export interface LocalToolsMetaOptions {
+ readonly homeDir?: string;
+ readonly path?: string;
+}
+
+export const getLocalToolsMetaPath = (options: LocalToolsMetaOptions = {}): string =>
+ options.path ??
+ process.env.COMPOSIO_LOCAL_TOOLS_PATH ??
+ path.join(options.homeDir ?? os.homedir(), 'composio', 'local_tools.json');
+
+export const createEmptyLocalToolsMeta = (): LocalToolsMetaFile => ({
+ version: LOCAL_TOOLS_META_VERSION,
+ tools: {},
+ toolkits: {},
+});
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const parseLocalToolsMeta = (raw: string): LocalToolsMetaFile => {
+ const parsed = JSON.parse(raw) as unknown;
+ if (!isRecord(parsed)) {
+ return createEmptyLocalToolsMeta();
+ }
+ return {
+ version: typeof parsed.version === 'number' ? parsed.version : LOCAL_TOOLS_META_VERSION,
+ updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : undefined,
+ tools: isRecord(parsed.tools) ? (parsed.tools as Record<string, LocalToolMetaEntry>) : {},
+ toolkits: isRecord(parsed.toolkits)
+ ? (parsed.toolkits as Record<string, LocalToolkitMetaEntry>)
+ : {},
+ };
+};
+
+export const readLocalToolsMeta = async (
+ options: LocalToolsMetaOptions = {}
+): Promise<LocalToolsMetaFile> => {
+ const filePath = getLocalToolsMetaPath(options);
+ try {
+ return parseLocalToolsMeta(await fs.readFile(filePath, 'utf8'));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ return createEmptyLocalToolsMeta();
+ }
+ throw error;
+ }
+};
+
+export const writeLocalToolsMeta = async (
+ meta: LocalToolsMetaFile,
+ options: LocalToolsMetaOptions = {}
+): Promise<void> => {
+ const filePath = getLocalToolsMetaPath(options);
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
+ const next: LocalToolsMetaFile = {
+ ...meta,
+ version: LOCAL_TOOLS_META_VERSION,
+ updatedAt: new Date().toISOString(),
+ };
+ await fs.writeFile(filePath, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
+};
+
+export const getLocalToolMeta = async (
+ finalSlug: string,
+ options: LocalToolsMetaOptions = {}
+): Promise<LocalToolMetaEntry | undefined> => {
+ const meta = await readLocalToolsMeta(options);
+ return meta.tools[finalSlug.toUpperCase()] ?? meta.tools[finalSlug];
+};
+
+export const getLocalToolkitMeta = async (
+ toolkitSlug: string,
+ options: LocalToolsMetaOptions = {}
+): Promise<LocalToolkitMetaEntry | undefined> => {
+ const meta = await readLocalToolsMeta(options);
+ return meta.toolkits[toolkitSlug.toLowerCase()] ?? meta.toolkits[toolkitSlug];
+};
+
+export const updateLocalToolMeta = async (
+ finalSlug: string,
+ patch: LocalToolMetaEntry,
+ options: LocalToolsMetaOptions = {}
+): Promise<LocalToolsMetaFile> => {
+ const meta = await readLocalToolsMeta(options);
+ const key = finalSlug.toUpperCase();
+ const previous = meta.tools[key] ?? {};
+ const next: LocalToolsMetaFile = {
+ ...meta,
+ tools: {
+ ...meta.tools,
+ [key]: {
+ ...previous,
+ ...patch,
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ };
+ await writeLocalToolsMeta(next, options);
+ return next;
+};
+
+export const updateLocalToolkitMeta = async (
+ toolkitSlug: string,
+ patch: LocalToolkitMetaEntry,
+ options: LocalToolsMetaOptions = {}
+): Promise<LocalToolsMetaFile> => {
+ const meta = await readLocalToolsMeta(options);
+ const key = toolkitSlug.toLowerCase();
+ const previous = meta.toolkits[key] ?? {};
+ const next: LocalToolsMetaFile = {
+ ...meta,
+ toolkits: {
+ ...meta.toolkits,
+ [key]: {
+ ...previous,
+ ...patch,
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ };
+ await writeLocalToolsMeta(next, options);
+ return next;
+};
diff --git a/ts/packages/cli-local-tools/src/platform.ts b/ts/packages/cli-local-tools/src/platform.ts
new file mode 100644
index 000000000..5a9718700
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/platform.ts
@@ -0,0 +1,40 @@
+import type { LocalCliPlatform } from './types';
+
+export interface DetectPlatformInput {
+ readonly platform?: NodeJS.Platform;
+ readonly arch?: NodeJS.Architecture | string;
+}
+
+export const detectCliPlatform = (input: DetectPlatformInput = {}): LocalCliPlatform => {
+ const platform = input.platform ?? process.platform;
+ const arch = input.arch ?? process.arch;
+ if (platform === 'darwin') {
+ return arch === 'x64' ? 'darwin-x64' : 'darwin-arm64';
+ }
+ if (platform === 'linux') {
+ return arch === 'arm64' ? 'linux-arm64' : 'linux-x64';
+ }
+ if (platform === 'win32') {
+ return arch === 'arm64' ? 'win32-arm64' : 'win32-x64';
+ }
+ return 'all';
+};
+
+const platformFamily = (platform: LocalCliPlatform): LocalCliPlatform => {
+ if (platform.startsWith('darwin')) return 'darwin';
+ if (platform.startsWith('linux')) return 'linux';
+ if (platform.startsWith('win32')) return 'win32';
+ return platform;
+};
+
+export const supportsCliPlatform = (
+ supportedPlatforms: ReadonlyArray<LocalCliPlatform>,
+ currentPlatform: LocalCliPlatform = detectCliPlatform()
+): boolean => {
+ if (supportedPlatforms.includes('all')) return true;
+ if (supportedPlatforms.includes(currentPlatform)) return true;
+ return supportedPlatforms.includes(platformFamily(currentPlatform));
+};
+
+export const formatSupportedPlatforms = (platforms: ReadonlyArray<LocalCliPlatform>): string =>
+ platforms.includes('all') ? 'all CLI platforms' : platforms.join(', ');
diff --git a/ts/packages/cli-local-tools/src/readiness.ts b/ts/packages/cli-local-tools/src/readiness.ts
new file mode 100644
index 000000000..20e19ca70
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/readiness.ts
@@ -0,0 +1,460 @@
+import { constants as fsConstants } from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { resolveBundledBinary } from './bundled-binaries';
+import { detectCliPlatform, formatSupportedPlatforms, supportsCliPlatform } from './platform';
+import { readLocalToolsMeta, type LocalToolsMetaOptions } from './meta';
+import { localToolkitDeclarations, normalizeLocalToolSlug } from './registry';
+import type {
+ LocalBundledBinaryRef,
+ LocalCliPlatform,
+ LocalCommandInvocation,
+ LocalMcpServerSpec,
+ LocalToolkitDeclaration,
+ LocalToolDeclaration,
+ LocalToolExecution,
+} from './types';
+
+export type LocalReadinessStatus =
+ | 'ready'
+ | 'unsupported'
+ | 'disabled'
+ | 'missing'
+ | 'not_implemented'
+ | 'unknown';
+
+export interface LocalCommandReadiness {
+ readonly command: string;
+ readonly args?: ReadonlyArray<string>;
+ readonly found: boolean;
+ readonly path?: string;
+}
+
+export interface LocalToolReadiness {
+ readonly finalSlug: string;
+ readonly slug: string;
+ readonly name: string;
+ readonly toolkitSlug: string;
+ readonly executionKind: LocalToolExecution['kind'];
+ readonly platforms: ReadonlyArray<LocalCliPlatform>;
+ readonly supported: boolean;
+ readonly status: LocalReadinessStatus;
+ readonly command?: LocalCommandReadiness;
+ readonly messages: ReadonlyArray<string>;
+ readonly hints: ReadonlyArray<string>;
+}
+
+export interface LocalToolkitReadiness {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly platforms: ReadonlyArray<LocalCliPlatform>;
+ readonly supported: boolean;
+ readonly status: LocalReadinessStatus;
+ readonly source?: LocalToolkitDeclaration['source'];
+ readonly setup?: LocalToolkitDeclaration['setup'];
+ readonly tools: ReadonlyArray<LocalToolReadiness>;
+ readonly messages: ReadonlyArray<string>;
+ readonly hints: ReadonlyArray<string>;
+}
+
+export interface LocalToolsReadinessReport {
+ readonly currentPlatform: LocalCliPlatform;
+ readonly toolkits: ReadonlyArray<LocalToolkitReadiness>;
+}
+
+const toolkitMatchesFilter = (
+ toolkit: LocalToolkitDeclaration,
+ requestedToolkits?: ReadonlyArray<string>
+): boolean => {
+ if (!requestedToolkits || requestedToolkits.length === 0) return true;
+ const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
+ return requested.has(toolkit.slug.toLowerCase());
+};
+
+const statusPriority: Record<LocalReadinessStatus, number> = {
+ ready: 0,
+ unknown: 1,
+ not_implemented: 2,
+ missing: 3,
+ disabled: 4,
+ unsupported: 5,
+};
+
+const aggregateStatus = (statuses: ReadonlyArray<LocalReadinessStatus>): LocalReadinessStatus => {
+ if (statuses.length === 0) return 'unknown';
+ return statuses.reduce((current, next) =>
+ statusPriority[next] > statusPriority[current] ? next : current
+ );
+};
+
+const resolveValue = <T>(
+ value: T | ((input: Record<string, unknown>) => T),
+ input: Record<string, unknown> = {}
+): T =>
+ typeof value === 'function' ? (value as (input: Record<string, unknown>) => T)(input) : value;
+
+const splitPathEntries = (pathValue: string | undefined): ReadonlyArray<string> =>
+ (pathValue ?? '')
+ .split(path.delimiter)
+ .map(entry => entry.trim())
+ .filter(Boolean);
+
+const hasPathSeparator = (command: string): boolean =>
+ command.includes('/') || command.includes('\\');
+
+const executableCandidates = (command: string): ReadonlyArray<string> => {
+ if (process.platform !== 'win32') return [command];
+ const extensions = (process.env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM')
+ .split(';')
+ .map(ext => ext.trim())
+ .filter(Boolean);
+ if (extensions.some(ext => command.toUpperCase().endsWith(ext.toUpperCase()))) return [command];
+ return extensions.map(ext => `${command}${ext}`);
+};
+
+const canExecute = async (filePath: string): Promise<boolean> => {
+ try {
+ await fs.access(filePath, fsConstants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+export const findExecutableOnPath = async (command: string): Promise<string | undefined> => {
+ const trimmed = command.trim();
+ if (!trimmed) return undefined;
+
+ if (path.isAbsolute(trimmed) || hasPathSeparator(trimmed)) {
+ for (const candidate of executableCandidates(trimmed)) {
+ if (await canExecute(candidate)) return candidate;
+ }
+ return undefined;
+ }
+
+ for (const pathEntry of splitPathEntries(process.env.PATH)) {
+ for (const candidate of executableCandidates(path.join(pathEntry, trimmed))) {
+ if (await canExecute(candidate)) return candidate;
+ }
+ }
+
+ return undefined;
+};
+
+const getToolkitMeta = (
+ meta: Awaited<ReturnType<typeof readLocalToolsMeta>>,
+ toolkitSlug: string
+) => meta.toolkits[toolkitSlug.toLowerCase()] ?? meta.toolkits[toolkitSlug];
+
+const getToolMeta = (meta: Awaited<ReturnType<typeof readLocalToolsMeta>>, finalSlug: string) =>
+ meta.tools[finalSlug.toUpperCase()] ?? meta.tools[finalSlug];
+
+const isBundledBinaryRef = (value: unknown): value is LocalBundledBinaryRef =>
+ typeof value === 'object' &&
+ value !== null &&
+ 'bundledBinary' in value &&
+ typeof (value as { bundledBinary?: unknown }).bundledBinary === 'string';
+
+const resolveCommandSpec = async (
+ execution: Extract<LocalToolExecution, { kind: 'command' }>,
+ params: {
+ readonly toolkit: LocalToolkitDeclaration;
+ readonly currentPlatform: LocalCliPlatform;
+ readonly commandOverride?: string;
+ }
+): Promise<LocalCommandInvocation> => {
+ const commandValue = resolveValue(execution.command);
+ const invocation: LocalCommandInvocation =
+ typeof commandValue === 'string'
+ ? { command: commandValue }
+ : isBundledBinaryRef(commandValue)
+ ? await (async () => {
+ const resolved = await resolveBundledBinary(params.toolkit, commandValue, {
+ currentPlatform: params.currentPlatform,
+ });
+ return {
+ command: resolved?.exists
+ ? resolved.path
+ : (commandValue.fallbackCommand ?? resolved?.path ?? commandValue.bundledBinary),
+ };
+ })()
+ : commandValue;
+ return {
+ ...invocation,
+ command: params.commandOverride ?? invocation.command,
+ args: invocation.args ?? (execution.args ? resolveValue(execution.args) : undefined),
+ };
+};
+
+const resolveMcpServer = (
+ execution: Extract<LocalToolExecution, { kind: 'mcp' }>
+): LocalMcpServerSpec => resolveValue(execution.server);
+
+const setupHintsForToolkit = (toolkit: LocalToolkitDeclaration): ReadonlyArray<string> => [
+ ...(toolkit.setup?.install ? [toolkit.setup.install] : []),
+ ...(toolkit.setup?.commandOverrides ?? []),
+ ...(toolkit.setup?.notes ?? []),
+];
+
+const checkCommand = async (
+ command: string,
+ args?: ReadonlyArray<string>
+): Promise<LocalCommandReadiness> => {
+ const executablePath = await findExecutableOnPath(command);
+ return {
+ command,
+ ...(args ? { args } : {}),
+ found: executablePath !== undefined,
+ ...(executablePath ? { path: executablePath } : {}),
+ };
+};
+
+const checkToolReadiness = async (params: {
+ readonly toolkit: LocalToolkitDeclaration;
+ readonly tool: LocalToolDeclaration;
+ readonly currentPlatform: LocalCliPlatform;
+ readonly toolkitDisabled: boolean;
+ readonly commandOverride?: string;
+ readonly toolDisabled: boolean;
+}): Promise<LocalToolReadiness> => {
+ const { toolkit, tool, currentPlatform, toolkitDisabled, commandOverride, toolDisabled } = params;
+ const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
+ const supported =
+ supportsCliPlatform(toolkit.platforms, currentPlatform) &&
+ supportsCliPlatform(tool.platforms, currentPlatform);
+ const base = {
+ finalSlug,
+ slug: tool.slug,
+ name: tool.name,
+ toolkitSlug: toolkit.slug,
+ executionKind: tool.execution.kind,
+ platforms: tool.platforms,
+ supported,
+ } as const;
+
+ if (!supported) {
+ return {
+ ...base,
+ status: 'unsupported',
+ messages: [
+ `Unsupported on ${currentPlatform}; tool platforms: ${formatSupportedPlatforms(tool.platforms)}.`,
+ ],
+ hints: setupHintsForToolkit(toolkit),
+ };
+ }
+
+ if (toolkitDisabled || toolDisabled) {
+ return {
+ ...base,
+ status: 'disabled',
+ messages: ['Disabled by ~/composio/local_tools.json metadata.'],
+ hints: ['Remove disabled=true from the toolkit/tool metadata entry to re-enable it.'],
+ };
+ }
+
+ if (tool.execution.kind === 'command') {
+ try {
+ const invocation = await resolveCommandSpec(tool.execution, {
+ toolkit,
+ currentPlatform,
+ commandOverride,
+ });
+ const command = await checkCommand(invocation.command, invocation.args);
+ return {
+ ...base,
+ status: command.found ? 'ready' : 'missing',
+ command,
+ messages: command.found
+ ? [`Command found: ${command.path ?? command.command}.`]
+ : [`Command not found on PATH: ${command.command}.`],
+ hints: command.found
+ ? []
+ : [
+ ...setupHintsForToolkit(toolkit),
+ `Set ${finalSlug}.installation.command or ${toolkit.slug.toLowerCase()}.installation.command in ~/composio/local_tools.json to override the binary.`,
+ ],
+ };
+ } catch (error) {
+ return {
+ ...base,
+ status: 'unknown',
+ messages: [
+ `Could not resolve command wrapper: ${error instanceof Error ? error.message : String(error)}.`,
+ ],
+ hints: setupHintsForToolkit(toolkit),
+ };
+ }
+ }
+
+ if (tool.execution.kind === 'mcp') {
+ try {
+ const server = resolveMcpServer(tool.execution);
+ const command = await checkCommand(server.command, server.args);
+ return {
+ ...base,
+ status: command.found ? 'ready' : 'missing',
+ command,
+ messages: command.found
+ ? [`MCP server launcher found: ${command.path ?? command.command}.`]
+ : [`MCP server launcher not found on PATH: ${command.command}.`],
+ hints: command.found ? (toolkit.setup?.notes ?? []) : setupHintsForToolkit(toolkit),
+ };
+ } catch (error) {
+ return {
+ ...base,
+ status: 'unknown',
+ messages: [
+ `Could not resolve MCP server wrapper: ${error instanceof Error ? error.message : String(error)}.`,
+ ],
+ hints: setupHintsForToolkit(toolkit),
+ };
+ }
+ }
+
+ if (tool.execution.kind === 'ffi') {
+ const library = tool.execution.library;
+ const libraryPath =
+ typeof library === 'string'
+ ? library
+ : ((await resolveBundledBinary(toolkit, library, { currentPlatform }))?.path ??
+ library.fallbackCommand);
+ const found = libraryPath
+ ? await fs.access(libraryPath).then(
+ () => true,
+ () => false
+ )
+ : false;
+ const bunAvailable = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
+ return {
+ ...base,
+ status: found ? (bunAvailable ? 'ready' : 'unknown') : 'missing',
+ messages: [
+ found
+ ? `FFI library found: ${libraryPath}.`
+ : `FFI library not found${typeof library === 'string' ? `: ${library}` : ` for bundled binary ${library.bundledBinary}`}.`,
+ bunAvailable
+ ? 'Bun FFI runtime is available.'
+ : 'Bun FFI runtime is not available in this process; packaged CLI execution is required.',
+ ],
+ hints: found && bunAvailable ? [] : setupHintsForToolkit(toolkit),
+ };
+ }
+
+ if (tool.execution.kind === 'native' && tool.execution.readiness) {
+ const command = await checkCommand(
+ commandOverride ?? tool.execution.readiness.command,
+ tool.execution.readiness.args
+ );
+ return {
+ ...base,
+ status: command.found ? 'ready' : 'missing',
+ command,
+ messages: command.found
+ ? [
+ `Native wrapper prerequisite found: ${command.path ?? command.command}; app-specific runtime checks still happen at execution time.`,
+ ]
+ : [`Native wrapper prerequisite not found on PATH: ${command.command}.`],
+ hints: command.found ? [] : setupHintsForToolkit(toolkit),
+ };
+ }
+
+ if (tool.execution.kind === 'native' && toolkit.bundledBinaries?.length) {
+ const bundledChecks = await Promise.all(
+ toolkit.bundledBinaries.map(async binary => ({
+ binary,
+ resolved: await resolveBundledBinary(
+ toolkit,
+ { bundledBinary: binary.id },
+ { currentPlatform }
+ ),
+ }))
+ );
+ const missing = bundledChecks.filter(check => check.resolved?.exists !== true);
+ return {
+ ...base,
+ status: missing.length === 0 ? 'ready' : 'missing',
+ messages:
+ missing.length === 0
+ ? bundledChecks.map(
+ check => `Bundled local binary found: ${check.resolved?.path ?? check.binary.id}.`
+ )
+ : missing.map(check => `Bundled local binary not found: ${check.binary.id}.`),
+ hints: missing.length === 0 ? [] : setupHintsForToolkit(toolkit),
+ };
+ }
+
+ return {
+ ...base,
+ status: 'unknown',
+ messages: ['Native local tool wrapper will self-check at execution time.'],
+ hints: setupHintsForToolkit(toolkit),
+ };
+};
+
+export const checkLocalToolkitsReadiness = async (
+ options: {
+ readonly currentPlatform?: LocalCliPlatform;
+ readonly toolkits?: ReadonlyArray<string>;
+ readonly includeUnsupported?: boolean;
+ readonly metaOptions?: LocalToolsMetaOptions;
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): Promise<LocalToolsReadinessReport> => {
+ const currentPlatform = options.currentPlatform ?? detectCliPlatform();
+ const meta = await readLocalToolsMeta(options.metaOptions);
+ const toolkits = (options.declarations ?? localToolkitDeclarations).filter(toolkit =>
+ toolkitMatchesFilter(toolkit, options.toolkits)
+ );
+ const visibleToolkits = options.includeUnsupported
+ ? toolkits
+ : toolkits.filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform));
+
+ const reports = await Promise.all(
+ visibleToolkits.map(async toolkit => {
+ const toolkitMeta = getToolkitMeta(meta, toolkit.slug);
+ const toolkitSupported = supportsCliPlatform(toolkit.platforms, currentPlatform);
+ const toolkitDisabled = toolkitMeta?.disabled === true;
+ const tools = await Promise.all(
+ toolkit.tools.map(tool => {
+ const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
+ const toolMeta = getToolMeta(meta, finalSlug);
+ return checkToolReadiness({
+ toolkit,
+ tool,
+ currentPlatform,
+ toolkitDisabled,
+ toolDisabled: toolMeta?.disabled === true,
+ commandOverride: toolMeta?.installation?.command ?? toolkitMeta?.installation?.command,
+ });
+ })
+ );
+ const status = toolkitSupported
+ ? toolkitDisabled
+ ? 'disabled'
+ : aggregateStatus(tools.map(tool => tool.status))
+ : 'unsupported';
+ return {
+ slug: toolkit.slug,
+ name: toolkit.name,
+ description: toolkit.description,
+ platforms: toolkit.platforms,
+ supported: toolkitSupported,
+ status,
+ source: toolkit.source,
+ setup: toolkit.setup,
+ tools,
+ messages: toolkitSupported
+ ? toolkitDisabled
+ ? ['Disabled by ~/composio/local_tools.json metadata.']
+ : []
+ : [
+ `Unsupported on ${currentPlatform}; toolkit platforms: ${formatSupportedPlatforms(toolkit.platforms)}.`,
+ ],
+ hints: status === 'ready' ? [] : setupHintsForToolkit(toolkit),
+ } satisfies LocalToolkitReadiness;
+ })
+ );
+
+ return { currentPlatform, toolkits: reports };
+};
diff --git a/ts/packages/cli-local-tools/src/registry.test.ts b/ts/packages/cli-local-tools/src/registry.test.ts
new file mode 100644
index 000000000..f8b3abd81
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/registry.test.ts
@@ -0,0 +1,121 @@
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { z } from 'zod/v3';
+import {
+ createLocalToolRouterExperimentalPayload,
+ getLocalToolkitDeclarations,
+ getLocalToolInputDefinition,
+ localToolkitDeclarations,
+ normalizeLocalToolSlug,
+} from './registry';
+import { checkLocalToolkitsReadiness } from './readiness';
+import type { LocalToolkitDeclaration } from './types';
+
+const fixtureToolkit: LocalToolkitDeclaration = {
+ slug: 'FIXTURE_APP',
+ name: 'Fixture App',
+ description: 'Fixture local toolkit for registry tests.',
+ platforms: ['darwin-arm64', 'linux-x64'],
+ tools: [
+ {
+ slug: 'RUN_COMMAND',
+ name: 'Run fixture command',
+ description: 'Runs a fixture command.',
+ platforms: ['darwin-arm64', 'linux-x64'],
+ inputParams: z.object({
+ args: z.array(z.string()).default([]),
+ }),
+ execution: {
+ kind: 'command',
+ command: 'node',
+ args: input => (Array.isArray(input.args) ? input.args.map(String) : []),
+ },
+ },
+ ],
+};
+
+const findToolkit = (
+ payload: ReturnType<typeof createLocalToolRouterExperimentalPayload>,
+ slug: string
+) => payload?.custom_toolkits?.find(toolkit => toolkit.slug === slug);
+
+describe('@composio/cli-local-tools registry', () => {
+ it('registers concrete local toolkits in the integration layer', () => {
+ expect(localToolkitDeclarations.map(toolkit => toolkit.slug)).toEqual(
+ expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
+ );
+ expect(
+ localToolkitDeclarations
+ .find(toolkit => toolkit.slug === 'BEEPER_IMESSAGE')
+ ?.tools.map(tool => tool.slug)
+ ).toEqual(expect.arrayContaining(['LIST_THREADS', 'SEND_MESSAGE', 'AUTHORIZE']));
+ expect(
+ localToolkitDeclarations
+ .find(toolkit => toolkit.slug === 'CHROME_DEVTOOLS')
+ ?.tools.map(tool => tool.slug)
+ ).toEqual(expect.arrayContaining(['LIST_PAGES', 'NEW_PAGE', 'EVALUATE_SCRIPT']));
+ expect(
+ localToolkitDeclarations
+ .find(toolkit => toolkit.slug === 'PEEKABOO')
+ ?.tools.map(tool => tool.slug)
+ ).toEqual(expect.arrayContaining(['PERMISSIONS_STATUS', 'SEE', 'CLICK']));
+ });
+
+ it('normalizes local tool slugs to the Tool Router LOCAL_<TOOLKIT>_<TOOL> shape', () => {
+ expect(normalizeLocalToolSlug('RUN_CLI', 'EXAMPLE_APP')).toBe('LOCAL_EXAMPLE_APP_RUN_CLI');
+ });
+
+ it('filters declarations by platform', () => {
+ expect(
+ getLocalToolkitDeclarations({
+ currentPlatform: 'linux-x64',
+ declarations: [fixtureToolkit],
+ }).map(toolkit => toolkit.slug)
+ ).toEqual(['FIXTURE_APP']);
+ expect(
+ getLocalToolkitDeclarations({
+ currentPlatform: 'win32-x64',
+ declarations: [fixtureToolkit],
+ }).map(toolkit => toolkit.slug)
+ ).toEqual([]);
+ });
+
+ it('builds Tool Router custom toolkit payloads for supported local toolkits', () => {
+ const payload = createLocalToolRouterExperimentalPayload({
+ currentPlatform: 'darwin-arm64',
+ toolkits: ['fixture_app'],
+ declarations: [fixtureToolkit],
+ });
+
+ expect(payload?.custom_toolkits).toHaveLength(1);
+ expect(findToolkit(payload, 'FIXTURE_APP')?.tools.map(tool => tool.slug)).toEqual([
+ 'RUN_COMMAND',
+ ]);
+ });
+
+ it('exposes local input schemas for CLI --get-schema and dry-run validation', () => {
+ const definition = getLocalToolInputDefinition('LOCAL_FIXTURE_APP_RUN_COMMAND', {
+ declarations: [fixtureToolkit],
+ });
+ expect(definition?.version).toBe('local');
+ expect(definition?.schema.properties).toHaveProperty('args');
+ });
+
+ it('reports platform readiness for supplied local toolkit declarations', async () => {
+ const report = await checkLocalToolkitsReadiness({
+ currentPlatform: 'linux-x64',
+ includeUnsupported: true,
+ declarations: [fixtureToolkit],
+ metaOptions: {
+ path: path.join(os.tmpdir(), `composio-local-tools-test-${Date.now()}.json`),
+ },
+ });
+
+ expect(report.toolkits.find(toolkit => toolkit.slug === 'FIXTURE_APP')?.tools).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ finalSlug: 'LOCAL_FIXTURE_APP_RUN_COMMAND' }),
+ ])
+ );
+ });
+});
diff --git a/ts/packages/cli-local-tools/src/registry.ts b/ts/packages/cli-local-tools/src/registry.ts
new file mode 100644
index 000000000..6c261f964
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/registry.ts
@@ -0,0 +1,285 @@
+import zodToJsonSchema from 'zod-to-json-schema';
+import { beeperImessageToolkit } from './toolkits/beeper-imessage';
+import { chromeDevtoolsToolkit } from './toolkits/chrome-devtools';
+import { peekabooToolkit } from './toolkits/peekaboo';
+import type { z } from 'zod/v3';
+import { formatSupportedPlatforms, detectCliPlatform, supportsCliPlatform } from './platform';
+import { executeLocalTool } from './runtime';
+import type {
+ LocalCliPlatform,
+ LocalToolkitDeclaration,
+ LocalToolDeclaration,
+ LocalToolResolution,
+ LocalToolRouterExperimentalPayload,
+} from './types';
+
+export const LOCAL_TOOL_PREFIX = 'LOCAL_';
+
+interface LocalCustomTool {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputSchema: Record<string, unknown>;
+ readonly outputSchema?: Record<string, unknown>;
+}
+
+interface LocalCustomToolkit {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly tools: ReadonlyArray<LocalCustomTool>;
+}
+
+/**
+ * Built-in local toolkits shipped with @composio/cli-local-tools.
+ *
+ * The foundation package intentionally starts empty. Concrete integrations are
+ * added in separate stack PRs so each app can be reviewed and validated on its
+ * own.
+ */
+export const localToolkitDeclarations: ReadonlyArray<LocalToolkitDeclaration> = [
+ beeperImessageToolkit,
+ chromeDevtoolsToolkit,
+ peekabooToolkit,
+];
+
+const normalizeSegment = (value: string): string =>
+ value
+ .toUpperCase()
+ .replace(/[^A-Z0-9]+/g, '_')
+ .replace(/^_+|_+$/g, '');
+
+export const normalizeLocalToolSlug = (toolSlug: string, toolkitSlug?: string): string =>
+ toolkitSlug
+ ? `${LOCAL_TOOL_PREFIX}${normalizeSegment(toolkitSlug)}_${normalizeSegment(toolSlug)}`
+ : `${LOCAL_TOOL_PREFIX}${normalizeSegment(toolSlug)}`;
+
+const descriptionWithPlatform = (
+ description: string,
+ platforms: ReadonlyArray<LocalCliPlatform>
+): string => `${description}\n\nLocal CLI platforms: ${formatSupportedPlatforms(platforms)}.`;
+
+const zodObjectToJsonSchema = (schema: z.ZodTypeAny): Record<string, unknown> => {
+ const converted = zodToJsonSchema(schema, { name: 'input' }) as {
+ definitions?: { input?: Record<string, unknown> };
+ } & Record<string, unknown>;
+ const inputDefinition = converted.definitions?.input ?? converted;
+ return {
+ type: 'object',
+ properties:
+ inputDefinition.properties && typeof inputDefinition.properties === 'object'
+ ? (inputDefinition.properties as Record<string, unknown>)
+ : {},
+ ...(Array.isArray(inputDefinition.required) ? { required: inputDefinition.required } : {}),
+ };
+};
+
+const zodToOutputJsonSchema = (schema: z.ZodTypeAny): Record<string, unknown> => {
+ const converted = zodToJsonSchema(schema, { name: 'output' }) as {
+ definitions?: { output?: Record<string, unknown> };
+ } & Record<string, unknown>;
+ return converted.definitions?.output ?? converted;
+};
+
+const toCustomTool = (
+ toolkit: LocalToolkitDeclaration,
+ tool: LocalToolDeclaration
+): LocalCustomTool => ({
+ slug: tool.slug,
+ name: tool.name,
+ description: descriptionWithPlatform(tool.description, tool.platforms),
+ inputSchema: zodObjectToJsonSchema(tool.inputParams as z.ZodTypeAny),
+ ...(tool.outputParams ? { outputSchema: zodToOutputJsonSchema(tool.outputParams) } : {}),
+});
+
+const toCustomToolkit = (
+ toolkit: LocalToolkitDeclaration,
+ tools: ReadonlyArray<LocalCustomTool>
+): LocalCustomToolkit => ({
+ slug: toolkit.slug,
+ name: toolkit.name,
+ description: descriptionWithPlatform(toolkit.description, toolkit.platforms),
+ tools,
+});
+
+const toolkitMatchesFilter = (
+ toolkit: LocalToolkitDeclaration,
+ requestedToolkits?: ReadonlyArray<string>
+): boolean => {
+ if (!requestedToolkits || requestedToolkits.length === 0) return true;
+ const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
+ return requested.has(toolkit.slug.toLowerCase());
+};
+
+const declarationsFor = (
+ declarations: ReadonlyArray<LocalToolkitDeclaration> | undefined
+): ReadonlyArray<LocalToolkitDeclaration> => declarations ?? localToolkitDeclarations;
+
+export const getAllLocalToolkitSlugs = (
+ options: {
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): ReadonlyArray<string> =>
+ declarationsFor(options.declarations).map(toolkit => toolkit.slug.toLowerCase());
+
+export const isLocalToolkitSlug = (
+ toolkitSlug: string | undefined,
+ options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
+): boolean => {
+ if (!toolkitSlug) return false;
+ const lower = toolkitSlug.toLowerCase();
+ return getAllLocalToolkitSlugs(options).includes(lower);
+};
+
+export const isLocalToolSlug = (
+ toolSlug: string,
+ options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
+): boolean => {
+ const upper = toolSlug.toUpperCase();
+ if (!upper.startsWith(LOCAL_TOOL_PREFIX)) return false;
+ return (
+ resolveLocalTool(toolSlug, { includeUnsupported: true, declarations: options.declarations }) !==
+ null
+ );
+};
+
+export const getLocalToolkitDeclarations = (
+ options: {
+ readonly currentPlatform?: LocalCliPlatform;
+ readonly toolkits?: ReadonlyArray<string>;
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): ReadonlyArray<LocalToolkitDeclaration> => {
+ const currentPlatform = options.currentPlatform ?? detectCliPlatform();
+ return declarationsFor(options.declarations)
+ .filter(toolkit => toolkitMatchesFilter(toolkit, options.toolkits))
+ .filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform))
+ .map(toolkit => ({
+ ...toolkit,
+ tools: toolkit.tools.filter(tool => supportsCliPlatform(tool.platforms, currentPlatform)),
+ }))
+ .filter(toolkit => toolkit.tools.length > 0);
+};
+
+export const getLocalCustomToolkits = (
+ options: {
+ readonly currentPlatform?: LocalCliPlatform;
+ readonly toolkits?: ReadonlyArray<string>;
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): ReadonlyArray<LocalCustomToolkit> =>
+ getLocalToolkitDeclarations(options).map(toolkit =>
+ toCustomToolkit(
+ toolkit,
+ toolkit.tools.map(tool => toCustomTool(toolkit, tool))
+ )
+ );
+
+const customToolkitToPayload = (
+ toolkit: LocalCustomToolkit
+): NonNullable<LocalToolRouterExperimentalPayload['custom_toolkits']>[number] => ({
+ slug: toolkit.slug,
+ name: toolkit.name,
+ description: toolkit.description,
+ tools: toolkit.tools.map(tool => ({
+ slug: tool.slug,
+ name: tool.name,
+ description: tool.description,
+ input_schema: tool.inputSchema,
+ ...(tool.outputSchema ? { output_schema: tool.outputSchema } : {}),
+ })),
+});
+
+export const createLocalToolRouterExperimentalPayload = (
+ options: {
+ readonly currentPlatform?: LocalCliPlatform;
+ readonly toolkits?: ReadonlyArray<string>;
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): LocalToolRouterExperimentalPayload | undefined => {
+ const customToolkits = getLocalCustomToolkits(options).map(customToolkitToPayload);
+ if (customToolkits.length === 0) return undefined;
+ return { custom_toolkits: customToolkits };
+};
+
+export const resolveLocalTool = (
+ slug: string,
+ options: {
+ readonly currentPlatform?: LocalCliPlatform;
+ readonly includeUnsupported?: boolean;
+ readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
+ } = {}
+): LocalToolResolution | null => {
+ const currentPlatform = options.currentPlatform ?? detectCliPlatform();
+ const target = normalizeSegment(slug);
+
+ for (const toolkit of declarationsFor(options.declarations)) {
+ for (const tool of toolkit.tools) {
+ const finalSlug = normalizeLocalToolSlug(tool.slug, toolkit.slug);
+ const matches =
+ normalizeSegment(finalSlug) === target ||
+ normalizeSegment(tool.slug) === target ||
+ normalizeSegment(`${toolkit.slug}_${tool.slug}`) === target;
+ if (!matches) continue;
+
+ const supported =
+ supportsCliPlatform(toolkit.platforms, currentPlatform) &&
+ supportsCliPlatform(tool.platforms, currentPlatform);
+ if (!supported && !options.includeUnsupported) return null;
+ return { toolkit, tool, finalSlug, supported, currentPlatform };
+ }
+ }
+
+ return null;
+};
+
+export const getLocalToolInputDefinition = (
+ slug: string,
+ options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
+): {
+ readonly finalSlug: string;
+ readonly toolkit: string;
+ readonly schema: Record<string, unknown>;
+ readonly version: 'local';
+} | null => {
+ const resolution = resolveLocalTool(slug, {
+ includeUnsupported: true,
+ declarations: options.declarations,
+ });
+ if (!resolution) return null;
+ return {
+ finalSlug: resolution.finalSlug,
+ toolkit: resolution.toolkit.slug,
+ schema: toCustomTool(resolution.toolkit, resolution.tool).inputSchema,
+ version: 'local',
+ };
+};
+
+export const executeLocalToolBySlug = async (
+ slug: string,
+ args: Record<string, unknown>
+): Promise<Record<string, unknown> | null> => {
+ const resolution = resolveLocalTool(slug, { includeUnsupported: true });
+ if (!resolution) return null;
+ if (!resolution.supported) {
+ throw new Error(
+ `Local tool ${resolution.finalSlug} is not supported on ${resolution.currentPlatform}. Supported platforms: ${formatSupportedPlatforms(resolution.tool.platforms)}.`
+ );
+ }
+
+ const parsed = resolution.tool.inputParams.safeParse(args);
+ if (!parsed.success) {
+ throw new Error(
+ `Invalid arguments for local tool ${resolution.finalSlug}: ${parsed.error.issues
+ .map(issue => `${issue.path.join('.') || '<root>'}: ${issue.message}`)
+ .join('; ')}`
+ );
+ }
+
+ return executeLocalTool(resolution.tool.execution, parsed.data as Record<string, unknown>, {
+ toolkit: resolution.toolkit,
+ tool: resolution.tool,
+ finalSlug: resolution.finalSlug,
+ platform: resolution.currentPlatform,
+ });
+};
diff --git a/ts/packages/cli-local-tools/src/runtime.ts b/ts/packages/cli-local-tools/src/runtime.ts
new file mode 100644
index 000000000..5516e534c
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/runtime.ts
@@ -0,0 +1,294 @@
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { ensureBundledBinaryExecutable, resolveBundledBinary } from './bundled-binaries';
+import type {
+ LocalBundledBinaryRef,
+ LocalCommandExecution,
+ LocalCommandInvocation,
+ LocalCommandValue,
+ LocalExecutionContext,
+ LocalExecutionResult,
+ LocalFfiExecution,
+ LocalFfiLibraryHandle,
+ LocalFfiType,
+ LocalMcpExecution,
+ LocalToolExecution,
+} from './types';
+import { getLocalToolkitMeta, getLocalToolMeta } from './meta';
+
+const toErrorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
+
+const compactEnv = (env: Record<string, string | undefined> | undefined): Record<string, string> =>
+ Object.fromEntries(
+ Object.entries(env ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined)
+ );
+
+const resolveValue = <T>(
+ value: T | ((input: Record<string, unknown>) => T),
+ input: Record<string, unknown>
+): T =>
+ typeof value === 'function' ? (value as (input: Record<string, unknown>) => T)(input) : value;
+
+const parseJsonIfRequested = (stdout: string, parseJson: boolean): unknown => {
+ if (!parseJson || stdout.trim().length === 0) return stdout;
+ try {
+ return JSON.parse(stdout) as unknown;
+ } catch {
+ return stdout;
+ }
+};
+
+const isBundledBinaryRef = (value: unknown): value is LocalBundledBinaryRef =>
+ typeof value === 'object' &&
+ value !== null &&
+ 'bundledBinary' in value &&
+ typeof (value as { bundledBinary?: unknown }).bundledBinary === 'string';
+
+const commandValueToInvocation = async (
+ value: LocalCommandValue,
+ context: LocalExecutionContext
+): Promise<LocalCommandInvocation> => {
+ if (typeof value === 'string') return { command: value };
+
+ if (isBundledBinaryRef(value)) {
+ const resolved = await resolveBundledBinary(context.toolkit, value, {
+ currentPlatform: context.platform,
+ });
+ const command = resolved?.exists ? resolved.path : value.fallbackCommand;
+ if (!command) {
+ throw new Error(
+ `Bundled binary ${value.bundledBinary} was not found for ${context.platform} and no fallback command was provided.`
+ );
+ }
+ if (resolved?.exists && resolved.source === 'bundled') {
+ await ensureBundledBinaryExecutable(resolved.path);
+ }
+ return { ...value, command };
+ }
+
+ return value;
+};
+
+const resolveCommandInvocation = async (
+ execution: LocalCommandExecution,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+): Promise<LocalCommandInvocation> => {
+ const commandValue = resolveValue(execution.command, input);
+ const baseInvocation = await commandValueToInvocation(commandValue, context);
+
+ const toolMeta = await getLocalToolMeta(context.finalSlug);
+ const toolkitMeta = await getLocalToolkitMeta(context.toolkit.slug);
+ const commandOverride = toolMeta?.installation?.command ?? toolkitMeta?.installation?.command;
+
+ return {
+ ...baseInvocation,
+ command: commandOverride ?? baseInvocation.command,
+ args: baseInvocation.args ?? (execution.args ? resolveValue(execution.args, input) : []),
+ env: {
+ ...compactEnv(execution.env ? resolveValue(execution.env, input) : undefined),
+ ...compactEnv(baseInvocation.env),
+ },
+ cwd: baseInvocation.cwd ?? (execution.cwd ? resolveValue(execution.cwd, input) : undefined),
+ stdin:
+ baseInvocation.stdin ?? (execution.stdin ? resolveValue(execution.stdin, input) : undefined),
+ timeoutMs: baseInvocation.timeoutMs ?? execution.timeoutMs,
+ };
+};
+
+export const runLocalCommand = async (
+ execution: LocalCommandExecution,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+): Promise<LocalExecutionResult> => {
+ const invocation = await resolveCommandInvocation(execution, input, context);
+ const child = spawn(invocation.command, [...(invocation.args ?? [])], {
+ cwd: invocation.cwd,
+ env: { ...process.env, ...compactEnv(invocation.env) },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', chunk => {
+ stdout += chunk;
+ });
+ child.stderr.on('data', chunk => {
+ stderr += chunk;
+ });
+
+ if (invocation.stdin !== undefined) {
+ child.stdin.end(invocation.stdin);
+ } else {
+ child.stdin.end();
+ }
+
+ let timeout: NodeJS.Timeout | undefined;
+ if (invocation.timeoutMs && invocation.timeoutMs > 0) {
+ timeout = setTimeout(() => child.kill('SIGTERM'), invocation.timeoutMs);
+ }
+
+ const exitPromise = once(child, 'exit') as Promise<[number | null, NodeJS.Signals | null]>;
+ const errorPromise = once(child, 'error').then(([error]) => {
+ throw error;
+ }) as Promise<[number | null, NodeJS.Signals | null]>;
+ const [exitCode, signal] = await Promise.race([exitPromise, errorPromise]);
+ if (timeout) clearTimeout(timeout);
+
+ if (exitCode !== 0) {
+ throw new Error(
+ [
+ `Local command failed for ${context.finalSlug}: ${invocation.command} ${(invocation.args ?? []).join(' ')}`,
+ `exitCode=${exitCode ?? 'null'} signal=${signal ?? 'null'}`,
+ stderr.trim() ? `stderr: ${stderr.trim()}` : undefined,
+ ]
+ .filter(Boolean)
+ .join('\n')
+ );
+ }
+
+ return {
+ command: invocation.command,
+ args: invocation.args ?? [],
+ stdout,
+ stderr,
+ exitCode,
+ parsed: parseJsonIfRequested(stdout, execution.parseJson ?? false),
+ };
+};
+
+export const runLocalMcpTool = async (
+ execution: LocalMcpExecution,
+ input: Record<string, unknown>
+): Promise<LocalExecutionResult> => {
+ const [{ Client }, { StdioClientTransport }] = await Promise.all([
+ import('@modelcontextprotocol/sdk/client/index.js'),
+ import('@modelcontextprotocol/sdk/client/stdio.js'),
+ ]);
+
+ const server =
+ typeof execution.server === 'function' ? execution.server(input) : execution.server;
+ const client = new Client({ name: 'composio-cli-local-tools', version: '0.0.1' });
+ const transport = new StdioClientTransport({
+ command: server.command,
+ args: [...(server.args ?? [])],
+ env: { ...compactEnv(process.env), ...compactEnv(server.env) },
+ cwd: server.cwd,
+ });
+
+ await client.connect(transport);
+ try {
+ const toolName = execution.toolName
+ ? typeof execution.toolName === 'function'
+ ? execution.toolName(input)
+ : execution.toolName
+ : undefined;
+
+ if (!toolName) {
+ const result = await client.listTools();
+ return { tools: result.tools };
+ }
+
+ const args = execution.arguments
+ ? typeof execution.arguments === 'function'
+ ? execution.arguments(input)
+ : execution.arguments
+ : input;
+ const result = await client.callTool({ name: toolName, arguments: args });
+ return { toolName, result: result as unknown as Record<string, unknown> };
+ } finally {
+ await client.close().catch(() => undefined);
+ }
+};
+
+const ffiTypeMap: Record<LocalFfiType, string> = {
+ char: 'char',
+ uchar: 'uchar',
+ i8: 'i8',
+ u8: 'u8',
+ i16: 'i16',
+ u16: 'u16',
+ i32: 'i32',
+ u32: 'u32',
+ i64: 'i64',
+ u64: 'u64',
+ f32: 'f32',
+ f64: 'f64',
+ bool: 'bool',
+ ptr: 'ptr',
+ cstring: 'cstring',
+ void: 'void',
+};
+
+const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
+
+const resolveFfiLibraryPath = async (
+ execution: LocalFfiExecution,
+ context: LocalExecutionContext
+): Promise<string> => {
+ if (typeof execution.library === 'string') return execution.library;
+ const resolved = await resolveBundledBinary(context.toolkit, execution.library, {
+ currentPlatform: context.platform,
+ });
+ if (resolved?.exists) return resolved.path;
+ if (execution.library.fallbackCommand) return execution.library.fallbackCommand;
+ throw new Error(
+ `Bundled FFI library ${execution.library.bundledBinary} was not found for ${context.platform}.`
+ );
+};
+
+const runLocalFfiTool = async (
+ execution: LocalFfiExecution,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+): Promise<LocalExecutionResult> => {
+ if (!isBun) {
+ throw new Error(
+ 'Local FFI execution requires the Bun runtime used by the packaged Composio CLI.'
+ );
+ }
+
+ const { dlopen, FFIType } = (await import('bun:ffi')) as typeof import('bun:ffi');
+ const libraryPath = await resolveFfiLibraryPath(execution, context);
+ const bindings = Object.fromEntries(
+ Object.entries(execution.symbols).map(([name, symbol]) => [
+ name,
+ {
+ args: symbol.args.map(type => FFIType[ffiTypeMap[type] as keyof typeof FFIType]),
+ returns: FFIType[ffiTypeMap[symbol.returns] as keyof typeof FFIType],
+ },
+ ])
+ );
+ const library = dlopen(libraryPath, bindings);
+ const handle: LocalFfiLibraryHandle = {
+ path: libraryPath,
+ symbols: library.symbols as Record<string, (...args: ReadonlyArray<unknown>) => unknown>,
+ };
+ return execution.execute(input, context, handle);
+};
+
+export const executeLocalTool = async (
+ execution: LocalToolExecution,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+): Promise<LocalExecutionResult> => {
+ try {
+ if (execution.kind === 'native') {
+ return await execution.execute(input, context);
+ }
+ if (execution.kind === 'command') {
+ return await runLocalCommand(execution, input, context);
+ }
+ if (execution.kind === 'mcp') {
+ return await runLocalMcpTool(execution, input);
+ }
+ return await runLocalFfiTool(execution, input, context);
+ } catch (error) {
+ throw new Error(`Failed to execute local tool ${context.finalSlug}: ${toErrorMessage(error)}`, {
+ cause: error,
+ });
+ }
+};
diff --git a/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.test.ts b/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.test.ts
new file mode 100644
index 000000000..508c152e4
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { resolveBundledBinary } from '../bundled-binaries';
+import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
+import { beeperImessageToolkit } from './beeper-imessage';
+
+describe('@composio/cli-local-tools Beeper iMessage toolkit', () => {
+ it('exposes first-class schemas for Beeper iMessage tools', () => {
+ expect(beeperImessageToolkit.tools.map(tool => tool.slug)).toEqual(
+ expect.arrayContaining(['LIST_THREADS', 'FIND_THREAD', 'SEND_MESSAGE', 'AUTHORIZE'])
+ );
+
+ const sendSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_SEND_MESSAGE');
+ expect(sendSchema?.schema.properties).toHaveProperty('threadId');
+ expect(sendSchema?.schema.properties).toHaveProperty('text');
+ expect(sendSchema?.schema.properties).toHaveProperty('verifySent');
+
+ const listSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_LIST_THREADS');
+ expect(listSchema?.schema.properties).toHaveProperty('compact');
+ expect(listSchema?.schema.properties).toHaveProperty('resolveContactNames');
+
+ const reactSchema = getLocalToolInputDefinition('LOCAL_BEEPER_IMESSAGE_REACT_TO_MESSAGE');
+ expect(reactSchema?.schema.properties).toHaveProperty('prepareTranscript');
+ });
+
+ it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
+ 'resolves generated bundled imessage-cli and executes the bootstrap-free version command',
+ async () => {
+ const resolved = await resolveBundledBinary(
+ beeperImessageToolkit,
+ { bundledBinary: 'beeper-imessage-cli' },
+ { currentPlatform: process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64' }
+ );
+ expect(resolved?.exists).toBe(true);
+
+ const result = await executeLocalToolBySlug('LOCAL_BEEPER_IMESSAGE_VERSION', {});
+ expect(result?.resultText).toContain('platform-imessage 0.21.0');
+ }
+ );
+});
diff --git a/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.ts b/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.ts
new file mode 100644
index 000000000..0d46dd2f8
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/beeper-imessage.ts
@@ -0,0 +1,1299 @@
+import { spawn } from 'node:child_process';
+import { z } from 'zod/v3';
+import { runLocalCommand } from '../runtime';
+import type {
+ LocalCommandExecution,
+ LocalExecutionContext,
+ LocalExecutionResult,
+ LocalToolkitDeclaration,
+ LocalToolDeclaration,
+} from '../types';
+
+const IMESSAGE_CLI_BINARY_ID = 'beeper-imessage-cli';
+const IMESSAGE_CLI_VERSION = '0.21.0';
+const COMMAND_TIMEOUT_MS = 120_000;
+const SEND_VERIFY_TIMEOUT_MS = 8_000;
+const SEND_VERIFY_INTERVAL_MS = 500;
+const THREAD_SCAN_DEFAULT_MAX_PAGES = 10;
+const THREAD_SCAN_MAX_PAGES = 50;
+const CONTACT_LOOKUP_TIMEOUT_MS = 5_000;
+const REACTION_PREPARE_TIMEOUT_MS = 5_000;
+const REACTION_TIMEOUT_MS = 20_000;
+
+const baseInput = z.object({
+ dataDir: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('Optional directory for imessage-cli state. Defaults to a temporary directory.'),
+ useSecondaryInstance: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'Use a secondary Messages.app instance. This is usually fine for read/send/list tools. UI-dependent tools such as reactions default to the primary Messages.app instance because they need the transcript view to be visible.'
+ ),
+ verbose: z.boolean().default(false).describe('Enable verbose imessage-cli logging.'),
+});
+
+const primaryInstanceInput = baseInput.extend({
+ useSecondaryInstance: z
+ .boolean()
+ .default(false)
+ .describe(
+ 'Use a secondary Messages.app instance. Defaults to false for reactions because the upstream UI automation needs the primary transcript view to be visible.'
+ ),
+});
+
+const cursorInput = z.object({
+ before: z
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ 'Fetch items older than this cursor. For LIST_THREADS, use result.pageInfo.nextBefore.'
+ ),
+ after: z.string().min(1).optional().describe('Fetch items newer than this cursor.'),
+});
+
+const cliOutput = z.object({
+ ok: z.boolean(),
+ commandName: z.string(),
+ callId: z.string().optional(),
+ durationMs: z.number().optional(),
+ result: z.unknown().optional(),
+ resultText: z.string().optional(),
+ stdout: z.string(),
+ stderr: z.string(),
+});
+
+const stringArray = (value: unknown): string[] =>
+ Array.isArray(value) ? value.map(item => String(item)) : [];
+
+const stringValue = (value: unknown): string => String(value ?? '');
+
+const optionalString = (value: unknown): string | undefined => {
+ const text = typeof value === 'string' ? value.trim() : '';
+ return text.length > 0 ? text : undefined;
+};
+
+const absolutePath = (value: unknown): string => stringValue(value);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const toRecordArray = (value: unknown): Record<string, unknown>[] => {
+ if (Array.isArray(value)) return value.filter(isRecord);
+ if (isRecord(value) && Array.isArray(value.items)) return value.items.filter(isRecord);
+ return [];
+};
+
+const normalizePhone = (value: string): string => value.replace(/[^0-9]/g, '');
+
+const normalizeIdentifier = (value: unknown): string => {
+ const text = String(value ?? '')
+ .trim()
+ .toLowerCase();
+ if (!text) return '';
+ if (text.includes('@')) return text;
+ const digits = normalizePhone(text);
+ return digits || text;
+};
+
+const unique = <T>(values: ReadonlyArray<T>): T[] => [...new Set(values)];
+
+const compactRecord = (record: Record<string, unknown>, keys: ReadonlyArray<string>) =>
+ Object.fromEntries(keys.filter(key => record[key] !== undefined).map(key => [key, record[key]]));
+
+const messageIdOf = (message: unknown): string | undefined =>
+ isRecord(message) ? optionalString(message.id) : undefined;
+
+const messageTextOf = (message: unknown): string =>
+ isRecord(message) ? stringValue(message.text ?? '') : '';
+
+const messageIsSender = (message: unknown): boolean =>
+ isRecord(message) && message.isSender === true;
+
+const messageMatchesSentText = (message: unknown, text: string): boolean =>
+ messageIsSender(message) && messageTextOf(message) === text;
+
+const extractPageItems = (result: unknown): Record<string, unknown>[] =>
+ isRecord(result) ? toRecordArray(result.items) : [];
+
+const extractThreadId = (value: unknown): string | undefined => {
+ if (!isRecord(value)) return undefined;
+ return optionalString(value.id ?? value.threadId ?? value.threadID ?? value.chatId);
+};
+
+const participantIdentifiers = (thread: Record<string, unknown>): string[] => {
+ const participants = toRecordArray(thread.participants);
+ return unique(
+ participants.flatMap(participant =>
+ [participant.email, participant.phoneNumber, participant.handle, participant.id]
+ .map(optionalString)
+ .filter((value): value is string => Boolean(value))
+ )
+ );
+};
+
+const latestMessage = (thread: Record<string, unknown>): Record<string, unknown> | undefined => {
+ const messages = toRecordArray(thread.messages);
+ return messages[0];
+};
+
+const buildGlobalArgs = (input: Record<string, unknown>): string[] => {
+ const args: string[] = [];
+ const dataDir = optionalString(input.dataDir);
+ if (dataDir) args.push('--data-dir', dataDir);
+ if (input.useSecondaryInstance === false) args.push('--no-use-secondary-instance');
+ // Local tools are one-shot calls. Avoid keeping DB event watchers open unless a
+ // future streaming tool explicitly opts in.
+ args.push('--no-events');
+ if (input.verbose === true) args.push('--verbose');
+ return args;
+};
+
+const withCursorArgs = (input: Record<string, unknown>, args: string[]): string[] => {
+ const before = optionalString(input.before);
+ const after = optionalString(input.after);
+ if (before && after) throw new Error('Use only one of before or after.');
+ if (before) args.push('--before', before);
+ if (after) args.push('--after', after);
+ return args;
+};
+
+const stripAnsi = (text: string): string => text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
+
+const parseImessageCliOutput = (
+ commandName: string,
+ stdout: string,
+ stderr: string
+): LocalExecutionResult => {
+ const cleanStdout = stripAnsi(stdout);
+ const lines = cleanStdout.split(/\r?\n/);
+ const okIndex = lines.findIndex(line => /^\[\d+\] ok /.test(line));
+ const okLine = okIndex >= 0 ? lines[okIndex] : undefined;
+ const match = okLine?.match(/^\[(\d+)\] ok \S+ \((\d+(?:\.\d+)?)ms\)$/);
+
+ const resultLines = okIndex >= 0 ? lines.slice(okIndex + 1) : lines;
+ const resultText = resultLines
+ .filter(line => line.trim() !== 'Exiting...')
+ .join('\n')
+ .trim();
+
+ let parsed: unknown;
+ if (resultText) {
+ try {
+ parsed = JSON.parse(resultText) as unknown;
+ } catch {
+ parsed = undefined;
+ }
+ }
+
+ return {
+ ok: true,
+ commandName,
+ ...(match?.[1] ? { callId: match[1] } : {}),
+ ...(match?.[2] ? { durationMs: Number(match[2]) } : {}),
+ ...(parsed !== undefined ? { result: parsed } : {}),
+ ...(resultText ? { resultText } : {}),
+ stdout,
+ stderr,
+ };
+};
+
+const runImessageCli = async (
+ commandName: string,
+ commandArgs: ReadonlyArray<string>,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext,
+ options: { readonly timeoutMs?: number } = {}
+): Promise<LocalExecutionResult> => {
+ const execution: LocalCommandExecution = {
+ kind: 'command',
+ command: {
+ bundledBinary: IMESSAGE_CLI_BINARY_ID,
+ fallbackCommand: 'imessage-cli',
+ },
+ args: [...buildGlobalArgs(input), commandName, ...commandArgs],
+ timeoutMs: options.timeoutMs ?? COMMAND_TIMEOUT_MS,
+ };
+ const result = await runLocalCommand(execution, input, context);
+ return parseImessageCliOutput(
+ commandName,
+ String(result.stdout ?? ''),
+ String(result.stderr ?? '')
+ );
+};
+
+const runProcess = async (
+ command: string,
+ args: ReadonlyArray<string>,
+ timeoutMs: number
+): Promise<{ readonly stdout: string; readonly stderr: string }> => {
+ const child = spawn(command, [...args], {
+ env: process.env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', chunk => {
+ stdout += chunk;
+ });
+ child.stderr.on('data', chunk => {
+ stderr += chunk;
+ });
+
+ const exitPromise = new Promise<{
+ readonly exitCode: number | null;
+ readonly signal: string | null;
+ }>((resolve, reject) => {
+ child.once('error', reject);
+ child.once('exit', (exitCode, signal) => resolve({ exitCode, signal }));
+ });
+ const timeout = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
+ const { exitCode, signal } = await exitPromise.finally(() => clearTimeout(timeout));
+ if (exitCode !== 0) {
+ throw new Error(
+ `${command} failed with exitCode=${exitCode ?? 'null'} signal=${signal ?? 'null'}${
+ stderr.trim() ? `: ${stderr.trim()}` : ''
+ }`
+ );
+ }
+ return { stdout, stderr };
+};
+
+const contactLookupScript = `
+function normalizePhone(value) {
+ return String(value || '').replace(/[^0-9]/g, '');
+}
+function normalizeIdentifier(value) {
+ const text = String(value || '').trim().toLowerCase();
+ if (!text) return '';
+ if (text.indexOf('@') >= 0) return text;
+ return normalizePhone(text) || text;
+}
+function valuesOf(collection) {
+ try { return collection().map(item => String(item.value())); } catch (_) { return []; }
+}
+function personName(person) {
+ try { return String(person.name() || '').trim(); } catch (_) { return ''; }
+}
+function run(argv) {
+ const mode = argv[0] || 'query';
+ const payload = JSON.parse(argv[1] || '{}');
+ const query = String(payload.query || '').toLowerCase();
+ const requestedIdentifiers = (payload.identifiers || []).map(normalizeIdentifier).filter(Boolean);
+ const requestedSet = new Set(requestedIdentifiers);
+ const Contacts = Application('Contacts');
+ const people = Contacts.people();
+ const matches = [];
+ const labels = {};
+ for (const person of people) {
+ const name = personName(person);
+ const emails = valuesOf(person.emails);
+ const phones = valuesOf(person.phones);
+ const identifiers = emails.concat(phones);
+ const normalized = identifiers.map(normalizeIdentifier).filter(Boolean);
+ const haystack = [name].concat(identifiers).join(' ').toLowerCase();
+ if (mode === 'query' && query && haystack.indexOf(query) >= 0) {
+ matches.push({ name, emails, phones, identifiers });
+ }
+ if (mode === 'labels') {
+ for (let index = 0; index < normalized.length; index += 1) {
+ const value = normalized[index];
+ if (requestedSet.has(value)) labels[value] = name || identifiers[index] || value;
+ }
+ }
+ }
+ return JSON.stringify({ matches: matches.slice(0, 25), labels });
+}
+`;
+
+interface ContactLookupResult {
+ readonly matches: ReadonlyArray<{
+ readonly name?: string;
+ readonly emails?: ReadonlyArray<string>;
+ readonly phones?: ReadonlyArray<string>;
+ readonly identifiers?: ReadonlyArray<string>;
+ }>;
+ readonly labels: Record<string, string>;
+ readonly error?: string;
+}
+
+const emptyContactLookup = (error?: string): ContactLookupResult => ({
+ matches: [],
+ labels: {},
+ ...(error ? { error } : {}),
+});
+
+const lookupContacts = async (
+ mode: 'query' | 'labels',
+ payload: Record<string, unknown>
+): Promise<ContactLookupResult> => {
+ if (process.platform !== 'darwin') return emptyContactLookup('Contacts lookup requires macOS.');
+ try {
+ const result = await runProcess(
+ 'osascript',
+ ['-l', 'JavaScript', '-e', contactLookupScript, mode, JSON.stringify(payload)],
+ CONTACT_LOOKUP_TIMEOUT_MS
+ );
+ const parsed = JSON.parse(result.stdout.trim()) as unknown;
+ if (!isRecord(parsed))
+ return emptyContactLookup('Contacts lookup returned a non-object result.');
+ return {
+ matches: Array.isArray(parsed.matches) ? parsed.matches.filter(isRecord) : [],
+ labels: isRecord(parsed.labels)
+ ? Object.fromEntries(
+ Object.entries(parsed.labels).map(([key, value]) => [key, String(value)])
+ )
+ : {},
+ };
+ } catch (error) {
+ return emptyContactLookup(error instanceof Error ? error.message : String(error));
+ }
+};
+
+const contactIdentifiersFromMatches = (lookup: ContactLookupResult): string[] =>
+ unique(
+ lookup.matches.flatMap(match =>
+ [...(match.identifiers ?? []), ...(match.emails ?? []), ...(match.phones ?? [])]
+ .map(normalizeIdentifier)
+ .filter(Boolean)
+ )
+ );
+
+const labelsForThreads = async (
+ threads: ReadonlyArray<Record<string, unknown>>,
+ enabled: boolean
+): Promise<Record<string, string>> => {
+ if (!enabled || threads.length === 0) return {};
+ const identifiers = unique(threads.flatMap(thread => participantIdentifiers(thread))).map(
+ normalizeIdentifier
+ );
+ if (identifiers.length === 0) return {};
+ return (await lookupContacts('labels', { identifiers })).labels;
+};
+
+const compactParticipant = (
+ participant: Record<string, unknown>,
+ labels: Record<string, string>
+): Record<string, unknown> => {
+ const identifier = optionalString(
+ participant.email ?? participant.phoneNumber ?? participant.handle
+ );
+ const normalized = normalizeIdentifier(identifier);
+ return {
+ ...compactRecord(participant, ['isSelf', 'email', 'phoneNumber', 'handle']),
+ ...(identifier && labels[normalized] ? { label: labels[normalized] } : {}),
+ };
+};
+
+const compactMessage = (message: unknown): Record<string, unknown> | undefined => {
+ if (!isRecord(message)) return undefined;
+ return compactRecord(message, [
+ 'id',
+ 'text',
+ 'isSender',
+ 'timestamp',
+ 'isDelivered',
+ 'isErrored',
+ 'seen',
+ ]);
+};
+
+const compactThread = (thread: Record<string, unknown>, labels: Record<string, string>) => {
+ const participants = toRecordArray(thread.participants).map(participant =>
+ compactParticipant(participant, labels)
+ );
+ const lastMessage = compactMessage(latestMessage(thread));
+ const participantLabels = unique(
+ participants
+ .map(participant =>
+ optionalString(participant.label ?? participant.email ?? participant.phoneNumber)
+ )
+ .filter((value): value is string => Boolean(value))
+ );
+ return {
+ ...compactRecord(thread, [
+ 'id',
+ 'title',
+ 'type',
+ 'timestamp',
+ 'folderName',
+ 'unreadCount',
+ 'isUnread',
+ 'isReadOnly',
+ 'isPinned',
+ 'isMarkedUnread',
+ 'isLowPriority',
+ 'lastReadMessageSortKey',
+ ]),
+ participantLabels,
+ participants,
+ ...(lastMessage ? { lastMessage } : {}),
+ };
+};
+
+const pageInfoFor = (result: unknown) => {
+ const record = isRecord(result) ? result : {};
+ const oldestCursor = optionalString(record.oldestCursor);
+ return {
+ hasMore: record.hasMore === true,
+ oldestCursor,
+ nextBefore: oldestCursor,
+ nextSteps: oldestCursor
+ ? `Fetch older threads with { "before": "${oldestCursor}" }.`
+ : 'No older cursor was returned.',
+ };
+};
+
+const compactThreadsResult = async (
+ rawResult: LocalExecutionResult,
+ options: {
+ readonly compact: boolean;
+ readonly includeRaw: boolean;
+ readonly resolveContactNames: boolean;
+ }
+): Promise<LocalExecutionResult> => {
+ if (!options.compact || !isRecord(rawResult.result)) return rawResult;
+ const threads = extractPageItems(rawResult.result);
+ const labels = await labelsForThreads(threads, options.resolveContactNames);
+ const compactResult = {
+ items: threads.map(thread => compactThread(thread, labels)),
+ pageInfo: pageInfoFor(rawResult.result),
+ contactResolution: {
+ enabled: options.resolveContactNames,
+ resolvedLabels: Object.keys(labels).length,
+ },
+ ...(options.includeRaw ? { raw: rawResult.result } : {}),
+ };
+ return {
+ ...rawResult,
+ result: compactResult,
+ resultText: undefined,
+ stdout: options.includeRaw ? rawResult.stdout : '',
+ };
+};
+
+const delay = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
+
+const fetchMessages = async (
+ threadId: string,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+): Promise<LocalExecutionResult> => runImessageCli('messages', [threadId], input, context);
+
+const pollForSentMessage = async (params: {
+ readonly threadId: string;
+ readonly text: string;
+ readonly input: Record<string, unknown>;
+ readonly context: LocalExecutionContext;
+ readonly timeoutMs: number;
+ readonly excludeMessageIds?: ReadonlySet<string>;
+}): Promise<{
+ readonly message?: Record<string, unknown>;
+ readonly messagesResult?: LocalExecutionResult;
+ readonly attempts: number;
+}> => {
+ const deadline = Date.now() + params.timeoutMs;
+ let attempts = 0;
+ let lastResult: LocalExecutionResult | undefined;
+
+ do {
+ attempts += 1;
+ lastResult = await fetchMessages(params.threadId, params.input, params.context);
+ const messages = extractPageItems(lastResult.result);
+ const message = messages.find(candidate => {
+ const candidateId = messageIdOf(candidate);
+ return (
+ messageMatchesSentText(candidate, params.text) &&
+ (!candidateId || !params.excludeMessageIds?.has(candidateId))
+ );
+ });
+ if (message) return { message, messagesResult: lastResult, attempts };
+ if (Date.now() < deadline) await delay(SEND_VERIFY_INTERVAL_MS);
+ } while (Date.now() < deadline);
+
+ return { messagesResult: lastResult, attempts };
+};
+
+const enhanceSendResult = (params: {
+ readonly commandResult: LocalExecutionResult;
+ readonly threadId?: string;
+ readonly sentText: string;
+ readonly sentMessage?: Record<string, unknown>;
+ readonly messagesResult?: LocalExecutionResult;
+ readonly attempts: number;
+ readonly verify: boolean;
+}): LocalExecutionResult => {
+ const sentMessageId = messageIdOf(params.sentMessage);
+ const sendVerification = {
+ commandSucceeded: params.commandResult.ok === true,
+ verified: Boolean(params.sentMessage),
+ status: params.sentMessage
+ ? 'observed_sent_message'
+ : params.verify
+ ? 'command_succeeded_but_sent_message_not_observed_yet'
+ : 'not_requested',
+ attempts: params.attempts,
+ threadId: params.threadId,
+ sentMessageId,
+ };
+
+ let enhancedResult = params.commandResult.result;
+ if (isRecord(enhancedResult) && params.sentMessage) {
+ const messagesPage = isRecord(params.messagesResult?.result)
+ ? params.messagesResult?.result
+ : { items: [params.sentMessage], hasMore: false };
+ enhancedResult = {
+ ...enhancedResult,
+ messages: messagesPage,
+ sentMessage: params.sentMessage,
+ sentMessageId,
+ sendVerification,
+ };
+ } else if (isRecord(enhancedResult)) {
+ enhancedResult = {
+ ...enhancedResult,
+ sentMessage: params.sentMessage ?? null,
+ sentMessageId,
+ sendVerification,
+ };
+ } else {
+ enhancedResult = {
+ originalResult: enhancedResult,
+ sentMessage: params.sentMessage ?? null,
+ sentMessageId,
+ sendVerification,
+ };
+ }
+
+ return {
+ ...params.commandResult,
+ result: enhancedResult,
+ sentMessage: params.sentMessage ?? null,
+ sentMessageId,
+ sendVerification,
+ resultText: JSON.stringify(enhancedResult, null, 2),
+ };
+};
+
+const threadMatches = (params: {
+ readonly thread: Record<string, unknown>;
+ readonly query?: string;
+ readonly recipientIdentifiers: ReadonlySet<string>;
+ readonly contactIdentifiers: ReadonlySet<string>;
+ readonly labels: Record<string, string>;
+}): boolean => {
+ const identifiers = participantIdentifiers(params.thread);
+ const normalizedIdentifiers = identifiers.map(normalizeIdentifier).filter(Boolean);
+ const labels = normalizedIdentifiers.map(identifier => params.labels[identifier]).filter(Boolean);
+ const query = params.query?.trim().toLowerCase();
+
+ if (params.recipientIdentifiers.size > 0) {
+ const normalizedSet = new Set(normalizedIdentifiers);
+ const hasAllRecipients = [...params.recipientIdentifiers].every(identifier =>
+ normalizedSet.has(identifier)
+ );
+ if (hasAllRecipients) return true;
+ }
+
+ if (params.contactIdentifiers.size > 0) {
+ const normalizedSet = new Set(normalizedIdentifiers);
+ if ([...params.contactIdentifiers].some(identifier => normalizedSet.has(identifier)))
+ return true;
+ }
+
+ if (!query) return false;
+ const searchable = [
+ optionalString(params.thread.title),
+ optionalString(params.thread.id),
+ ...identifiers,
+ ...labels,
+ ]
+ .filter((value): value is string => Boolean(value))
+ .join(' ')
+ .toLowerCase();
+ return searchable.includes(query);
+};
+
+const scanThreads = async (params: {
+ readonly input: Record<string, unknown>;
+ readonly context: LocalExecutionContext;
+ readonly query?: string;
+ readonly recipients?: ReadonlyArray<string>;
+ readonly maxPages?: number;
+ readonly resolveContactNames?: boolean;
+}): Promise<{
+ readonly matches: ReadonlyArray<Record<string, unknown>>;
+ readonly pagesScanned: number;
+ readonly nextBefore?: string;
+ readonly hasMore: boolean;
+ readonly contactLookup?: ContactLookupResult;
+ readonly labels: Record<string, string>;
+}> => {
+ const maxPages = Math.min(
+ Math.max(1, Number(params.maxPages ?? THREAD_SCAN_DEFAULT_MAX_PAGES)),
+ THREAD_SCAN_MAX_PAGES
+ );
+ const recipients = params.recipients ?? [];
+ const recipientIdentifiers = new Set(recipients.map(normalizeIdentifier).filter(Boolean));
+ const contactLookup =
+ params.resolveContactNames && params.query
+ ? await lookupContacts('query', { query: params.query })
+ : undefined;
+ const contactIdentifiers = new Set(
+ contactLookup ? contactIdentifiersFromMatches(contactLookup) : []
+ );
+
+ let before: string | undefined = optionalString(params.input.before);
+ let hasMore = true;
+ let pagesScanned = 0;
+ let nextBefore: string | undefined;
+ const matches: Record<string, unknown>[] = [];
+ const labelTargets: Record<string, unknown>[] = [];
+
+ while (pagesScanned < maxPages && hasMore) {
+ pagesScanned += 1;
+ const pageInput = { ...params.input, ...(before ? { before } : {}) };
+ const page = await runImessageCli(
+ 'threads',
+ withCursorArgs(pageInput, []),
+ pageInput,
+ params.context
+ );
+ const result = isRecord(page.result) ? page.result : {};
+ const threads = extractPageItems(result);
+ labelTargets.push(...threads);
+ const labels = await labelsForThreads(threads, params.resolveContactNames ?? true);
+ matches.push(
+ ...threads.filter(thread =>
+ threadMatches({
+ thread,
+ query: params.query,
+ recipientIdentifiers,
+ contactIdentifiers,
+ labels,
+ })
+ )
+ );
+ hasMore = result.hasMore === true;
+ nextBefore = optionalString(result.oldestCursor);
+ before = nextBefore;
+ if (!before) break;
+ }
+
+ const labels = await labelsForThreads(labelTargets, params.resolveContactNames ?? true);
+ return { matches, pagesScanned, nextBefore, hasMore, contactLookup, labels };
+};
+
+const commandTool = <TInput extends z.ZodTypeAny>(definition: {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputParams: TInput;
+ readonly command: string;
+ readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
+}): LocalToolDeclaration<TInput> => ({
+ slug: definition.slug,
+ name: definition.name,
+ description: definition.description,
+ platforms: ['darwin-arm64', 'darwin-x64'],
+ inputParams: definition.inputParams,
+ outputParams: cliOutput,
+ execution: {
+ kind: 'native',
+ execute: (input, context) =>
+ runImessageCli(definition.command, definition.args(input as z.infer<TInput>), input, context),
+ },
+});
+
+const nativeTool = <TInput extends z.ZodTypeAny>(definition: {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputParams: TInput;
+ readonly execute: (
+ input: z.infer<TInput>,
+ context: LocalExecutionContext
+ ) => Promise<LocalExecutionResult>;
+}): LocalToolDeclaration<TInput> => ({
+ slug: definition.slug,
+ name: definition.name,
+ description: definition.description,
+ platforms: ['darwin-arm64', 'darwin-x64'],
+ inputParams: definition.inputParams,
+ outputParams: cliOutput,
+ execution: {
+ kind: 'native',
+ execute: (input, context) => definition.execute(input as z.infer<TInput>, context),
+ },
+});
+
+const threadId = z
+ .string()
+ .min(1)
+ .describe('platform-imessage chat/thread ID, e.g. any;-;[email protected].');
+const messageId = z.string().min(1).describe('platform-imessage message ID.');
+const text = z.string().min(1).describe('Message text.');
+const filePath = z.string().min(1).describe('Local file path to attach.');
+
+const listThreadsInput = baseInput.merge(cursorInput).extend({
+ compact: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'Return a compact thread shape with id/title/type/participant labels/lastMessage/pageInfo. Set false to return the raw upstream CLI response.'
+ ),
+ includeRaw: z
+ .boolean()
+ .default(false)
+ .describe('When compact=true, include the raw upstream thread page under result.raw.'),
+ resolveContactNames: z
+ .boolean()
+ .default(true)
+ .describe('Best-effort macOS Contacts lookup for participant labels in compact output.'),
+});
+
+const findThreadInput = baseInput.extend({
+ query: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('Contact name, phone/email, thread title, or participant identifier to search for.'),
+ recipients: z
+ .array(z.string().min(1))
+ .optional()
+ .describe('Phone numbers or emails that must be present in the thread participants.'),
+ maxPages: z
+ .number()
+ .int()
+ .positive()
+ .max(THREAD_SCAN_MAX_PAGES)
+ .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
+ .describe('Maximum 25-thread pages to scan.'),
+ compact: z.boolean().default(true).describe('Return compact thread matches.'),
+ resolveContactNames: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'Best-effort macOS Contacts lookup so names like “Mustafa” can resolve to phone/email participants.'
+ ),
+});
+
+const sendVerificationInput = {
+ verifySent: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'After the send command succeeds, poll the local Messages DB for the newly sent message.'
+ ),
+ verificationTimeoutMs: z
+ .number()
+ .int()
+ .min(0)
+ .max(30_000)
+ .default(SEND_VERIFY_TIMEOUT_MS)
+ .describe(
+ 'How long to poll for the sent message before returning command_succeeded_but_not_observed.'
+ ),
+};
+
+const reactionInput = primaryInstanceInput.extend({
+ threadId,
+ messageId,
+ reaction: z
+ .string()
+ .min(1)
+ .describe(
+ 'Reaction key or emoji. Standard keys: heart, like, dislike, laugh, emphasize, question.'
+ ),
+ prepareTranscript: z
+ .boolean()
+ .default(true)
+ .describe('Run select-thread before reacting so the transcript is visible for UI automation.'),
+ prepareTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(30_000)
+ .default(REACTION_PREPARE_TIMEOUT_MS)
+ .describe('Timeout for select-thread transcript preparation.'),
+ reactionTimeoutMs: z
+ .number()
+ .int()
+ .positive()
+ .max(60_000)
+ .default(REACTION_TIMEOUT_MS)
+ .describe('Timeout for the reaction command itself.'),
+});
+
+const sendMessageInput = baseInput.extend({ threadId, text, ...sendVerificationInput });
+
+const createThreadAndSendInput = baseInput.extend({
+ recipients: z.array(z.string().min(1)).min(1).describe('Recipient phone numbers or emails.'),
+ message: text,
+ ...sendVerificationInput,
+});
+
+export const beeperImessageToolkit: LocalToolkitDeclaration = {
+ slug: 'BEEPER_IMESSAGE',
+ name: 'Beeper iMessage (local)',
+ description:
+ 'Local macOS iMessage tools backed by Beeper platform-imessage imessage-cli. Reads ~/Library/Messages and automates Messages.app for send/reaction/chat mutations.',
+ platforms: ['darwin-arm64', 'darwin-x64'],
+ source: {
+ type: 'cli',
+ repository: 'https://github.com/ComposioHQ/platform-imessage',
+ command: 'imessage-cli',
+ },
+ bundledBinaries: [
+ {
+ id: IMESSAGE_CLI_BINARY_ID,
+ description: `Beeper platform-imessage imessage-cli ${IMESSAGE_CLI_VERSION}.`,
+ targets: [
+ {
+ platforms: ['darwin-arm64'],
+ path: 'beeper-imessage/darwin-arm64/imessage-cli',
+ },
+ {
+ platforms: ['darwin-x64'],
+ path: 'beeper-imessage/darwin-x64/imessage-cli',
+ },
+ ],
+ },
+ ],
+ setup: {
+ install:
+ 'The CLI ships a bundled imessage-cli binary built from the ts/packages/cli-local-tools/vendor/platform-imessage submodule. Alternatively install/build imessage-cli and set a command override in ~/composio/local_tools.json.',
+ commandOverrides: [
+ 'composio local-tools configure BEEPER_IMESSAGE --command /path/to/imessage-cli',
+ ],
+ notes: [
+ 'Requires macOS with Messages.app configured for iMessage.',
+ 'Read-only tools require Messages Data access. Mutating tools require Messages Data and Accessibility; some setup flows may also request Contacts or Automation.',
+ 'Run LOCAL_BEEPER_IMESSAGE_AUTHORIZE (or imessage-cli authorize) to inspect/request permissions. A future local-tool auth abstraction should route this through composio link BEEPER_IMESSAGE.',
+ 'Most read/send tools work with the secondary Messages instance. Reaction tools default to the primary instance and prepare the transcript because upstream UI automation requires a visible reply transcript.',
+ ],
+ },
+ tools: [
+ commandTool({
+ slug: 'VERSION',
+ name: 'Get imessage-cli version',
+ description:
+ 'Print the bundled Beeper platform-imessage CLI version without touching Messages.app.',
+ inputParams: baseInput,
+ command: 'version',
+ args: () => [],
+ }),
+ commandTool({
+ slug: 'AUTHORIZE',
+ name: 'Inspect or request iMessage local permissions',
+ description:
+ 'Run imessage-cli authorize for Accessibility, Contacts, Messages Data, and Automation permissions. This may open macOS prompts or System Settings. This is the local equivalent of linking/authorizing the iMessage toolkit.',
+ inputParams: baseInput.extend({
+ target: z
+ .enum(['all', 'accessibility', 'contacts', 'messages-data', 'automation'])
+ .default('all')
+ .describe('Permission target to inspect/request.'),
+ }),
+ command: 'authorize',
+ args: input => [input.target],
+ }),
+ commandTool({
+ slug: 'CURRENT_USER',
+ name: 'Get current iMessage user',
+ description:
+ 'Return the iMessage identity known to the local platform-imessage backend. Requires Messages Data access.',
+ inputParams: baseInput,
+ command: 'current-user',
+ args: () => [],
+ }),
+ nativeTool({
+ slug: 'LIST_THREADS',
+ name: 'List iMessage threads',
+ description:
+ 'List normal-inbox iMessage chats from the local Messages database. Defaults to compact output with pageInfo.nextBefore for pagination; set compact=false for raw upstream output.',
+ inputParams: listThreadsInput,
+ execute: async (input, context) => {
+ const raw = await runImessageCli('threads', withCursorArgs(input, []), input, context);
+ return compactThreadsResult(raw, {
+ compact: input.compact,
+ includeRaw: input.includeRaw,
+ resolveContactNames: input.resolveContactNames,
+ });
+ },
+ }),
+ nativeTool({
+ slug: 'FIND_THREAD',
+ name: 'Find iMessage thread',
+ description:
+ 'Find threads by contact name, phone/email, thread title, or participants without doing a manual LIST_THREADS pagination/filter dance.',
+ inputParams: findThreadInput,
+ execute: async (input, context) => {
+ if (!input.query && (!input.recipients || input.recipients.length === 0)) {
+ throw new Error('Provide query or recipients to find an iMessage thread.');
+ }
+ const scan = await scanThreads({
+ input,
+ context,
+ query: input.query,
+ recipients: input.recipients,
+ maxPages: input.maxPages,
+ resolveContactNames: input.resolveContactNames,
+ });
+ const result = {
+ items: input.compact
+ ? scan.matches.map(thread => compactThread(thread, scan.labels))
+ : scan.matches,
+ pageInfo: {
+ pagesScanned: scan.pagesScanned,
+ hasMore: scan.hasMore,
+ nextBefore: scan.nextBefore,
+ },
+ contactResolution: {
+ enabled: input.resolveContactNames,
+ matchedContacts: scan.contactLookup?.matches.length ?? 0,
+ error: scan.contactLookup?.error,
+ },
+ };
+ return {
+ ok: true,
+ commandName: 'find-thread',
+ result,
+ resultText: JSON.stringify(result, null, 2),
+ stdout: '',
+ stderr: '',
+ };
+ },
+ }),
+ commandTool({
+ slug: 'GET_THREAD',
+ name: 'Get iMessage thread',
+ description: 'Fetch a single iMessage chat/thread by platform-imessage thread ID.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'thread',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'LIST_MESSAGES',
+ name: 'List iMessage messages',
+ description:
+ 'List messages in a chat from the local Messages database, optionally using cursors.',
+ inputParams: baseInput.merge(cursorInput).extend({ threadId }),
+ command: 'messages',
+ args: input => withCursorArgs(input, [input.threadId]),
+ }),
+ commandTool({
+ slug: 'GET_MESSAGE',
+ name: 'Get iMessage message',
+ description: 'Fetch a single message by chat/thread ID and message ID.',
+ inputParams: baseInput.extend({ threadId, messageId }),
+ command: 'message',
+ args: input => [input.threadId, input.messageId],
+ }),
+ nativeTool({
+ slug: 'SEARCH_MESSAGES',
+ name: 'Search local iMessage messages',
+ description:
+ 'Search local iMessage messages by text and, by default, also search thread participants/contact names so queries like “Nikos” can find matching chats.',
+ inputParams: baseInput.extend({
+ query: z
+ .string()
+ .min(1)
+ .describe('Text, participant name, phone/email, or thread title to search for.'),
+ includeThreadMatches: z
+ .boolean()
+ .default(true)
+ .describe(
+ 'Also scan threads/participants/contact names in addition to upstream message text search.'
+ ),
+ maxThreadPages: z
+ .number()
+ .int()
+ .positive()
+ .max(THREAD_SCAN_MAX_PAGES)
+ .default(THREAD_SCAN_DEFAULT_MAX_PAGES)
+ .describe('Maximum 25-thread pages to scan when includeThreadMatches=true.'),
+ compactThreads: z
+ .boolean()
+ .default(true)
+ .describe('Return compact matching thread records.'),
+ resolveContactNames: z
+ .boolean()
+ .default(true)
+ .describe('Best-effort macOS Contacts lookup for participant/name matching.'),
+ }),
+ execute: async (input, context) => {
+ const searchResult = await runImessageCli('search', [input.query], input, context);
+ const threadScan = input.includeThreadMatches
+ ? await scanThreads({
+ input,
+ context,
+ query: input.query,
+ maxPages: input.maxThreadPages,
+ resolveContactNames: input.resolveContactNames,
+ })
+ : undefined;
+ const result = {
+ messageSearch: searchResult.result,
+ matchingThreads: threadScan
+ ? input.compactThreads
+ ? threadScan.matches.map(thread => compactThread(thread, threadScan.labels))
+ : threadScan.matches
+ : [],
+ threadSearch: threadScan
+ ? {
+ pagesScanned: threadScan.pagesScanned,
+ hasMore: threadScan.hasMore,
+ nextBefore: threadScan.nextBefore,
+ contactResolution: {
+ enabled: input.resolveContactNames,
+ matchedContacts: threadScan.contactLookup?.matches.length ?? 0,
+ error: threadScan.contactLookup?.error,
+ },
+ }
+ : { enabled: false },
+ };
+ return {
+ ...searchResult,
+ result,
+ resultText: JSON.stringify(result, null, 2),
+ };
+ },
+ }),
+ nativeTool({
+ slug: 'CREATE_THREAD_AND_SEND',
+ name: 'Create iMessage thread and send message',
+ description:
+ 'Create or resolve a chat for one or more recipients and send the initial message. After the send command succeeds, this verifies the newly sent message and returns sentMessage/sentMessageId to avoid stale existing-thread ambiguity.',
+ inputParams: createThreadAndSendInput,
+ execute: async (input, context) => {
+ const createResult = await runImessageCli(
+ 'create-thread',
+ [...stringArray(input.recipients), '--message', input.message],
+ input,
+ context
+ );
+ const threadId = extractThreadId(createResult.result);
+ const verification =
+ input.verifySent && threadId
+ ? await pollForSentMessage({
+ threadId,
+ text: input.message,
+ input,
+ context,
+ timeoutMs: input.verificationTimeoutMs,
+ })
+ : { attempts: 0 };
+ return enhanceSendResult({
+ commandResult: createResult,
+ threadId,
+ sentText: input.message,
+ sentMessage: verification.message,
+ messagesResult: verification.messagesResult,
+ attempts: verification.attempts,
+ verify: input.verifySent,
+ });
+ },
+ }),
+ nativeTool({
+ slug: 'SEND_MESSAGE',
+ name: 'Send iMessage text',
+ description:
+ 'Send a text message to an existing chat/thread. Returns sendVerification plus sentMessage/sentMessageId when the local DB observes the new message, so callers should not retry solely because a thread preview is stale.',
+ inputParams: sendMessageInput,
+ execute: async (input, context) => {
+ const beforeMessages = input.verifySent
+ ? await fetchMessages(input.threadId, input, context)
+ : undefined;
+ const excludeMessageIds = new Set(
+ extractPageItems(beforeMessages?.result)
+ .map(messageIdOf)
+ .filter((value): value is string => Boolean(value))
+ );
+ const sendResult = await runImessageCli(
+ 'send',
+ [input.threadId, input.text],
+ input,
+ context
+ );
+ const verification = input.verifySent
+ ? await pollForSentMessage({
+ threadId: input.threadId,
+ text: input.text,
+ input,
+ context,
+ timeoutMs: input.verificationTimeoutMs,
+ excludeMessageIds,
+ })
+ : { attempts: 0 };
+ return enhanceSendResult({
+ commandResult: sendResult,
+ threadId: input.threadId,
+ sentText: input.text,
+ sentMessage: verification.message,
+ messagesResult: verification.messagesResult,
+ attempts: verification.attempts,
+ verify: input.verifySent,
+ });
+ },
+ }),
+ commandTool({
+ slug: 'REPLY_TO_MESSAGE',
+ name: 'Reply to iMessage message',
+ description: 'Reply to a specific iMessage with text. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId, messageId, text }),
+ command: 'reply',
+ args: input => [input.threadId, input.messageId, input.text],
+ }),
+ commandTool({
+ slug: 'SEND_FILE',
+ name: 'Send iMessage file attachment',
+ description:
+ 'Send a local file attachment to an existing chat/thread. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId, filePath }),
+ command: 'send-file',
+ args: input => [input.threadId, absolutePath(input.filePath)],
+ }),
+ commandTool({
+ slug: 'REPLY_WITH_FILE',
+ name: 'Reply to iMessage with file attachment',
+ description:
+ 'Reply to a specific message with a local file attachment. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId, messageId, filePath }),
+ command: 'reply-file',
+ args: input => [input.threadId, input.messageId, absolutePath(input.filePath)],
+ }),
+ commandTool({
+ slug: 'EDIT_MESSAGE',
+ name: 'Edit sent iMessage',
+ description:
+ 'Edit a previously sent iMessage. Supported by upstream on macOS Ventura or later.',
+ inputParams: baseInput.extend({ threadId, messageId, text }),
+ command: 'edit',
+ args: input => [input.threadId, input.messageId, input.text],
+ }),
+ commandTool({
+ slug: 'UNDO_SEND',
+ name: 'Undo sent iMessage',
+ description:
+ 'Undo send for a previously sent iMessage. Upstream supports this on macOS Ventura or later within the Messages time limit.',
+ inputParams: baseInput.extend({ threadId, messageId }),
+ command: 'undo-send',
+ args: input => [input.threadId, input.messageId],
+ }),
+ nativeTool({
+ slug: 'REACT_TO_MESSAGE',
+ name: 'React to iMessage',
+ description:
+ 'Add a standard reaction to a message using a supported key or emoji. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
+ inputParams: reactionInput,
+ execute: async (input, context) => {
+ const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
+ if (input.prepareTranscript) {
+ await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
+ timeoutMs: input.prepareTimeoutMs,
+ });
+ }
+ return runImessageCli(
+ 'react',
+ [input.threadId, input.messageId, input.reaction],
+ effectiveInput,
+ context,
+ { timeoutMs: input.reactionTimeoutMs }
+ );
+ },
+ }),
+ nativeTool({
+ slug: 'UNREACT_FROM_MESSAGE',
+ name: 'Remove iMessage reaction',
+ description:
+ 'Remove a standard reaction from a message. Defaults to the primary Messages.app instance and runs select-thread first because upstream reaction automation needs a visible transcript.',
+ inputParams: reactionInput,
+ execute: async (input, context) => {
+ const effectiveInput = { ...input, useSecondaryInstance: input.useSecondaryInstance };
+ if (input.prepareTranscript) {
+ await runImessageCli('select-thread', [input.threadId], effectiveInput, context, {
+ timeoutMs: input.prepareTimeoutMs,
+ });
+ }
+ return runImessageCli(
+ 'unreact',
+ [input.threadId, input.messageId, input.reaction],
+ effectiveInput,
+ context,
+ { timeoutMs: input.reactionTimeoutMs }
+ );
+ },
+ }),
+ commandTool({
+ slug: 'MARK_READ',
+ name: 'Mark iMessage thread read',
+ description:
+ 'Mark a chat/thread as read by sending a read receipt. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'mark-read',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'MARK_UNREAD',
+ name: 'Mark iMessage thread unread',
+ description: 'Mark a chat/thread as unread. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'mark-unread',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'MUTE_THREAD',
+ name: 'Mute iMessage thread',
+ description: 'Mute a chat/thread indefinitely. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'mute',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'UNMUTE_THREAD',
+ name: 'Unmute iMessage thread',
+ description: 'Unmute a chat/thread. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'unmute',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'SEND_TYPING_STATUS',
+ name: 'Send iMessage typing status',
+ description: 'Send typing on/off status for a chat/thread. Mutates real Messages state.',
+ inputParams: baseInput.extend({
+ threadId,
+ status: z.enum(['on', 'off']).describe('Typing status to send.'),
+ }),
+ command: 'typing',
+ args: input => [input.threadId, input.status],
+ }),
+ commandTool({
+ slug: 'NOTIFY_ANYWAY',
+ name: 'Notify anyway for iMessage thread',
+ description:
+ 'Trigger the Messages "notify anyway" action for a chat/thread. Mutates real Messages state.',
+ inputParams: baseInput.extend({ threadId }),
+ command: 'notify-anyway',
+ args: input => [input.threadId],
+ }),
+ commandTool({
+ slug: 'DELETE_THREAD',
+ name: 'Delete iMessage thread',
+ description:
+ 'Delete a chat/thread from Messages. Requires confirm=true because this mutates real Messages state.',
+ inputParams: baseInput.extend({
+ threadId,
+ confirm: z.literal(true).describe('Must be true to delete the thread.'),
+ }),
+ command: 'delete-thread',
+ args: input => [input.threadId],
+ }),
+ ],
+};
diff --git a/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.test.ts b/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.test.ts
new file mode 100644
index 000000000..e2f3be89c
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
+import { chromeDevtoolsToolkit } from './chrome-devtools';
+
+describe('@composio/cli-local-tools Chrome DevTools toolkit', () => {
+ it('exposes first-class schemas for documented Chrome DevTools tools', () => {
+ expect(chromeDevtoolsToolkit.source?.type).toBe('mcp');
+ expect(chromeDevtoolsToolkit.tools.map(tool => tool.slug)).toEqual(
+ expect.arrayContaining([
+ 'LIST_PAGES',
+ 'NEW_PAGE',
+ 'NAVIGATE_PAGE',
+ 'TAKE_SNAPSHOT',
+ 'EVALUATE_SCRIPT',
+ 'CLICK',
+ 'DRAG',
+ 'HANDLE_DIALOG',
+ 'LIST_NETWORK_REQUESTS',
+ 'LIST_EXTENSIONS',
+ ])
+ );
+
+ const newPageSchema = getLocalToolInputDefinition('LOCAL_CHROME_DEVTOOLS_NEW_PAGE');
+ expect(newPageSchema?.schema.properties).toHaveProperty('url');
+ expect(newPageSchema?.schema.required).toContain('url');
+
+ const evaluateSchema = getLocalToolInputDefinition('LOCAL_CHROME_DEVTOOLS_EVALUATE_SCRIPT');
+ expect(evaluateSchema?.schema.properties).toHaveProperty('function');
+ expect(evaluateSchema?.schema.properties).toHaveProperty('args');
+ });
+
+ it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1')(
+ 'validates against a real chrome-devtools-mcp daemon',
+ async () => {
+ try {
+ const start = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_START_DAEMON', {
+ headless: true,
+ usageStatistics: false,
+ performanceCrux: false,
+ });
+ expect(start?.ok).toBe(true);
+
+ const page = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_NEW_PAGE', {
+ url: 'data:text/html,<title>Composio Chrome Local Tools</title><h1>Hello from Chrome</h1>',
+ });
+ expect(page?.ok).toBe(true);
+
+ const evaluated = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_EVALUATE_SCRIPT', {
+ function: '() => document.title',
+ });
+ expect(evaluated?.result).toEqual(
+ expect.objectContaining({
+ message: expect.stringContaining('Composio Chrome Local Tools'),
+ })
+ );
+
+ const pages = await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_LIST_PAGES', {});
+ expect(pages?.result).toEqual(expect.objectContaining({ pages: expect.any(Array) }));
+ } finally {
+ await executeLocalToolBySlug('LOCAL_CHROME_DEVTOOLS_STOP_DAEMON', {});
+ }
+ },
+ 120_000
+ );
+});
diff --git a/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.ts b/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.ts
new file mode 100644
index 000000000..e5e37e1ac
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/chrome-devtools.ts
@@ -0,0 +1,788 @@
+import { z } from 'zod/v3';
+import { runLocalCommand } from '../runtime';
+import type {
+ LocalCommandExecution,
+ LocalExecutionContext,
+ LocalExecutionResult,
+ LocalToolkitDeclaration,
+ LocalToolDeclaration,
+} from '../types';
+
+const CHROME_DEVTOOLS_MCP_VERSION = '0.24.0';
+const COMMAND_TIMEOUT_MS = 180_000;
+
+const cliOutput = z.object({
+ ok: z.boolean(),
+ commandName: z.string(),
+ result: z.unknown().optional(),
+ resultText: z.string().optional(),
+ stdout: z.string(),
+ stderr: z.string(),
+});
+
+const baseInput = z.object({
+ debug: z.boolean().default(false).describe('Set DEBUG=* for the chrome-devtools command.'),
+ sessionId: z
+ .string()
+ .optional()
+ .describe('Optional upstream chrome-devtools CLI session id for isolated daemon state.'),
+});
+
+const pageId = z.number().int().nonnegative().describe('Page ID from LIST_PAGES.');
+const uid = z.string().min(1).describe('Element uid from TAKE_SNAPSHOT.');
+
+const npxArgs = [
+ '-y',
+ '--package',
+ `chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION}`,
+ 'chrome-devtools',
+];
+
+const addOption = (args: string[], name: string, value: unknown): string[] => {
+ if (value === undefined || value === null || value === '') return args;
+ args.push(`--${name}`, String(value));
+ return args;
+};
+
+const addBooleanFlag = (args: string[], name: string, value: unknown): string[] => {
+ if (value === true) args.push(`--${name}`);
+ return args;
+};
+
+const addBooleanOption = (args: string[], name: string, value: unknown): string[] => {
+ if (value === true) args.push(`--${name}`);
+ if (value === false) args.push(`--no-${name}`);
+ return args;
+};
+
+const addRepeated = (args: string[], name: string, values: unknown): string[] => {
+ if (!Array.isArray(values)) return args;
+ for (const value of values) {
+ if (value === undefined || value === null || value === '') continue;
+ args.push(`--${name}`, String(value));
+ }
+ return args;
+};
+
+const extractJson = (text: string): unknown | undefined => {
+ const candidates = [text.indexOf('{'), text.indexOf('[')].filter(index => index >= 0);
+ if (!candidates.length) return undefined;
+
+ const start = Math.min(...candidates);
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+
+ for (let index = start; index < text.length; index += 1) {
+ const char = text[index];
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (char === '\\') {
+ escaped = true;
+ } else if (char === '"') {
+ inString = false;
+ }
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ continue;
+ }
+ if (char === '{' || char === '[') {
+ depth += 1;
+ continue;
+ }
+ if (char === '}' || char === ']') {
+ depth -= 1;
+ if (depth === 0) {
+ try {
+ return JSON.parse(text.slice(start, index + 1)) as unknown;
+ } catch {
+ return undefined;
+ }
+ }
+ }
+ }
+
+ return undefined;
+};
+
+const parseChromeDevtoolsOutput = (
+ commandName: string,
+ stdout: string,
+ stderr: string,
+ parseJson: boolean
+): LocalExecutionResult => {
+ const trimmed = stdout.trim();
+ const result = parseJson ? extractJson(trimmed) : undefined;
+ return {
+ ok: true,
+ commandName,
+ ...(result !== undefined ? { result } : {}),
+ ...(result === undefined && trimmed ? { resultText: trimmed } : {}),
+ stdout,
+ stderr,
+ };
+};
+
+const runChromeDevtools = async (
+ commandName: string,
+ commandArgs: ReadonlyArray<string>,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext,
+ options: { readonly json?: boolean } = { json: true }
+): Promise<LocalExecutionResult> => {
+ const args = [...npxArgs];
+ addOption(args, 'sessionId', input.sessionId);
+ args.push(commandName, ...commandArgs);
+ if (options.json !== false) args.push('--output-format=json');
+ const execution: LocalCommandExecution = {
+ kind: 'command',
+ command: 'npx',
+ args,
+ env: {
+ CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS: '1',
+ ...(input.usageStatistics === true ? {} : { CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: '1' }),
+ ...(input.debug === true ? { DEBUG: '*' } : {}),
+ },
+ timeoutMs: COMMAND_TIMEOUT_MS,
+ };
+ const result = await runLocalCommand(execution, input, context);
+ return parseChromeDevtoolsOutput(
+ commandName,
+ String(result.stdout ?? ''),
+ String(result.stderr ?? ''),
+ options.json !== false
+ );
+};
+
+const commandTool = <TInput extends z.ZodTypeAny>(definition: {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputParams: TInput;
+ readonly command: string;
+ readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
+ readonly json?: boolean;
+}): LocalToolDeclaration<TInput> => ({
+ slug: definition.slug,
+ name: definition.name,
+ description: definition.description,
+ platforms: ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'],
+ inputParams: definition.inputParams,
+ outputParams: cliOutput,
+ execution: {
+ kind: 'native',
+ readiness: {
+ command: 'npx',
+ args: npxArgs,
+ },
+ execute: (input, context) =>
+ runChromeDevtools(
+ definition.command,
+ definition.args(input as z.infer<TInput>),
+ input,
+ context,
+ { json: definition.json }
+ ),
+ },
+});
+
+export const chromeDevtoolsToolkit: LocalToolkitDeclaration = {
+ slug: 'CHROME_DEVTOOLS',
+ name: 'Chrome DevTools (local)',
+ description:
+ 'Local Chrome automation and debugging tools backed by the official chrome-devtools-mcp package and its chrome-devtools CLI daemon.',
+ platforms: ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'],
+ source: {
+ type: 'mcp',
+ package: `chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION}`,
+ repository: 'https://github.com/ChromeDevTools/chrome-devtools-mcp',
+ command: `npx -y --package chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION} chrome-devtools`,
+ },
+ setup: {
+ install: `Requires Node.js/npm and a supported Chrome installation. Tools run via npx --package chrome-devtools-mcp@${CHROME_DEVTOOLS_MCP_VERSION} chrome-devtools.`,
+ commandOverrides: [],
+ notes: [
+ 'The upstream chrome-devtools CLI automatically starts and reuses a background chrome-devtools-mcp daemon for stateful browser sessions.',
+ 'Use START_DAEMON to configure headless/browserUrl/userDataDir before invoking page tools, or let the first tool auto-start the daemon with upstream defaults.',
+ 'Use STOP_DAEMON when finished to close the background MCP/browser process.',
+ 'Chrome DevTools MCP can inspect and modify browser contents; avoid using it on sensitive sessions.',
+ ],
+ },
+ tools: [
+ commandTool({
+ slug: 'START_DAEMON',
+ name: 'Start Chrome DevTools MCP daemon',
+ description:
+ 'Start or restart the background chrome-devtools-mcp daemon and browser with optional launch settings.',
+ inputParams: baseInput.extend({
+ browserUrl: z
+ .string()
+ .optional()
+ .describe('Connect to an existing debuggable Chrome URL, e.g. http://127.0.0.1:9222.'),
+ wsEndpoint: z
+ .string()
+ .optional()
+ .describe('Connect to an existing Chrome DevTools WebSocket endpoint.'),
+ headless: z.boolean().optional().describe('Run Chrome headless. Upstream default is true.'),
+ executablePath: z.string().optional().describe('Custom Chrome executable path.'),
+ userDataDir: z.string().optional().describe('Chrome user data directory.'),
+ channel: z
+ .enum(['canary', 'dev', 'beta', 'stable'])
+ .optional()
+ .describe('Chrome release channel.'),
+ isolated: z.boolean().optional().describe('Use an isolated temporary user data dir.'),
+ acceptInsecureCerts: z
+ .boolean()
+ .optional()
+ .describe('Ignore self-signed/expired certificate errors.'),
+ proxyServer: z.string().optional().describe('Chrome proxy server setting.'),
+ performanceCrux: z
+ .boolean()
+ .optional()
+ .describe('Allow CrUX field data lookups for performance tools.'),
+ usageStatistics: z
+ .boolean()
+ .optional()
+ .describe('Allow Google usage statistics for the MCP server.'),
+ slim: z.boolean().optional().describe('Expose the upstream slim tool set.'),
+ categoryExtensions: z
+ .boolean()
+ .optional()
+ .describe('Enable or disable Chrome extension tools in the upstream daemon.'),
+ }),
+ command: 'start',
+ json: false,
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'browserUrl', input.browserUrl);
+ addOption(args, 'wsEndpoint', input.wsEndpoint);
+ addBooleanOption(args, 'headless', input.headless);
+ addOption(args, 'executablePath', input.executablePath);
+ addOption(args, 'userDataDir', input.userDataDir);
+ addOption(args, 'channel', input.channel);
+ addBooleanOption(args, 'isolated', input.isolated);
+ addBooleanFlag(args, 'acceptInsecureCerts', input.acceptInsecureCerts);
+ addOption(args, 'proxyServer', input.proxyServer);
+ addBooleanOption(args, 'performanceCrux', input.performanceCrux);
+ addBooleanOption(args, 'usageStatistics', input.usageStatistics);
+ addBooleanFlag(args, 'slim', input.slim);
+ addBooleanOption(args, 'categoryExtensions', input.categoryExtensions);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'STOP_DAEMON',
+ name: 'Stop Chrome DevTools MCP daemon',
+ description: 'Stop the background chrome-devtools-mcp daemon/browser if running.',
+ inputParams: baseInput,
+ command: 'stop',
+ json: false,
+ args: () => [],
+ }),
+ commandTool({
+ slug: 'STATUS_DAEMON',
+ name: 'Get Chrome DevTools MCP daemon status',
+ description: 'Check whether the chrome-devtools-mcp daemon is running.',
+ inputParams: baseInput,
+ command: 'status',
+ json: false,
+ args: () => [],
+ }),
+ commandTool({
+ slug: 'LIST_PAGES',
+ name: 'List Chrome pages',
+ description: 'Get pages open in the browser controlled by Chrome DevTools MCP.',
+ inputParams: baseInput,
+ command: 'list_pages',
+ args: () => [],
+ }),
+ commandTool({
+ slug: 'NEW_PAGE',
+ name: 'Open new Chrome page',
+ description: 'Open a new Chrome tab and load a URL.',
+ inputParams: baseInput.extend({
+ url: z.string().url().describe('URL to load in a new page.'),
+ background: z.boolean().optional().describe('Open in background.'),
+ isolatedContext: z.string().optional().describe('Named isolated browser context.'),
+ timeout: z
+ .number()
+ .int()
+ .nonnegative()
+ .optional()
+ .describe('Maximum wait time in milliseconds.'),
+ }),
+ command: 'new_page',
+ args: input => {
+ const args = [input.url];
+ addBooleanFlag(args, 'background', input.background);
+ addOption(args, 'isolatedContext', input.isolatedContext);
+ addOption(args, 'timeout', input.timeout);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'NAVIGATE_PAGE',
+ name: 'Navigate Chrome page',
+ description: 'Navigate selected page by URL, back, forward, or reload.',
+ inputParams: baseInput.extend({
+ type: z.enum(['url', 'back', 'forward', 'reload']).optional().describe('Navigation type.'),
+ url: z.string().optional().describe('Target URL for type=url.'),
+ ignoreCache: z.boolean().optional().describe('Ignore cache on reload.'),
+ handleBeforeUnload: z
+ .enum(['accept', 'decline'])
+ .optional()
+ .describe('Handle beforeunload dialogs.'),
+ initScript: z
+ .string()
+ .optional()
+ .describe('Script to run before the next navigation document loads.'),
+ timeout: z
+ .number()
+ .int()
+ .nonnegative()
+ .optional()
+ .describe('Maximum wait time in milliseconds.'),
+ }),
+ command: 'navigate_page',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'type', input.type);
+ addOption(args, 'url', input.url);
+ addBooleanFlag(args, 'ignoreCache', input.ignoreCache);
+ addOption(args, 'handleBeforeUnload', input.handleBeforeUnload);
+ addOption(args, 'initScript', input.initScript);
+ addOption(args, 'timeout', input.timeout);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'SELECT_PAGE',
+ name: 'Select Chrome page',
+ description: 'Select a page as context for future Chrome DevTools tool calls.',
+ inputParams: baseInput.extend({ pageId, bringToFront: z.boolean().optional() }),
+ command: 'select_page',
+ args: input => {
+ const args = [String(input.pageId)];
+ addBooleanFlag(args, 'bringToFront', input.bringToFront);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'CLOSE_PAGE',
+ name: 'Close Chrome page',
+ description: 'Close a page by ID. The last open page cannot be closed.',
+ inputParams: baseInput.extend({ pageId }),
+ command: 'close_page',
+ args: input => [String(input.pageId)],
+ }),
+ commandTool({
+ slug: 'TAKE_SNAPSHOT',
+ name: 'Take Chrome accessibility snapshot',
+ description:
+ 'Take a text snapshot of the selected page, including element uids for automation.',
+ inputParams: baseInput.extend({
+ filePath: z.string().optional().describe('Optional path to save the snapshot.'),
+ verbose: z.boolean().optional().describe('Include all a11y tree details.'),
+ }),
+ command: 'take_snapshot',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'filePath', input.filePath);
+ addBooleanFlag(args, 'verbose', input.verbose);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'TAKE_SCREENSHOT',
+ name: 'Take Chrome screenshot',
+ description: 'Take a screenshot of the selected page or element.',
+ inputParams: baseInput.extend({
+ filePath: z.string().optional(),
+ format: z.enum(['png', 'jpeg', 'webp']).optional(),
+ quality: z.number().min(0).max(100).optional(),
+ fullPage: z.boolean().optional(),
+ uid: z.string().optional(),
+ }),
+ command: 'take_screenshot',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'filePath', input.filePath);
+ addOption(args, 'format', input.format);
+ addOption(args, 'quality', input.quality);
+ addBooleanFlag(args, 'fullPage', input.fullPage);
+ addOption(args, 'uid', input.uid);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'EVALUATE_SCRIPT',
+ name: 'Evaluate JavaScript in Chrome page',
+ description:
+ 'Evaluate a JavaScript function in the selected page and return a JSON-serializable result.',
+ inputParams: baseInput.extend({
+ function: z.string().min(1).describe('Function declaration, e.g. () => document.title.'),
+ args: z.array(z.unknown()).optional().describe('Arguments passed to the function.'),
+ dialogAction: z
+ .string()
+ .optional()
+ .describe('Dialog action: accept, dismiss, or prompt response.'),
+ }),
+ command: 'evaluate_script',
+ args: input => {
+ const args = [input.function];
+ if (input.args !== undefined) addOption(args, 'args', JSON.stringify(input.args));
+ addOption(args, 'dialogAction', input.dialogAction);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'LIST_CONSOLE_MESSAGES',
+ name: 'List Chrome console messages',
+ description: 'List console messages for the selected page since the last navigation.',
+ inputParams: baseInput.extend({
+ pageSize: z.number().int().positive().optional(),
+ pageIdx: z.number().int().nonnegative().optional(),
+ types: z.array(z.string()).optional(),
+ includePreservedMessages: z.boolean().optional(),
+ }),
+ command: 'list_console_messages',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'pageSize', input.pageSize);
+ addOption(args, 'pageIdx', input.pageIdx);
+ addRepeated(args, 'types', input.types);
+ addBooleanFlag(args, 'includePreservedMessages', input.includePreservedMessages);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'GET_CONSOLE_MESSAGE',
+ name: 'Get Chrome console message',
+ description: 'Get a console message by ID from LIST_CONSOLE_MESSAGES.',
+ inputParams: baseInput.extend({ msgid: z.number().int().nonnegative() }),
+ command: 'get_console_message',
+ args: input => [String(input.msgid)],
+ }),
+ commandTool({
+ slug: 'LIST_NETWORK_REQUESTS',
+ name: 'List Chrome network requests',
+ description: 'List network requests for the selected page since the last navigation.',
+ inputParams: baseInput.extend({
+ pageSize: z.number().int().positive().optional(),
+ pageIdx: z.number().int().nonnegative().optional(),
+ resourceTypes: z.array(z.string()).optional(),
+ includePreservedRequests: z.boolean().optional(),
+ }),
+ command: 'list_network_requests',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'pageSize', input.pageSize);
+ addOption(args, 'pageIdx', input.pageIdx);
+ addRepeated(args, 'resourceTypes', input.resourceTypes);
+ addBooleanFlag(args, 'includePreservedRequests', input.includePreservedRequests);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'GET_NETWORK_REQUEST',
+ name: 'Get Chrome network request',
+ description:
+ 'Get a selected or specific network request and optionally save bodies to files.',
+ inputParams: baseInput.extend({
+ reqid: z.number().int().nonnegative().optional(),
+ requestFilePath: z.string().optional(),
+ responseFilePath: z.string().optional(),
+ }),
+ command: 'get_network_request',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'reqid', input.reqid);
+ addOption(args, 'requestFilePath', input.requestFilePath);
+ addOption(args, 'responseFilePath', input.responseFilePath);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'CLICK',
+ name: 'Click Chrome page element',
+ description: 'Click an element by uid from TAKE_SNAPSHOT.',
+ inputParams: baseInput.extend({
+ uid,
+ dblClick: z.boolean().optional(),
+ includeSnapshot: z.boolean().optional(),
+ }),
+ command: 'click',
+ args: input => {
+ const args = [input.uid];
+ addBooleanFlag(args, 'dblClick', input.dblClick);
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'FILL',
+ name: 'Fill Chrome page field',
+ description: 'Fill an input, textarea, or select element by uid from TAKE_SNAPSHOT.',
+ inputParams: baseInput.extend({
+ uid,
+ value: z.string(),
+ includeSnapshot: z.boolean().optional(),
+ }),
+ command: 'fill',
+ args: input => {
+ const args = [input.uid, input.value];
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'DRAG',
+ name: 'Drag Chrome page element',
+ description: 'Drag an element by uid onto another element by uid.',
+ inputParams: baseInput.extend({
+ from_uid: z.string().min(1).describe('Uid of the element to drag.'),
+ to_uid: z.string().min(1).describe('Uid of the drop target element.'),
+ includeSnapshot: z.boolean().optional(),
+ }),
+ command: 'drag',
+ args: input => {
+ const args = [input.from_uid, input.to_uid];
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'HANDLE_DIALOG',
+ name: 'Handle Chrome dialog',
+ description: 'Accept or dismiss a browser dialog, optionally providing prompt text.',
+ inputParams: baseInput.extend({
+ action: z.enum(['accept', 'dismiss']),
+ promptText: z.string().optional(),
+ }),
+ command: 'handle_dialog',
+ args: input => {
+ const args = [input.action];
+ addOption(args, 'promptText', input.promptText);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'HOVER',
+ name: 'Hover Chrome page element',
+ description: 'Hover an element by uid from TAKE_SNAPSHOT.',
+ inputParams: baseInput.extend({ uid, includeSnapshot: z.boolean().optional() }),
+ command: 'hover',
+ args: input => {
+ const args = [input.uid];
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'PRESS_KEY',
+ name: 'Press key in Chrome page',
+ description: 'Press a key or key combination in the selected page.',
+ inputParams: baseInput.extend({
+ key: z.string().min(1),
+ includeSnapshot: z.boolean().optional(),
+ }),
+ command: 'press_key',
+ args: input => {
+ const args = [input.key];
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'TYPE_TEXT',
+ name: 'Type text in Chrome page',
+ description: 'Type text with the keyboard into the currently focused input.',
+ inputParams: baseInput.extend({
+ text: z.string(),
+ submitKey: z
+ .string()
+ .optional()
+ .describe('Optional key pressed after typing, e.g. Enter, Tab, Escape.'),
+ }),
+ command: 'type_text',
+ args: input => {
+ const args = [input.text];
+ addOption(args, 'submitKey', input.submitKey);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'UPLOAD_FILE',
+ name: 'Upload file in Chrome page',
+ description: 'Upload a local file through a file input or element that opens a file chooser.',
+ inputParams: baseInput.extend({
+ uid,
+ filePath: z.string().min(1),
+ includeSnapshot: z.boolean().optional(),
+ }),
+ command: 'upload_file',
+ args: input => {
+ const args = [input.uid, input.filePath];
+ addBooleanFlag(args, 'includeSnapshot', input.includeSnapshot);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'RESIZE_PAGE',
+ name: 'Resize Chrome page',
+ description: 'Resize the selected page window to specific dimensions.',
+ inputParams: baseInput.extend({
+ width: z.number().positive(),
+ height: z.number().positive(),
+ }),
+ command: 'resize_page',
+ args: input => [String(input.width), String(input.height)],
+ }),
+ commandTool({
+ slug: 'EMULATE',
+ name: 'Emulate Chrome page conditions',
+ description:
+ 'Emulate color scheme, CPU/network throttling, geolocation, user agent, or viewport.',
+ inputParams: baseInput.extend({
+ colorScheme: z.enum(['dark', 'light', 'auto']).optional(),
+ cpuThrottlingRate: z.number().positive().optional(),
+ geolocation: z
+ .string()
+ .optional()
+ .describe('Latitude/longitude as <latitude>x<longitude>, or omit to clear.'),
+ networkConditions: z
+ .enum(['Offline', 'Slow 3G', 'Fast 3G', 'Slow 4G', 'Fast 4G'])
+ .optional(),
+ userAgent: z.string().optional(),
+ viewport: z
+ .string()
+ .optional()
+ .describe('<width>x<height>x<devicePixelRatio>[,mobile][,touch][,landscape].'),
+ }),
+ command: 'emulate',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'colorScheme', input.colorScheme);
+ addOption(args, 'cpuThrottlingRate', input.cpuThrottlingRate);
+ addOption(args, 'geolocation', input.geolocation);
+ addOption(args, 'networkConditions', input.networkConditions);
+ addOption(args, 'userAgent', input.userAgent);
+ addOption(args, 'viewport', input.viewport);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'LIGHTHOUSE_AUDIT',
+ name: 'Run Chrome Lighthouse audit',
+ description:
+ 'Run an accessibility/SEO/best-practices/agentic-browsing Lighthouse audit on the selected page.',
+ inputParams: baseInput.extend({
+ mode: z.enum(['navigation', 'snapshot']).optional(),
+ device: z.enum(['desktop', 'mobile']).optional(),
+ outputDirPath: z.string().optional(),
+ }),
+ command: 'lighthouse_audit',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'mode', input.mode);
+ addOption(args, 'device', input.device);
+ addOption(args, 'outputDirPath', input.outputDirPath);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'PERFORMANCE_START_TRACE',
+ name: 'Start Chrome performance trace',
+ description: 'Start a Chrome DevTools performance trace on the selected page.',
+ inputParams: baseInput.extend({
+ reload: z.boolean().optional(),
+ autoStop: z.boolean().optional(),
+ filePath: z.string().optional(),
+ }),
+ command: 'performance_start_trace',
+ args: input => {
+ const args: string[] = [];
+ addBooleanFlag(args, 'reload', input.reload);
+ addBooleanFlag(args, 'autoStop', input.autoStop);
+ addOption(args, 'filePath', input.filePath);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'PERFORMANCE_STOP_TRACE',
+ name: 'Stop Chrome performance trace',
+ description: 'Stop the active Chrome DevTools performance trace and return insights.',
+ inputParams: baseInput.extend({ filePath: z.string().optional() }),
+ command: 'performance_stop_trace',
+ args: input => {
+ const args: string[] = [];
+ addOption(args, 'filePath', input.filePath);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'PERFORMANCE_ANALYZE_INSIGHT',
+ name: 'Analyze Chrome performance insight',
+ description:
+ 'Return detailed information for a specific performance insight from a trace result.',
+ inputParams: baseInput.extend({
+ insightSetId: z.string().min(1),
+ insightName: z.string().min(1),
+ }),
+ command: 'performance_analyze_insight',
+ args: input => [input.insightSetId, input.insightName],
+ }),
+ commandTool({
+ slug: 'LIST_EXTENSIONS',
+ name: 'List Chrome extensions',
+ description: 'List Chrome extensions installed in the controlled browser.',
+ inputParams: baseInput,
+ command: 'list_extensions',
+ args: () => [],
+ }),
+ commandTool({
+ slug: 'INSTALL_EXTENSION',
+ name: 'Install Chrome extension',
+ description: 'Install an unpacked Chrome extension from an absolute local path.',
+ inputParams: baseInput.extend({ path: z.string().min(1) }),
+ command: 'install_extension',
+ args: input => [input.path],
+ }),
+ commandTool({
+ slug: 'RELOAD_EXTENSION',
+ name: 'Reload Chrome extension',
+ description: 'Reload an unpacked Chrome extension by extension id.',
+ inputParams: baseInput.extend({ id: z.string().min(1) }),
+ command: 'reload_extension',
+ args: input => [input.id],
+ }),
+ commandTool({
+ slug: 'TRIGGER_EXTENSION_ACTION',
+ name: 'Trigger Chrome extension action',
+ description: 'Trigger the default toolbar action for a Chrome extension by id.',
+ inputParams: baseInput.extend({ id: z.string().min(1) }),
+ command: 'trigger_extension_action',
+ args: input => [input.id],
+ }),
+ commandTool({
+ slug: 'UNINSTALL_EXTENSION',
+ name: 'Uninstall Chrome extension',
+ description: 'Uninstall a Chrome extension by extension id.',
+ inputParams: baseInput.extend({ id: z.string().min(1) }),
+ command: 'uninstall_extension',
+ args: input => [input.id],
+ }),
+ commandTool({
+ slug: 'TAKE_MEMORY_SNAPSHOT',
+ name: 'Take Chrome memory snapshot',
+ description:
+ 'Capture a heap snapshot of the selected page to a local file for memory analysis.',
+ inputParams: baseInput.extend({ filePath: z.string().min(1) }),
+ command: 'take_memory_snapshot',
+ args: input => [input.filePath],
+ }),
+ ],
+};
diff --git a/ts/packages/cli-local-tools/src/toolkits/peekaboo.test.ts b/ts/packages/cli-local-tools/src/toolkits/peekaboo.test.ts
new file mode 100644
index 000000000..ab5c01db8
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/peekaboo.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { resolveBundledBinary } from '../bundled-binaries';
+import { executeLocalToolBySlug, getLocalToolInputDefinition } from '../registry';
+import { peekabooToolkit } from './peekaboo';
+
+describe('@composio/cli-local-tools Peekaboo toolkit', () => {
+ it('exposes first-class schemas for Peekaboo tools', () => {
+ expect(peekabooToolkit.tools.map(tool => tool.slug)).toEqual(
+ expect.arrayContaining([
+ 'PERMISSIONS_STATUS',
+ 'LIST_APPS',
+ 'SEE',
+ 'IMAGE',
+ 'CLICK',
+ 'TYPE',
+ 'WINDOW_FOCUS',
+ 'APP_LAUNCH',
+ ])
+ );
+
+ const seeSchema = getLocalToolInputDefinition('LOCAL_PEEKABOO_SEE');
+ expect(seeSchema?.schema.properties).toHaveProperty('app');
+ expect(seeSchema?.schema.properties).toHaveProperty('annotate');
+
+ const clickSchema = getLocalToolInputDefinition('LOCAL_PEEKABOO_CLICK');
+ expect(clickSchema?.schema.properties).toHaveProperty('on');
+ expect(clickSchema?.schema.properties).toHaveProperty('coords');
+ });
+
+ it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
+ 'resolves generated bundled Peekaboo CLI and executes version without permissions',
+ async () => {
+ const resolved = await resolveBundledBinary(
+ peekabooToolkit,
+ { bundledBinary: 'peekaboo-cli' },
+ { currentPlatform: process.arch === 'x64' ? 'darwin-x64' : 'darwin-arm64' }
+ );
+ expect(resolved?.exists).toBe(true);
+
+ const result = await executeLocalToolBySlug('LOCAL_PEEKABOO_VERSION', {});
+ expect(result?.resultText).toContain('Peekaboo 3.0.0');
+ }
+ );
+
+ it.runIf(process.env.COMPOSIO_REAL_LOCAL_TOOLS_TESTS === '1' && process.platform === 'darwin')(
+ 'validates against real Peekaboo permission and app-list commands',
+ async () => {
+ const permissions = await executeLocalToolBySlug('LOCAL_PEEKABOO_PERMISSIONS_STATUS', {});
+ expect(permissions?.result).toEqual(expect.objectContaining({ success: true }));
+
+ const apps = await executeLocalToolBySlug('LOCAL_PEEKABOO_LIST_APPS', {});
+ expect(apps?.result).toEqual(
+ expect.objectContaining({
+ data: expect.objectContaining({ applications: expect.any(Array) }),
+ })
+ );
+ },
+ 120_000
+ );
+});
diff --git a/ts/packages/cli-local-tools/src/toolkits/peekaboo.ts b/ts/packages/cli-local-tools/src/toolkits/peekaboo.ts
new file mode 100644
index 000000000..b262c51ba
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/toolkits/peekaboo.ts
@@ -0,0 +1,965 @@
+import { z } from 'zod/v3';
+import { runLocalCommand } from '../runtime';
+import type {
+ LocalCommandExecution,
+ LocalExecutionContext,
+ LocalExecutionResult,
+ LocalToolkitDeclaration,
+ LocalToolDeclaration,
+} from '../types';
+
+const PEEKABOO_VERSION = '3.0.0-beta4';
+const COMMAND_TIMEOUT_MS = 180_000;
+
+const cliOutput = z.object({
+ ok: z.boolean(),
+ commandName: z.string(),
+ result: z.unknown().optional(),
+ resultText: z.string().optional(),
+ stdout: z.string(),
+ stderr: z.string(),
+});
+
+const baseInput = z.object({
+ verbose: z.boolean().default(false).describe('Enable verbose Peekaboo logging.'),
+ noRemote: z
+ .boolean()
+ .default(false)
+ .describe('Force local Peekaboo services and skip the XPC helper.'),
+ logLevel: z
+ .enum(['trace', 'verbose', 'debug', 'info', 'warning', 'error', 'critical'])
+ .optional(),
+ xpcService: z.string().optional().describe('Override Peekaboo XPC helper mach service name.'),
+});
+
+const targetInput = {
+ app: z.string().optional().describe('Application name, bundle id, or PID:1234 target.'),
+ pid: z.number().int().positive().optional().describe('Target application process id.'),
+ windowTitle: z.string().optional().describe('Target window title.'),
+ windowIndex: z.number().int().nonnegative().optional().describe('0-based target window index.'),
+} as const;
+
+const focusInput = {
+ noAutoFocus: z.boolean().optional().describe('Disable automatic focus before interaction.'),
+ spaceSwitch: z.boolean().optional().describe("Switch to the target window's Space if needed."),
+ bringToCurrentSpace: z
+ .boolean()
+ .optional()
+ .describe('Move target window to current Space instead.'),
+ focusTimeoutSeconds: z.number().positive().optional(),
+ focusRetryCountValue: z.number().int().nonnegative().optional(),
+} as const;
+
+const extractJson = (text: string): unknown | undefined => {
+ const candidates = [text.indexOf('{'), text.indexOf('[')].filter(index => index >= 0);
+ if (!candidates.length) return undefined;
+
+ const start = Math.min(...candidates);
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+
+ for (let index = start; index < text.length; index += 1) {
+ const char = text[index];
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (char === '\\') {
+ escaped = true;
+ } else if (char === '"') {
+ inString = false;
+ }
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ continue;
+ }
+ if (char === '{' || char === '[') {
+ depth += 1;
+ continue;
+ }
+ if (char === '}' || char === ']') {
+ depth -= 1;
+ if (depth === 0) {
+ try {
+ return JSON.parse(text.slice(start, index + 1)) as unknown;
+ } catch {
+ return undefined;
+ }
+ }
+ }
+ }
+
+ return undefined;
+};
+
+const addOption = (args: string[], name: string, value: unknown): string[] => {
+ if (value === undefined || value === null || value === '') return args;
+ args.push(`--${name}`, String(value));
+ return args;
+};
+
+const addBooleanFlag = (args: string[], name: string, value: unknown): string[] => {
+ if (value === true) args.push(`--${name}`);
+ return args;
+};
+
+const addRepeated = (args: string[], name: string, values: unknown): string[] => {
+ if (!Array.isArray(values)) return args;
+ for (const value of values) {
+ if (value === undefined || value === null || value === '') continue;
+ args.push(`--${name}`, String(value));
+ }
+ return args;
+};
+
+const addGlobalOptions = (args: string[], input: Record<string, unknown>, json: boolean) => {
+ if (json) args.push('--json');
+ addBooleanFlag(args, 'verbose', input.verbose);
+ addBooleanFlag(args, 'no-remote', input.noRemote);
+ addOption(args, 'log-level', input.logLevel);
+ addOption(args, 'xpc-service', input.xpcService);
+};
+
+const addTargetOptions = (args: string[], input: Record<string, unknown>) => {
+ addOption(args, 'app', input.app);
+ addOption(args, 'pid', input.pid);
+ addOption(args, 'window-title', input.windowTitle);
+ addOption(args, 'window-index', input.windowIndex);
+};
+
+const addFocusOptions = (args: string[], input: Record<string, unknown>) => {
+ addBooleanFlag(args, 'no-auto-focus', input.noAutoFocus);
+ addBooleanFlag(args, 'space-switch', input.spaceSwitch);
+ addBooleanFlag(args, 'bring-to-current-space', input.bringToCurrentSpace);
+ addOption(args, 'focus-timeout-seconds', input.focusTimeoutSeconds);
+ addOption(args, 'focus-retry-count-value', input.focusRetryCountValue);
+};
+
+const parsePeekabooOutput = (
+ commandName: string,
+ stdout: string,
+ stderr: string,
+ parseJson: boolean
+): LocalExecutionResult => {
+ const trimmed = stdout.trim();
+ const result = parseJson ? extractJson(trimmed) : undefined;
+ return {
+ ok: true,
+ commandName,
+ ...(result !== undefined ? { result } : {}),
+ ...(result === undefined && trimmed ? { resultText: trimmed } : {}),
+ stdout,
+ stderr,
+ };
+};
+
+const runPeekaboo = async (
+ commandName: string,
+ commandArgs: ReadonlyArray<string>,
+ input: Record<string, unknown>,
+ context: LocalExecutionContext,
+ options: { readonly json?: boolean } = { json: true }
+): Promise<LocalExecutionResult> => {
+ const args = [...commandArgs];
+ const parseJson = options.json !== false;
+ addGlobalOptions(args, input, parseJson);
+ const execution: LocalCommandExecution = {
+ kind: 'command',
+ command: { bundledBinary: 'peekaboo-cli', fallbackCommand: 'peekaboo' },
+ args,
+ timeoutMs: COMMAND_TIMEOUT_MS,
+ };
+ const result = await runLocalCommand(execution, input, context);
+ return parsePeekabooOutput(
+ commandName,
+ String(result.stdout ?? ''),
+ String(result.stderr ?? ''),
+ parseJson
+ );
+};
+
+const commandTool = <TInput extends z.ZodTypeAny>(definition: {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputParams: TInput;
+ readonly args: (input: z.infer<TInput>) => ReadonlyArray<string>;
+ readonly json?: boolean;
+}): LocalToolDeclaration<TInput> => ({
+ slug: definition.slug,
+ name: definition.name,
+ description: definition.description,
+ platforms: ['darwin-arm64', 'darwin-x64'],
+ inputParams: definition.inputParams,
+ outputParams: cliOutput,
+ execution: {
+ kind: 'native',
+ execute: (input, context) =>
+ runPeekaboo(definition.slug, definition.args(input as z.infer<TInput>), input, context, {
+ json: definition.json,
+ }),
+ },
+});
+
+const listDetails = z
+ .array(z.enum(['bounds', 'ids', 'off_screen']))
+ .optional()
+ .describe('Window details to include when listing windows.');
+
+export const peekabooToolkit: LocalToolkitDeclaration = {
+ slug: 'PEEKABOO',
+ name: 'Peekaboo (local)',
+ description: 'Local macOS screen capture and GUI automation tools backed by the Peekaboo CLI.',
+ platforms: ['darwin-arm64', 'darwin-x64'],
+ source: {
+ type: 'cli',
+ package: `@steipete/peekaboo@${PEEKABOO_VERSION}`,
+ repository: 'https://github.com/steipete/Peekaboo',
+ command: 'peekaboo',
+ },
+ bundledBinaries: [
+ {
+ id: 'peekaboo-cli',
+ description: 'Peekaboo macOS automation CLI',
+ targets: [
+ {
+ platforms: ['darwin-arm64'],
+ path: 'peekaboo/darwin-arm64/peekaboo',
+ },
+ {
+ platforms: ['darwin-x64'],
+ path: 'peekaboo/darwin-x64/peekaboo',
+ },
+ ],
+ },
+ ],
+ setup: {
+ install:
+ 'Requires macOS 15+, Screen Recording permission for capture/read tools, and Accessibility permission for click/type/window/menu automation. macOS Peekaboo binaries are generated for CLI release artifacts from the pinned upstream submodule; alternatively install with `brew install steipete/tap/peekaboo`.',
+ commandOverrides: [],
+ notes: [
+ 'Run PERMISSIONS_STATUS before UI automation and grant missing permissions in System Settings.',
+ 'Use SEE to capture a snapshot and element ids before CLICK, TYPE, SCROLL, MOVE, or DRAG.',
+ 'Most tools are one-shot CLI wrappers that return Peekaboo JSON output when upstream supports --json.',
+ 'Automation tools can control the local GUI; avoid sensitive screens unless intended.',
+ ],
+ },
+ tools: [
+ commandTool({
+ slug: 'VERSION',
+ name: 'Get Peekaboo version',
+ description: 'Return the bundled or installed Peekaboo CLI version.',
+ inputParams: baseInput,
+ json: false,
+ args: () => ['--version'],
+ }),
+ commandTool({
+ slug: 'PERMISSIONS_STATUS',
+ name: 'Check Peekaboo permissions',
+ description: 'Check macOS Screen Recording, Accessibility, and Automation permissions.',
+ inputParams: baseInput,
+ args: () => ['permissions', 'status'],
+ }),
+ commandTool({
+ slug: 'PERMISSIONS_GRANT',
+ name: 'Show Peekaboo permission grant instructions',
+ description: 'Return grant instructions for missing macOS permissions.',
+ inputParams: baseInput,
+ args: () => ['permissions', 'grant'],
+ }),
+ commandTool({
+ slug: 'LIST_APPS',
+ name: 'List running macOS apps',
+ description: 'Enumerate running GUI applications with process and focus metadata.',
+ inputParams: baseInput,
+ args: () => ['list', 'apps'],
+ }),
+ commandTool({
+ slug: 'LIST_WINDOWS',
+ name: 'List macOS app windows',
+ description: 'List windows for a target application with optional bounds/id details.',
+ inputParams: baseInput.extend({
+ app: z.string().min(1).describe('Application name, bundle id, or PID:1234.'),
+ includeDetails: listDetails,
+ }),
+ args: input => {
+ const args = ['list', 'windows'];
+ addOption(args, 'app', input.app);
+ if (input.includeDetails?.length)
+ addOption(args, 'include-details', input.includeDetails.join(','));
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'LIST_SCREENS',
+ name: 'List macOS screens',
+ description: 'List connected displays, resolution, scaling, and main/secondary state.',
+ inputParams: baseInput,
+ args: () => ['list', 'screens'],
+ }),
+ commandTool({
+ slug: 'LIST_MENUBAR',
+ name: 'List macOS menu bar items',
+ description: 'List menu bar/status items and indices for menu-bar automation.',
+ inputParams: baseInput,
+ args: () => ['list', 'menubar'],
+ }),
+ commandTool({
+ slug: 'LIST_PERMISSIONS',
+ name: 'List Peekaboo permission status',
+ description: 'List the same permission state exposed by `peekaboo list permissions`.',
+ inputParams: baseInput,
+ args: () => ['list', 'permissions'],
+ }),
+ commandTool({
+ slug: 'TOOLS',
+ name: 'List Peekaboo tool catalog',
+ description: 'Return Peekaboo native/MCP tool catalog for discovery and auditing.',
+ inputParams: baseInput.extend({ noSort: z.boolean().optional() }),
+ args: input => {
+ const args = ['tools'];
+ addBooleanFlag(args, 'no-sort', input.noSort);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'SEE',
+ name: 'Capture annotated UI snapshot',
+ description:
+ 'Capture UI accessibility metadata and optional annotated screenshot for automation.',
+ inputParams: baseInput.extend({
+ app: z.string().optional(),
+ pid: z.number().int().positive().optional(),
+ windowTitle: z.string().optional(),
+ mode: z.enum(['screen', 'window', 'frontmost']).optional(),
+ path: z.string().optional(),
+ captureEngine: z.enum(['auto', 'classic', 'cg', 'modern', 'sckit']).optional(),
+ screenIndex: z.number().int().nonnegative().optional(),
+ analyze: z.string().optional(),
+ annotate: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['see'];
+ addOption(args, 'app', input.app);
+ addOption(args, 'pid', input.pid);
+ addOption(args, 'window-title', input.windowTitle);
+ addOption(args, 'mode', input.mode);
+ addOption(args, 'path', input.path);
+ addOption(args, 'capture-engine', input.captureEngine);
+ addOption(args, 'screen-index', input.screenIndex);
+ addOption(args, 'analyze', input.analyze);
+ addBooleanFlag(args, 'annotate', input.annotate);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'IMAGE',
+ name: 'Capture raw screenshot',
+ description: 'Capture a screen/window/frontmost image and optionally save or analyze it.',
+ inputParams: baseInput.extend({
+ app: z.string().optional(),
+ pid: z.number().int().positive().optional(),
+ path: z.string().optional(),
+ mode: z.enum(['auto', 'screen', 'window', 'frontmost']).optional(),
+ windowTitle: z.string().optional(),
+ windowIndex: z.number().int().nonnegative().optional(),
+ screenIndex: z.number().int().nonnegative().optional(),
+ format: z.enum(['png', 'jpg']).optional(),
+ captureFocus: z.enum(['auto', 'background', 'foreground']).optional(),
+ analyze: z.string().optional(),
+ retina: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['image'];
+ addOption(args, 'app', input.app);
+ addOption(args, 'pid', input.pid);
+ addOption(args, 'path', input.path);
+ addOption(args, 'mode', input.mode);
+ addOption(args, 'window-title', input.windowTitle);
+ addOption(args, 'window-index', input.windowIndex);
+ addOption(args, 'screen-index', input.screenIndex);
+ addOption(args, 'format', input.format);
+ addOption(args, 'capture-focus', input.captureFocus);
+ addOption(args, 'analyze', input.analyze);
+ addBooleanFlag(args, 'retina', input.retina);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'CLICK',
+ name: 'Click UI element or coordinates',
+ description: 'Click by fuzzy query, Peekaboo element id, or x,y coordinates.',
+ inputParams: baseInput.extend({
+ query: z.string().optional(),
+ session: z.string().optional(),
+ on: z.string().optional().describe('Element id from SEE.'),
+ id: z.string().optional().describe('Alias for on.'),
+ app: z.string().optional(),
+ coords: z.string().optional().describe('Coordinates as x,y.'),
+ waitFor: z.number().int().positive().optional(),
+ double: z.boolean().optional(),
+ right: z.boolean().optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['click'];
+ if (input.query) args.push(input.query);
+ addOption(args, 'session', input.session);
+ addOption(args, 'on', input.on);
+ addOption(args, 'id', input.id);
+ addOption(args, 'app', input.app);
+ addOption(args, 'coords', input.coords);
+ addOption(args, 'wait-for', input.waitFor);
+ addBooleanFlag(args, 'double', input.double);
+ addBooleanFlag(args, 'right', input.right);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'TYPE',
+ name: 'Type text or keyboard input',
+ description: 'Type text, clear fields, and append return/tab/escape/delete key actions.',
+ inputParams: baseInput.extend({
+ text: z.string().optional(),
+ session: z.string().optional(),
+ delay: z.number().int().nonnegative().optional(),
+ profile: z.enum(['human', 'linear']).optional(),
+ wpm: z.number().int().min(80).max(220).optional(),
+ tab: z.number().int().positive().optional(),
+ app: z.string().optional(),
+ return: z.boolean().optional(),
+ escape: z.boolean().optional(),
+ delete: z.boolean().optional(),
+ clear: z.boolean().optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['type'];
+ if (input.text) args.push(input.text);
+ addOption(args, 'session', input.session);
+ addOption(args, 'delay', input.delay);
+ addOption(args, 'profile', input.profile);
+ addOption(args, 'wpm', input.wpm);
+ addOption(args, 'tab', input.tab);
+ addOption(args, 'app', input.app);
+ addBooleanFlag(args, 'return', input.return);
+ addBooleanFlag(args, 'escape', input.escape);
+ addBooleanFlag(args, 'delete', input.delete);
+ addBooleanFlag(args, 'clear', input.clear);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'PRESS',
+ name: 'Press special keys',
+ description: 'Press one or more special keys such as return, tab, arrows, or function keys.',
+ inputParams: baseInput.extend({
+ keys: z.array(z.string().min(1)).min(1),
+ count: z.number().int().positive().optional(),
+ delay: z.number().int().nonnegative().optional(),
+ hold: z.number().int().nonnegative().optional(),
+ session: z.string().optional(),
+ app: z.string().optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['press', ...input.keys];
+ addOption(args, 'count', input.count);
+ addOption(args, 'delay', input.delay);
+ addOption(args, 'hold', input.hold);
+ addOption(args, 'session', input.session);
+ addOption(args, 'app', input.app);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'HOTKEY',
+ name: 'Press key combination',
+ description: 'Press modifier combos such as cmd,c or cmd,shift,t.',
+ inputParams: baseInput.extend({
+ keys: z.string().min(1).describe('Comma- or space-separated key combo.'),
+ holdDuration: z.number().int().nonnegative().optional(),
+ app: z.string().optional(),
+ snapshot: z.string().optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['hotkey', input.keys];
+ addOption(args, 'hold-duration', input.holdDuration);
+ addOption(args, 'app', input.app);
+ addOption(args, 'snapshot', input.snapshot);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'SCROLL',
+ name: 'Scroll UI',
+ description: 'Scroll up, down, left, or right at pointer position or a captured element.',
+ inputParams: baseInput.extend({
+ direction: z.enum(['up', 'down', 'left', 'right']),
+ amount: z.number().int().positive().optional(),
+ on: z.string().optional(),
+ snapshot: z.string().optional(),
+ app: z.string().optional(),
+ delay: z.number().int().nonnegative().optional(),
+ smooth: z.boolean().optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['scroll'];
+ addOption(args, 'direction', input.direction);
+ addOption(args, 'amount', input.amount);
+ addOption(args, 'on', input.on);
+ addOption(args, 'snapshot', input.snapshot);
+ addOption(args, 'app', input.app);
+ addOption(args, 'delay', input.delay);
+ addBooleanFlag(args, 'smooth', input.smooth);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'MOVE',
+ name: 'Move cursor',
+ description: 'Move cursor to coordinates, element id/query, or screen center.',
+ inputParams: baseInput.extend({
+ coords: z.string().optional().describe('Coordinates as x,y.'),
+ id: z.string().optional(),
+ to: z.string().optional().describe('Fuzzy element query.'),
+ center: z.boolean().optional(),
+ snapshot: z.string().optional(),
+ app: z.string().optional(),
+ smooth: z.boolean().optional(),
+ duration: z.number().int().nonnegative().optional(),
+ steps: z.number().int().positive().optional(),
+ profile: z.enum(['linear', 'human']).optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['move'];
+ if (input.coords) args.push(input.coords);
+ addOption(args, 'id', input.id);
+ addOption(args, 'to', input.to);
+ addBooleanFlag(args, 'center', input.center);
+ addOption(args, 'snapshot', input.snapshot);
+ addOption(args, 'app', input.app);
+ addBooleanFlag(args, 'smooth', input.smooth);
+ addOption(args, 'duration', input.duration);
+ addOption(args, 'steps', input.steps);
+ addOption(args, 'profile', input.profile);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'DRAG',
+ name: 'Drag and drop',
+ description: 'Drag from an element/coordinate to another element/coordinate or app.',
+ inputParams: baseInput.extend({
+ from: z.string().optional(),
+ fromCoords: z.string().optional().describe('Start coordinates as x,y.'),
+ to: z.string().optional(),
+ toCoords: z.string().optional().describe('End coordinates as x,y.'),
+ toApp: z.string().optional(),
+ snapshot: z.string().optional(),
+ app: z.string().optional(),
+ duration: z.number().int().nonnegative().optional(),
+ steps: z.number().int().positive().optional(),
+ modifiers: z.string().optional().describe('Comma-separated modifiers such as cmd,shift.'),
+ profile: z.enum(['linear', 'human']).optional(),
+ ...focusInput,
+ }),
+ args: input => {
+ const args = ['drag'];
+ addOption(args, 'from', input.from);
+ addOption(args, 'from-coords', input.fromCoords);
+ addOption(args, 'to', input.to);
+ addOption(args, 'to-coords', input.toCoords);
+ addOption(args, 'to-app', input.toApp);
+ addOption(args, 'snapshot', input.snapshot);
+ addOption(args, 'app', input.app);
+ addOption(args, 'duration', input.duration);
+ addOption(args, 'steps', input.steps);
+ addOption(args, 'modifiers', input.modifiers);
+ addOption(args, 'profile', input.profile);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'APP_LAUNCH',
+ name: 'Launch macOS app',
+ description: 'Launch an app by name/path or bundle id and optionally open documents/URLs.',
+ inputParams: baseInput.extend({
+ app: z.string().optional(),
+ bundleId: z.string().optional(),
+ open: z.array(z.string()).optional(),
+ waitUntilReady: z.boolean().optional(),
+ noFocus: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['app', 'launch'];
+ if (input.app) args.push(input.app);
+ addOption(args, 'bundle-id', input.bundleId);
+ addRepeated(args, 'open', input.open);
+ addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
+ addBooleanFlag(args, 'no-focus', input.noFocus);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'APP_QUIT',
+ name: 'Quit macOS app',
+ description: 'Quit one target app or all regular apps with exclusions.',
+ inputParams: baseInput.extend({
+ app: z.string().optional(),
+ pid: z.number().int().positive().optional(),
+ all: z.boolean().optional(),
+ except: z.string().optional().describe('Comma-separated app exclusions when all=true.'),
+ force: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['app', 'quit'];
+ addOption(args, 'app', input.app);
+ addOption(args, 'pid', input.pid);
+ addBooleanFlag(args, 'all', input.all);
+ addOption(args, 'except', input.except);
+ addBooleanFlag(args, 'force', input.force);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'APP_SWITCH',
+ name: 'Switch macOS app',
+ description: 'Activate a specific app or cycle with Cmd+Tab behavior.',
+ inputParams: baseInput.extend({ to: z.string().optional(), cycle: z.boolean().optional() }),
+ args: input => {
+ const args = ['app', 'switch'];
+ addOption(args, 'to', input.to);
+ addBooleanFlag(args, 'cycle', input.cycle);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'WINDOW_FOCUS',
+ name: 'Focus macOS window',
+ description: 'Bring a target app/window to foreground with optional Space handling.',
+ inputParams: baseInput.extend({ ...targetInput, ...focusInput }),
+ args: input => {
+ const args = ['window', 'focus'];
+ addTargetOptions(args, input);
+ addFocusOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'WINDOW_MOVE',
+ name: 'Move macOS window',
+ description: 'Move a target window to a new x,y origin.',
+ inputParams: baseInput.extend({ ...targetInput, x: z.number(), y: z.number() }),
+ args: input => {
+ const args = ['window', 'move'];
+ addTargetOptions(args, input);
+ addOption(args, 'x', input.x);
+ addOption(args, 'y', input.y);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'WINDOW_RESIZE',
+ name: 'Resize macOS window',
+ description: 'Resize a target window while keeping its origin.',
+ inputParams: baseInput.extend({ ...targetInput, width: z.number(), height: z.number() }),
+ args: input => {
+ const args = ['window', 'resize'];
+ addTargetOptions(args, input);
+ addOption(args, 'width', input.width);
+ addOption(args, 'height', input.height);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'WINDOW_SET_BOUNDS',
+ name: 'Set macOS window bounds',
+ description: 'Set target window origin and size in one operation.',
+ inputParams: baseInput.extend({
+ ...targetInput,
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ }),
+ args: input => {
+ const args = ['window', 'set-bounds'];
+ addTargetOptions(args, input);
+ addOption(args, 'x', input.x);
+ addOption(args, 'y', input.y);
+ addOption(args, 'width', input.width);
+ addOption(args, 'height', input.height);
+ return args;
+ },
+ }),
+ ...(['close', 'minimize', 'maximize'] as const).map(action =>
+ commandTool({
+ slug: `WINDOW_${action.toUpperCase()}`,
+ name: `${action[0]?.toUpperCase()}${action.slice(1)} macOS window`,
+ description: `${action[0]?.toUpperCase()}${action.slice(1)} a target macOS window.`,
+ inputParams: baseInput.extend(targetInput),
+ args: input => {
+ const args = ['window', action];
+ addTargetOptions(args, input);
+ return args;
+ },
+ })
+ ),
+ commandTool({
+ slug: 'MENU_LIST',
+ name: 'List app menus',
+ description: 'List menu tree for a target app.',
+ inputParams: baseInput.extend({ ...targetInput, includeDisabled: z.boolean().optional() }),
+ args: input => {
+ const args = ['menu', 'list'];
+ addTargetOptions(args, input);
+ addBooleanFlag(args, 'include-disabled', input.includeDisabled);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'MENU_CLICK',
+ name: 'Click app menu item',
+ description: 'Click an application menu item by item name or path such as File > Save.',
+ inputParams: baseInput.extend({
+ ...targetInput,
+ ...focusInput,
+ item: z.string().optional(),
+ path: z.string().optional(),
+ }),
+ args: input => {
+ const args = ['menu', 'click'];
+ addTargetOptions(args, input);
+ addFocusOptions(args, input);
+ addOption(args, 'item', input.item);
+ addOption(args, 'path', input.path);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'MENU_LIST_ALL',
+ name: 'List frontmost menus and menu extras',
+ description: 'Snapshot frontmost app menus and system menu extras.',
+ inputParams: baseInput.extend({
+ includeDisabled: z.boolean().optional(),
+ includeFrames: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['menu', 'list-all'];
+ addBooleanFlag(args, 'include-disabled', input.includeDisabled);
+ addBooleanFlag(args, 'include-frames', input.includeFrames);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'CLIPBOARD',
+ name: 'Read or write macOS clipboard',
+ description: 'Get, set, clear, save, restore, or load macOS clipboard contents.',
+ inputParams: baseInput.extend({
+ action: z.enum(['get', 'set', 'clear', 'save', 'restore', 'load']),
+ text: z.string().optional(),
+ filePath: z.string().optional(),
+ imagePath: z.string().optional(),
+ dataBase64: z.string().optional(),
+ uti: z.string().optional(),
+ prefer: z.string().optional(),
+ output: z.string().optional(),
+ slot: z.string().optional(),
+ alsoText: z.string().optional(),
+ allowLarge: z.boolean().optional(),
+ verify: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['clipboard'];
+ addOption(args, 'action', input.action);
+ addOption(args, 'text', input.text);
+ addOption(args, 'file-path', input.filePath);
+ addOption(args, 'image-path', input.imagePath);
+ addOption(args, 'data-base64', input.dataBase64);
+ addOption(args, 'uti', input.uti);
+ addOption(args, 'prefer', input.prefer);
+ addOption(args, 'output', input.output);
+ addOption(args, 'slot', input.slot);
+ addOption(args, 'also-text', input.alsoText);
+ addBooleanFlag(args, 'allow-large', input.allowLarge);
+ addBooleanFlag(args, 'verify', input.verify);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'APP_HIDE',
+ name: 'Hide macOS app',
+ description: 'Hide a target application.',
+ inputParams: baseInput.extend({ app: z.string().min(1) }),
+ args: input => ['app', 'hide', '--app', input.app],
+ }),
+ commandTool({
+ slug: 'APP_UNHIDE',
+ name: 'Unhide macOS app',
+ description: 'Show/unhide a target application.',
+ inputParams: baseInput.extend({ app: z.string().min(1) }),
+ args: input => ['app', 'unhide', '--app', input.app],
+ }),
+ commandTool({
+ slug: 'APP_RELAUNCH',
+ name: 'Relaunch macOS app',
+ description: 'Quit and relaunch a target application.',
+ inputParams: baseInput.extend({
+ app: z.string().min(1),
+ wait: z.number().nonnegative().optional(),
+ force: z.boolean().optional(),
+ waitUntilReady: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['app', 'relaunch', input.app];
+ addOption(args, 'wait', input.wait);
+ addBooleanFlag(args, 'force', input.force);
+ addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'DIALOG',
+ name: 'Interact with system dialog',
+ description: 'List, click, input into, select files for, or dismiss system dialogs.',
+ inputParams: baseInput.extend({
+ action: z.enum(['list', 'click', 'input', 'file', 'dismiss']),
+ button: z.string().optional(),
+ text: z.string().optional(),
+ field: z.string().optional(),
+ path: z.string().optional(),
+ name: z.string().optional(),
+ select: z.string().optional(),
+ force: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['dialog', input.action];
+ addOption(args, 'button', input.button);
+ addOption(args, 'text', input.text);
+ addOption(args, 'field', input.field);
+ addOption(args, 'path', input.path);
+ addOption(args, 'name', input.name);
+ addOption(args, 'select', input.select);
+ addBooleanFlag(args, 'force', input.force);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'DOCK',
+ name: 'Interact with macOS Dock',
+ description:
+ 'List Dock items, launch apps from Dock, right-click items, or show/hide the Dock.',
+ inputParams: baseInput.extend({
+ action: z.enum(['list', 'launch', 'right-click', 'hide', 'show']),
+ app: z.string().optional(),
+ select: z.string().optional(),
+ }),
+ args: input => {
+ const args = ['dock', input.action];
+ if (input.action === 'launch' && input.app) args.push(input.app);
+ if (input.action !== 'launch') addOption(args, 'app', input.app);
+ addOption(args, 'select', input.select);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'SPACE',
+ name: 'Manage macOS Spaces',
+ description: 'List Spaces, switch Spaces, or move windows between Spaces.',
+ inputParams: baseInput.extend({
+ action: z.enum(['list', 'switch', 'move-window']),
+ to: z.number().int().positive().optional(),
+ toCurrent: z.boolean().optional(),
+ ...targetInput,
+ }),
+ args: input => {
+ const args = ['space', input.action];
+ addOption(args, 'to', input.to);
+ addBooleanFlag(args, 'to-current', input.toCurrent);
+ addTargetOptions(args, input);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'MENUBAR',
+ name: 'Interact with macOS menu bar items',
+ description: 'List or click status/menu-bar items by name or index.',
+ inputParams: baseInput.extend({
+ action: z.enum(['list', 'click']),
+ itemName: z.string().optional(),
+ index: z.number().int().nonnegative().optional(),
+ includeRawDebug: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['menubar', input.action];
+ if (input.itemName) args.push(input.itemName);
+ addOption(args, 'index', input.index);
+ addBooleanFlag(args, 'include-raw-debug', input.includeRawDebug);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'OPEN',
+ name: 'Open URL or file',
+ description: 'Open a URL or local file with its default or specified application.',
+ inputParams: baseInput.extend({
+ target: z.string().min(1),
+ app: z.string().optional(),
+ bundleId: z.string().optional(),
+ waitUntilReady: z.boolean().optional(),
+ noFocus: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['open', input.target];
+ addOption(args, 'app', input.app);
+ addOption(args, 'bundle-id', input.bundleId);
+ addBooleanFlag(args, 'wait-until-ready', input.waitUntilReady);
+ addBooleanFlag(args, 'no-focus', input.noFocus);
+ return args;
+ },
+ }),
+ commandTool({
+ slug: 'SLEEP',
+ name: 'Sleep in Peekaboo flow',
+ description: 'Pause for a number of milliseconds between GUI actions.',
+ inputParams: baseInput.extend({ duration: z.number().int().nonnegative() }),
+ args: input => ['sleep', String(input.duration)],
+ }),
+ commandTool({
+ slug: 'CLEAN',
+ name: 'Clean Peekaboo caches',
+ description: 'Prune Peekaboo session cache and temporary files.',
+ inputParams: baseInput.extend({
+ allSessions: z.boolean().optional(),
+ olderThan: z
+ .number()
+ .positive()
+ .optional()
+ .describe('Remove sessions older than this many hours.'),
+ session: z.string().optional(),
+ dryRun: z.boolean().optional(),
+ }),
+ args: input => {
+ const args = ['clean'];
+ addBooleanFlag(args, 'all-sessions', input.allSessions);
+ addOption(args, 'older-than', input.olderThan);
+ addOption(args, 'session', input.session);
+ addBooleanFlag(args, 'dry-run', input.dryRun);
+ return args;
+ },
+ }),
+ ],
+};
diff --git a/ts/packages/cli-local-tools/src/types.ts b/ts/packages/cli-local-tools/src/types.ts
new file mode 100644
index 000000000..848866eb6
--- /dev/null
+++ b/ts/packages/cli-local-tools/src/types.ts
@@ -0,0 +1,202 @@
+import type { z } from 'zod/v3';
+
+export type LocalCliPlatform =
+ | 'all'
+ | 'darwin'
+ | 'linux'
+ | 'win32'
+ | 'darwin-arm64'
+ | 'darwin-x64'
+ | 'linux-arm64'
+ | 'linux-x64'
+ | 'win32-arm64'
+ | 'win32-x64';
+
+export type LocalExecutionResult = Record<string, unknown>;
+
+export interface LocalBundledBinaryTarget {
+ /** Platform selectors that can use this artifact. */
+ readonly platforms: ReadonlyArray<LocalCliPlatform>;
+ /** Path relative to the local-tools bundle root. */
+ readonly path: string;
+ /** Mark executable before running. Defaults to true for command binaries. */
+ readonly executable?: boolean;
+}
+
+export interface LocalBundledBinaryDeclaration {
+ /** Stable id used by command/FFI declarations, e.g. `peekaboo-cli`. */
+ readonly id: string;
+ readonly description?: string;
+ readonly targets: ReadonlyArray<LocalBundledBinaryTarget>;
+}
+
+export interface LocalBundledBinaryRef {
+ readonly bundledBinary: string;
+ /** PATH command or absolute path to use when the bundled artifact is absent. */
+ readonly fallbackCommand?: string;
+}
+
+export interface LocalExecutionContext {
+ readonly toolkit: LocalToolkitDeclaration;
+ readonly tool: LocalToolDeclaration;
+ readonly finalSlug: string;
+ readonly platform: LocalCliPlatform;
+}
+
+export interface LocalCommandInvocation {
+ readonly command: string;
+ readonly args?: ReadonlyArray<string>;
+ readonly env?: Record<string, string | undefined>;
+ readonly cwd?: string;
+ readonly stdin?: string;
+ readonly timeoutMs?: number;
+}
+
+export type LocalCommandValue =
+ | string
+ | LocalBundledBinaryRef
+ | LocalCommandInvocation
+ | (LocalCommandInvocation & LocalBundledBinaryRef);
+
+export interface LocalCommandExecution {
+ readonly kind: 'command';
+ readonly command: LocalCommandValue | ((input: Record<string, unknown>) => LocalCommandValue);
+ readonly args?:
+ | ReadonlyArray<string>
+ | ((input: Record<string, unknown>) => ReadonlyArray<string>);
+ readonly env?:
+ | Record<string, string | undefined>
+ | ((input: Record<string, unknown>) => Record<string, string | undefined>);
+ readonly cwd?: string | ((input: Record<string, unknown>) => string | undefined);
+ readonly stdin?: string | ((input: Record<string, unknown>) => string | undefined);
+ readonly timeoutMs?: number;
+ /** Parse stdout as JSON when possible. Defaults to false. */
+ readonly parseJson?: boolean;
+}
+
+export interface LocalNativeExecution {
+ readonly kind: 'native';
+ /** Optional prerequisite command used by `composio local-tools doctor` for native wrappers. */
+ readonly readiness?: LocalCommandInvocation;
+ readonly execute: (
+ input: Record<string, unknown>,
+ context: LocalExecutionContext
+ ) => Promise<LocalExecutionResult> | LocalExecutionResult;
+}
+
+export interface LocalMcpServerSpec {
+ readonly command: string;
+ readonly args?: ReadonlyArray<string>;
+ readonly env?: Record<string, string | undefined>;
+ readonly cwd?: string;
+}
+
+export interface LocalMcpExecution {
+ readonly kind: 'mcp';
+ readonly server: LocalMcpServerSpec | ((input: Record<string, unknown>) => LocalMcpServerSpec);
+ /** Tool name to call. If omitted, the wrapper returns `listTools()`. */
+ readonly toolName?: string | ((input: Record<string, unknown>) => string | undefined);
+ readonly arguments?:
+ | Record<string, unknown>
+ | ((input: Record<string, unknown>) => Record<string, unknown>);
+}
+
+export type LocalFfiType =
+ | 'char'
+ | 'uchar'
+ | 'i8'
+ | 'u8'
+ | 'i16'
+ | 'u16'
+ | 'i32'
+ | 'u32'
+ | 'i64'
+ | 'u64'
+ | 'f32'
+ | 'f64'
+ | 'bool'
+ | 'ptr'
+ | 'cstring'
+ | 'void';
+
+export interface LocalFfiSymbolDeclaration {
+ readonly args: ReadonlyArray<LocalFfiType>;
+ readonly returns: LocalFfiType;
+}
+
+export interface LocalFfiLibraryHandle {
+ readonly path: string;
+ readonly symbols: Record<string, (...args: ReadonlyArray<unknown>) => unknown>;
+}
+
+export interface LocalFfiExecution {
+ readonly kind: 'ffi';
+ /** Absolute library path or bundled binary reference for a .dylib/.so/.dll. */
+ readonly library: string | LocalBundledBinaryRef;
+ readonly symbols: Record<string, LocalFfiSymbolDeclaration>;
+ readonly execute: (
+ input: Record<string, unknown>,
+ context: LocalExecutionContext,
+ library: LocalFfiLibraryHandle
+ ) => Promise<LocalExecutionResult> | LocalExecutionResult;
+}
+
+export type LocalToolExecution =
+ | LocalCommandExecution
+ | LocalNativeExecution
+ | LocalMcpExecution
+ | LocalFfiExecution;
+
+export interface LocalToolDeclaration<TInput extends z.ZodTypeAny = z.ZodTypeAny> {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly inputParams: TInput;
+ readonly outputParams?: z.ZodTypeAny;
+ readonly platforms: ReadonlyArray<LocalCliPlatform>;
+ readonly execution: LocalToolExecution;
+ readonly tags?: ReadonlyArray<string>;
+}
+
+export interface LocalToolkitDeclaration {
+ readonly slug: string;
+ readonly name: string;
+ readonly description: string;
+ readonly platforms: ReadonlyArray<LocalCliPlatform>;
+ readonly tools: ReadonlyArray<LocalToolDeclaration>;
+ readonly bundledBinaries?: ReadonlyArray<LocalBundledBinaryDeclaration>;
+ readonly source?: {
+ readonly type: 'cli' | 'mcp' | 'native' | 'ffi';
+ readonly package?: string;
+ readonly repository?: string;
+ readonly command?: string;
+ };
+ readonly setup?: {
+ readonly install?: string;
+ readonly commandOverrides?: ReadonlyArray<string>;
+ readonly notes?: ReadonlyArray<string>;
+ };
+}
+
+export interface LocalToolResolution {
+ readonly toolkit: LocalToolkitDeclaration;
+ readonly tool: LocalToolDeclaration;
+ readonly finalSlug: string;
+ readonly supported: boolean;
+ readonly currentPlatform: LocalCliPlatform;
+}
+
+export type LocalToolRouterExperimentalPayload = {
+ custom_toolkits?: Array<{
+ slug: string;
+ name: string;
+ description: string;
+ tools: Array<{
+ slug: string;
+ name: string;
+ description: string;
+ input_schema: Record<string, unknown>;
+ output_schema?: Record<string, unknown>;
+ }>;
+ }>;
+};
diff --git a/ts/packages/cli-local-tools/tsconfig.json b/ts/packages/cli-local-tools/tsconfig.json
new file mode 100644
index 000000000..8024d90e7
--- /dev/null
+++ b/ts/packages/cli-local-tools/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.src.json",
+ "compilerOptions": {
+ "composite": true,
+ "rootDir": "./src"
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["src/**/*.test.ts", "dist"]
+}
diff --git a/ts/packages/cli-local-tools/tsconfig.options.json b/ts/packages/cli-local-tools/tsconfig.options.json
new file mode 100644
index 000000000..25749a04b
--- /dev/null
+++ b/ts/packages/cli-local-tools/tsconfig.options.json
@@ -0,0 +1,23 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "../../../tsconfig.base.json",
+ "compilerOptions": {
+ "declaration": true,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "moduleResolution": "bundler",
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "verbatimModuleSyntax": true,
+ "pretty": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "types": ["node"]
+ },
+ "include": ["src"],
+ "exclude": ["**/dist", "test/__fixtures__/**"]
+}
diff --git a/ts/packages/cli-local-tools/tsconfig.src.json b/ts/packages/cli-local-tools/tsconfig.src.json
new file mode 100644
index 000000000..d8d650fbb
--- /dev/null
+++ b/ts/packages/cli-local-tools/tsconfig.src.json
@@ -0,0 +1,13 @@
+{
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "extends": "./tsconfig.options.json",
+ "compilerOptions": {
+ "outDir": "./dist",
+ "rootDir": ".",
+ "paths": {
+ "src/*": ["./src/*"]
+ }
+ },
+ "include": ["src"],
+ "exclude": ["src/**/*.test.ts"]
+}
diff --git a/ts/packages/cli-local-tools/tsdown.config.ts b/ts/packages/cli-local-tools/tsdown.config.ts
new file mode 100644
index 000000000..a2d9be2a3
--- /dev/null
+++ b/ts/packages/cli-local-tools/tsdown.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'tsdown';
+import { baseConfig } from '../../../tsdown.config.base.ts';
+
+export default defineConfig({
+ ...baseConfig,
+ tsconfig: 'tsconfig.src.json',
+ external: [/^bun:/],
+});
diff --git a/ts/packages/cli-local-tools/vendor/peekaboo b/ts/packages/cli-local-tools/vendor/peekaboo
new file mode 160000
index 000000000..31e66e8d0
--- /dev/null
+++ b/ts/packages/cli-local-tools/vendor/peekaboo
@@ -0,0 +1 @@
+Subproject commit 31e66e8d02656141d18f60bf3b46b24c2b9bc785
diff --git a/ts/packages/cli-local-tools/vendor/platform-imessage b/ts/packages/cli-local-tools/vendor/platform-imessage
new file mode 160000
index 000000000..364445a1b
--- /dev/null
+++ b/ts/packages/cli-local-tools/vendor/platform-imessage
@@ -0,0 +1 @@
+Subproject commit 364445a1b3089ad9fe293d5951efe160c5677c42
diff --git a/ts/packages/cli-local-tools/vitest.config.ts b/ts/packages/cli-local-tools/vitest.config.ts
new file mode 100644
index 000000000..da1d74e57
--- /dev/null
+++ b/ts/packages/cli-local-tools/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ include: ['src/**/*.test.ts'],
+ exclude: ['vendor/**', 'dist/**', 'node_modules/**'],
+ },
+});
diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.json
index 290ba0d05..aff7507dc 100644
--- a/ts/packages/cli/package.json
+++ b/ts/packages/cli/package.json
@@ -37,7 +37,7 @@
"table:metrics": "bun run ./scripts/optimize-metrics-table.ts",
"mock": "bun run ./scripts/copy-mocks-from-cache.ts",
"prebuild": "pnpm run typecheck",
- "build": "pnpm exec tsdown",
+ "build": "pnpm exec tsdown && bun run ./scripts/copy-local-tools-assets.ts ./dist",
"bin": "./dist/composio",
"test": "pnpm run validate:skills && vitest run",
"prepublishOnly": "pnpm run build && pnpm run build:binary",
@@ -78,6 +78,7 @@
"@clack/core": "catalog:",
"@clack/prompts": "catalog:",
"@composio/cli-keyring": "workspace:*",
+ "@composio/cli-local-tools": "workspace:*",
"@composio/client": "catalog:",
"@composio/core": "workspace:*",
"@composio/json-schema-to-zod": "workspace:*",
diff --git a/ts/packages/cli/scripts/_shared.ts b/ts/packages/cli/scripts/_shared.ts
index 87c4c8d3e..99f743598 100644
--- a/ts/packages/cli/scripts/_shared.ts
+++ b/ts/packages/cli/scripts/_shared.ts
@@ -49,6 +49,34 @@ const copyBundledAcpAdapters = async (outputDir: string): Promise<void> => {
await copyDirectoryRecursive(acpAdaptersCacheDir, acpOutputDir);
};
+export const LOCAL_TOOLS_BINARY_ASSET_DIRNAME = 'local-tools-binaries';
+
+const localToolsBinaryAssetsSourceDir = (): string =>
+ path.resolve(process.cwd(), '../cli-local-tools', LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
+
+const copyLocalToolBinaryAssetsDirectory = async (outputDir: string): Promise<boolean> => {
+ const sourceDir = localToolsBinaryAssetsSourceDir();
+ const sourceExists = await stat(sourceDir)
+ .then(stats => stats.isDirectory())
+ .catch(() => false);
+ if (!sourceExists) return false;
+
+ const outputAssetDir = path.join(outputDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
+ await rm(outputAssetDir, { force: true, recursive: true });
+ await copyDirectoryRecursive(sourceDir, outputAssetDir);
+ return true;
+};
+
+export const copyLocalToolBinaryAssets = (outputDir: string) =>
+ Effect.gen(function* () {
+ const copied = yield* Effect.tryPromise(() => copyLocalToolBinaryAssetsDirectory(outputDir));
+ if (copied) {
+ yield* Effect.logDebug(
+ `Copied local tool binary assets into ${path.join(outputDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME)}`
+ );
+ }
+ });
+
const isAllowedRuntimeSpecifier = (specifier: string): boolean =>
specifier.startsWith('.') ||
specifier.startsWith('/') ||
diff --git a/ts/packages/cli/scripts/build-all-binaries.ts b/ts/packages/cli/scripts/build-all-binaries.ts
index c073e610c..d7e4e10e5 100644
--- a/ts/packages/cli/scripts/build-all-binaries.ts
+++ b/ts/packages/cli/scripts/build-all-binaries.ts
@@ -16,7 +16,7 @@ import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { buildCompanionModules, teardown } from './_shared';
+import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
/**
* All cross-compilation targets and their artifact names.
@@ -89,6 +89,8 @@ export function buildAllBinaries() {
yield* Console.log(`\nBuilding run companion modules in ${companionOutputDir}...`);
yield* buildCompanionModules(companionOutputDir);
+ yield* copyLocalToolBinaryAssets('./dist/binaries');
+
yield* Console.log(`\nAll ${TARGETS.length} binaries built successfully.`);
});
}
diff --git a/ts/packages/cli/scripts/build-binary-cross.ts b/ts/packages/cli/scripts/build-binary-cross.ts
index 9404099da..d506d81cf 100644
--- a/ts/packages/cli/scripts/build-binary-cross.ts
+++ b/ts/packages/cli/scripts/build-binary-cross.ts
@@ -18,7 +18,7 @@ import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { buildCompanionModules, teardown } from './_shared';
+import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
/**
* Maps Bun cross-compilation targets to Composio artifact names.
@@ -108,6 +108,7 @@ export function buildBinaryCross() {
const companionOutputDir = './dist/binaries/companions';
yield* buildCompanionModules(companionOutputDir);
+ yield* copyLocalToolBinaryAssets('./dist/binaries');
yield* Console.log(`Binary cross-compiled: ${outfile}`);
});
diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.ts
index b6398217d..25e7f0a57 100644
--- a/ts/packages/cli/scripts/build-binary.ts
+++ b/ts/packages/cli/scripts/build-binary.ts
@@ -2,7 +2,7 @@ import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Stream, Logger, Layer, LogLevel } from 'effect';
import { Command } from '@effect/platform';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { buildCompanionModules, teardown } from './_shared';
+import { buildCompanionModules, copyLocalToolBinaryAssets, teardown } from './_shared';
/**
* Usage: `bun scripts/build-binary.ts`
@@ -79,6 +79,11 @@ export function buildBinary() {
yield* buildCompanionModules('./dist');
yield* Effect.logDebug('', 'Companion modules built successfully');
+
+ // Copy local-tool executable/library assets next to the standalone CLI so
+ // command and FFI local tools can resolve platform-specific bundled binaries
+ // at runtime.
+ yield* copyLocalToolBinaryAssets('./dist');
});
}
diff --git a/ts/packages/cli/scripts/copy-local-tools-assets.ts b/ts/packages/cli/scripts/copy-local-tools-assets.ts
new file mode 100644
index 000000000..1f0c54a4c
--- /dev/null
+++ b/ts/packages/cli/scripts/copy-local-tools-assets.ts
@@ -0,0 +1,14 @@
+#!/usr/bin/env bun
+
+import process from 'node:process';
+import { Effect } from 'effect';
+import { BunContext, BunRuntime } from '@effect/platform-bun';
+import { copyLocalToolBinaryAssets, teardown } from './_shared';
+
+const outputDir = process.argv[2] ?? './dist';
+
+copyLocalToolBinaryAssets(outputDir).pipe(
+ Effect.provide(BunContext.layer),
+ Effect.scoped,
+ BunRuntime.runMain({ teardown })
+);
diff --git a/ts/packages/cli/scripts/package-binaries.ts b/ts/packages/cli/scripts/package-binaries.ts
index 0216fca0d..1bc61aaf3 100644
--- a/ts/packages/cli/scripts/package-binaries.ts
+++ b/ts/packages/cli/scripts/package-binaries.ts
@@ -17,7 +17,7 @@
import process from 'node:process';
import { Config, ConfigProvider, Console, Effect, Logger, Layer, LogLevel } from 'effect';
import { BunContext, BunRuntime } from '@effect/platform-bun';
-import { teardown } from './_shared';
+import { LOCAL_TOOLS_BINARY_ASSET_DIRNAME, teardown } from './_shared';
import { $ } from 'bun';
import { readdir, stat } from 'node:fs/promises';
import path from 'node:path';
@@ -25,6 +25,7 @@ import { collectExpectedRunCompanionAssetRelativePaths } from '../src/services/r
const BINARIES_DIR = './dist/binaries';
const COMPANIONS_DIR = path.join(BINARIES_DIR, 'companions');
+const LOCAL_TOOLS_BINARY_ASSETS_DIR = path.join(BINARIES_DIR, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
/**
* Known binary artifact names (without extension).
@@ -80,6 +81,9 @@ export function packageBinaries() {
await $`mkdir -p ${targetDirectory}`.quiet();
await $`cp ${path.join(COMPANIONS_DIR, relativePath)} ${path.join(nestedDir, relativePath)}`.quiet();
}
+ if (await Bun.file(LOCAL_TOOLS_BINARY_ASSETS_DIR).exists()) {
+ await $`cp -R ${LOCAL_TOOLS_BINARY_ASSETS_DIR} ${path.join(nestedDir, LOCAL_TOOLS_BINARY_ASSET_DIRNAME)}`.quiet();
+ }
const previousCwd = process.cwd();
process.chdir(tempDir);
try {
diff --git a/ts/packages/cli/skills-src/composio-cli/reference-schema.ts b/ts/packages/cli/skills-src/composio-cli/reference-schema.ts
index 82ae46f46..c2598fb4e 100644
--- a/ts/packages/cli/skills-src/composio-cli/reference-schema.ts
+++ b/ts/packages/cli/skills-src/composio-cli/reference-schema.ts
@@ -43,6 +43,7 @@ const TOP_LEVEL_COMMANDS = new Set([
'execute',
'link',
'listen',
+ 'local-tools',
'login',
'logout',
'proxy',
@@ -62,6 +63,10 @@ export const resolveSkillBuildContext = (
CLI_EXPERIMENTAL_FEATURES.LISTEN,
channel
),
+ [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]: isExperimentalFeatureEnabledByDefault(
+ CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
+ channel
+ ),
[CLI_EXPERIMENTAL_FEATURES.MULTI_ACCOUNT]: isExperimentalFeatureEnabledByDefault(
CLI_EXPERIMENTAL_FEATURES.MULTI_ACCOUNT,
channel
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index 603a11ed6..e27f5155d 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -14,6 +14,7 @@ import { runCmd } from './run.cmd';
import { proxyCmd } from './proxy.cmd';
import { artifactsCmd } from './artifacts.cmd';
import { installCmd } from './install.cmd';
+import { localToolsCmd } from './local-tools/local-tools.cmd';
import { generateCmd } from './generate/generate.cmd';
import { buildDevCommand } from './dev.cmd';
import {
@@ -69,6 +70,7 @@ const ROOT_COMMANDS: ReadonlyArray<TaggedValue<Command.Command<any, any, any, an
tagged(proxyCmd),
tagged(artifactsCmd),
tagged(installCmd),
+ experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, localToolsCmd),
tagged(rootToolsCmd),
tagged(rootTriggersCmd),
tagged(rootToolsCmd$Search),
diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts
new file mode 100644
index 000000000..8d44d2d98
--- /dev/null
+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts
@@ -0,0 +1,180 @@
+import { Args, Command, Options } from '@effect/cli';
+import {
+ getLocalToolsMetaPath,
+ isLocalToolkitSlug,
+ resolveLocalTool,
+ updateLocalToolkitMeta,
+ updateLocalToolMeta,
+ type LocalToolMetaEntry,
+} from '@composio/cli-local-tools';
+import { Effect, Option } from 'effect';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { bold, gray } from 'src/ui/colors';
+
+const selector = Args.text({ name: 'selector' }).pipe(
+ Args.withDescription('Local toolkit slug or LOCAL_* tool slug to configure')
+);
+
+const command = Options.text('command').pipe(
+ Options.optional,
+ Options.withDescription('Override the local binary/launcher command')
+);
+
+const disable = Options.boolean('disable').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Disable this local toolkit/tool')
+);
+
+const enable = Options.boolean('enable').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Enable this local toolkit/tool by clearing disabled=false')
+);
+
+const authenticated = Options.boolean('authenticated').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Mark this local toolkit/tool as authenticated in metadata')
+);
+
+const unauthenticated = Options.boolean('unauthenticated').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Mark this local toolkit/tool as unauthenticated in metadata')
+);
+
+const json = Options.boolean('json').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print the updated metadata entry as JSON')
+);
+
+type ConfigureTarget =
+ | {
+ readonly kind: 'toolkit';
+ readonly key: string;
+ readonly label: string;
+ }
+ | {
+ readonly kind: 'tool';
+ readonly key: string;
+ readonly label: string;
+ readonly toolkitSlug: string;
+ };
+
+const resolveTarget = (value: string): ConfigureTarget | null => {
+ const localTool = resolveLocalTool(value, { includeUnsupported: true });
+ if (localTool) {
+ return {
+ kind: 'tool',
+ key: localTool.finalSlug,
+ label: localTool.finalSlug,
+ toolkitSlug: localTool.toolkit.slug,
+ };
+ }
+
+ if (isLocalToolkitSlug(value)) {
+ return {
+ kind: 'toolkit',
+ key: value.toLowerCase(),
+ label: value.toUpperCase(),
+ };
+ }
+
+ return null;
+};
+
+const buildPatch = (params: {
+ readonly command: Option.Option<string>;
+ readonly disable: boolean;
+ readonly enable: boolean;
+ readonly authenticated: boolean;
+ readonly unauthenticated: boolean;
+}): LocalToolMetaEntry | { readonly error: string } => {
+ if (params.disable && params.enable) {
+ return { error: 'Pass only one of --disable or --enable.' };
+ }
+ if (params.authenticated && params.unauthenticated) {
+ return { error: 'Pass only one of --authenticated or --unauthenticated.' };
+ }
+
+ const commandOverride = Option.getOrUndefined(params.command)?.trim();
+ const hasCommandOverride = commandOverride !== undefined && commandOverride.length > 0;
+ const hasChanges =
+ hasCommandOverride ||
+ params.disable ||
+ params.enable ||
+ params.authenticated ||
+ params.unauthenticated;
+ if (!hasChanges) {
+ return {
+ error:
+ 'Nothing to configure. Pass --command, --enable/--disable, or --authenticated/--unauthenticated.',
+ };
+ }
+
+ return {
+ ...(hasCommandOverride ? { installation: { command: commandOverride } } : {}),
+ ...(params.disable ? { disabled: true } : {}),
+ ...(params.enable ? { disabled: false } : {}),
+ ...(params.authenticated ? { authenticated: true } : {}),
+ ...(params.unauthenticated ? { authenticated: false } : {}),
+ };
+};
+
+const formatEntry = (target: ConfigureTarget, entry: LocalToolMetaEntry, metadataPath: string) =>
+ [
+ `${bold('Target:')} ${target.kind} ${target.label}`,
+ `${bold('Path:')} ${metadataPath}`,
+ `${bold('Command:')} ${entry.installation?.command ?? '-'}`,
+ `${bold('Disabled:')} ${entry.disabled === undefined ? '-' : String(entry.disabled)}`,
+ `${bold('Authenticated:')} ${entry.authenticated === undefined ? '-' : String(entry.authenticated)}`,
+ `${gray('Next:')} run \`composio local-tools doctor --toolkits ${target.kind === 'toolkit' ? target.key : target.toolkitSlug}\``,
+ ].join('\n');
+
+export const localToolsCmd$Configure = Command.make(
+ 'configure',
+ { selector, command, disable, enable, authenticated, unauthenticated, json },
+ ({ selector, command, disable, enable, authenticated, unauthenticated, json }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const target = resolveTarget(selector);
+ if (!target) {
+ return yield* Effect.fail(
+ new Error(
+ `Unknown local toolkit/tool "${selector}". Run \`composio local-tools list --all-platforms\` to inspect valid selectors.`
+ )
+ );
+ }
+
+ const patch = buildPatch({ command, disable, enable, authenticated, unauthenticated });
+ if ('error' in patch) {
+ return yield* Effect.fail(new Error(patch.error));
+ }
+
+ const metadata = yield* Effect.tryPromise(() =>
+ target.kind === 'toolkit'
+ ? updateLocalToolkitMeta(target.key, patch)
+ : updateLocalToolMeta(target.key, patch)
+ );
+ const entry =
+ target.kind === 'toolkit' ? metadata.toolkits[target.key]! : metadata.tools[target.key]!;
+ const metadataPath = getLocalToolsMetaPath();
+ const payload = { metadataPath, target, entry };
+
+ if (json) {
+ yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
+ return;
+ }
+
+ yield* ui.log.success(`Updated local ${target.kind} metadata.`);
+ yield* ui.log.message(formatEntry(target, entry, metadataPath));
+ })
+).pipe(
+ Command.withDescription(
+ [
+ 'Configure local toolkit/tool metadata without hand-editing ~/composio/local_tools.json.',
+ '',
+ 'Examples:',
+ ' composio local-tools configure <toolkit> --command /path/to/tool',
+ ' composio local-tools configure LOCAL_EXAMPLE_RUN --disable',
+ ' composio local-tools configure <toolkit> --authenticated --json',
+ ].join('\n')
+ )
+);
diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts
new file mode 100644
index 000000000..6ecca0596
--- /dev/null
+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.doctor.cmd.ts
@@ -0,0 +1,148 @@
+import { Command, Options } from '@effect/cli';
+import {
+ checkLocalToolkitsReadiness,
+ formatSupportedPlatforms,
+ getLocalToolsMetaPath,
+ type LocalReadinessStatus,
+ type LocalToolsReadinessReport,
+} from '@composio/cli-local-tools';
+import { Effect, Option } from 'effect';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { bold, gray, green, red } from 'src/ui/colors';
+import { truncate } from 'src/ui/truncate';
+
+const json = Options.boolean('json').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print readiness report as JSON')
+);
+
+const allPlatforms = Options.boolean('all-platforms').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Include local toolkits that are not supported on this CLI platform')
+);
+
+const strict = Options.boolean('strict').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Exit with an error when any visible local tool is not ready')
+);
+
+const toolkits = Options.text('toolkits').pipe(
+ Options.optional,
+ Options.withDescription('Filter by local toolkit slugs, comma-separated')
+);
+
+const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
+ const raw = Option.getOrUndefined(value);
+ if (!raw?.trim()) return undefined;
+ return raw
+ .split(',')
+ .map(part => part.trim())
+ .filter(Boolean);
+};
+
+const statusIcon = (status: LocalReadinessStatus): string => {
+ switch (status) {
+ case 'ready':
+ return green('✓');
+ case 'unsupported':
+ return gray('○');
+ case 'unknown':
+ return gray('?');
+ default:
+ return red('✗');
+ }
+};
+
+const statusLabel = (status: LocalReadinessStatus): string => {
+ if (status === 'ready') return green(status);
+ if (status === 'unsupported' || status === 'unknown') return gray(status);
+ return red(status);
+};
+
+const hasProblems = (report: LocalToolsReadinessReport): boolean =>
+ report.toolkits.some(toolkit =>
+ toolkit.tools.some(tool => tool.status !== 'ready' && tool.status !== 'unsupported')
+ );
+
+const formatDoctorReport = (report: LocalToolsReadinessReport, metadataPath: string): string => {
+ const lines: string[] = [];
+ lines.push(`${bold('Local tools doctor')} (${report.currentPlatform})`);
+ lines.push(`${gray('Metadata:')} ${metadataPath}`);
+
+ if (report.toolkits.length === 0) {
+ lines.push('No registered local toolkits match this platform/filter.');
+ return lines.join('\n');
+ }
+
+ for (const toolkit of report.toolkits) {
+ lines.push('');
+ lines.push(
+ `${statusIcon(toolkit.status)} ${bold(toolkit.slug)} ${gray(`(${toolkit.name}; ${statusLabel(toolkit.status)}; ${formatSupportedPlatforms(toolkit.platforms)})`)}`
+ );
+ lines.push(` ${gray(truncate(toolkit.description, 96))}`);
+ for (const message of toolkit.messages) {
+ lines.push(` ${gray('note:')} ${message}`);
+ }
+
+ for (const tool of toolkit.tools) {
+ const command = tool.command
+ ? tool.command.found
+ ? `${tool.command.command}${tool.command.path ? gray(` -> ${tool.command.path}`) : ''}`
+ : `${tool.command.command} ${red('(missing)')}`
+ : tool.executionKind;
+ lines.push(
+ ` ${statusIcon(tool.status)} ${tool.finalSlug.padEnd(36)} ${statusLabel(tool.status).padEnd(15)} ${gray(command)}`
+ );
+ for (const message of tool.messages) {
+ lines.push(` ${gray(message)}`);
+ }
+ }
+
+ const hints = [...new Set([...toolkit.hints, ...toolkit.tools.flatMap(tool => tool.hints)])];
+ for (const hint of hints) {
+ lines.push(` ${gray('hint:')} ${hint}`);
+ }
+ }
+
+ return lines.join('\n');
+};
+
+export const localToolsCmd$Doctor = Command.make(
+ 'doctor',
+ { json, allPlatforms, strict, toolkits },
+ ({ json, allPlatforms, strict, toolkits }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const toolkitFilter = parseToolkitFilter(toolkits);
+ const metadataPath = getLocalToolsMetaPath();
+ const report = yield* Effect.tryPromise(() =>
+ checkLocalToolkitsReadiness({
+ includeUnsupported: allPlatforms,
+ toolkits: toolkitFilter,
+ })
+ );
+
+ if (json) {
+ yield* ui.output(JSON.stringify({ metadataPath, ...report }, null, 2), { force: true });
+ } else {
+ yield* ui.log.message(formatDoctorReport(report, metadataPath));
+ }
+
+ if (strict && hasProblems(report)) {
+ return yield* Effect.fail(
+ new Error('One or more local tools are not ready. Run without --strict for setup hints.')
+ );
+ }
+ })
+).pipe(
+ Command.withDescription(
+ [
+ 'Check whether registered local toolkits have the commands and platform support needed to run.',
+ '',
+ 'Examples:',
+ ' composio local-tools doctor',
+ ' composio local-tools doctor --json',
+ ' composio local-tools doctor --toolkits <toolkit> --strict',
+ ].join('\n')
+ )
+);
diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.list.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.list.cmd.ts
new file mode 100644
index 000000000..75fbc7fe1
--- /dev/null
+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.list.cmd.ts
@@ -0,0 +1,158 @@
+import { Command, Options } from '@effect/cli';
+import {
+ detectCliPlatform,
+ formatSupportedPlatforms,
+ getLocalToolkitDeclarations,
+ getLocalToolsMetaPath,
+ localToolkitDeclarations,
+ normalizeLocalToolSlug,
+ supportsCliPlatform,
+} from '@composio/cli-local-tools';
+import { Effect, Option } from 'effect';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { bold, gray } from 'src/ui/colors';
+import { truncate } from 'src/ui/truncate';
+
+const json = Options.boolean('json').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print local tool declarations as JSON')
+);
+
+const allPlatforms = Options.boolean('all-platforms').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Include local toolkits that are not supported on this CLI platform')
+);
+
+const toolkits = Options.text('toolkits').pipe(
+ Options.optional,
+ Options.withDescription('Filter by local toolkit slugs, comma-separated')
+);
+
+const parseToolkitFilter = (value: Option.Option<string>): ReadonlyArray<string> | undefined => {
+ const raw = Option.getOrUndefined(value);
+ if (!raw?.trim()) return undefined;
+ return raw
+ .split(',')
+ .map(part => part.trim())
+ .filter(Boolean);
+};
+
+const toolkitMatchesFilter = (
+ toolkitSlug: string,
+ toolkitFilter: ReadonlyArray<string> | undefined
+): boolean => {
+ if (!toolkitFilter || toolkitFilter.length === 0) return true;
+ const allowed = new Set(toolkitFilter.map(slug => slug.toLowerCase()));
+ return allowed.has(toolkitSlug.toLowerCase());
+};
+
+const buildLocalToolkitRows = (params: {
+ readonly includeAllPlatforms: boolean;
+ readonly toolkitFilter?: ReadonlyArray<string>;
+}) => {
+ const currentPlatform = detectCliPlatform();
+ const sourceToolkits = params.includeAllPlatforms
+ ? localToolkitDeclarations.filter(toolkit =>
+ toolkitMatchesFilter(toolkit.slug, params.toolkitFilter)
+ )
+ : getLocalToolkitDeclarations({ toolkits: params.toolkitFilter });
+
+ return sourceToolkits.map(toolkit => {
+ const toolkitSupported = supportsCliPlatform(toolkit.platforms, currentPlatform);
+ return {
+ slug: toolkit.slug,
+ name: toolkit.name,
+ description: toolkit.description,
+ platforms: toolkit.platforms,
+ supported: toolkitSupported,
+ source: toolkit.source,
+ tools: toolkit.tools.map(tool => ({
+ slug: tool.slug,
+ finalSlug: normalizeLocalToolSlug(tool.slug, toolkit.slug),
+ name: tool.name,
+ description: tool.description,
+ platforms: tool.platforms,
+ supported: toolkitSupported && supportsCliPlatform(tool.platforms, currentPlatform),
+ executionKind: tool.execution.kind,
+ tags: tool.tags ?? [],
+ })),
+ };
+ });
+};
+
+const formatHumanRows = (
+ rows: ReturnType<typeof buildLocalToolkitRows>,
+ metaPath: string
+): string => {
+ const lines: string[] = [];
+ const currentPlatform = detectCliPlatform();
+ lines.push(`${bold('Local tools')} (${currentPlatform})`);
+ lines.push(`${gray('Metadata:')} ${metaPath}`);
+
+ if (rows.length === 0) {
+ lines.push('No registered local toolkits match this platform/filter.');
+ return lines.join('\n');
+ }
+
+ for (const toolkit of rows) {
+ const supportLabel = toolkit.supported ? 'supported' : 'unsupported';
+ lines.push('');
+ lines.push(
+ `${bold(toolkit.slug)} ${gray(`(${toolkit.name}; ${supportLabel}; ${formatSupportedPlatforms(toolkit.platforms)})`)}`
+ );
+ lines.push(` ${gray(truncate(toolkit.description, 96))}`);
+ if (toolkit.source?.repository) {
+ lines.push(` ${gray('source:')} ${toolkit.source.repository}`);
+ } else if (toolkit.source?.package) {
+ lines.push(` ${gray('source:')} ${toolkit.source.package}`);
+ }
+
+ for (const tool of toolkit.tools) {
+ const toolSupport = tool.supported ? '' : ` ${gray('(unsupported)')}`;
+ lines.push(
+ ` ${tool.finalSlug.padEnd(36)} ${truncate(tool.name, 24).padEnd(24)} ${gray(tool.executionKind)}${toolSupport}`
+ );
+ }
+ }
+
+ return lines.join('\n');
+};
+
+export const localToolsCmd$List = Command.make(
+ 'list',
+ { json, allPlatforms, toolkits },
+ ({ json, allPlatforms, toolkits }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const toolkitFilter = parseToolkitFilter(toolkits);
+ const rows = buildLocalToolkitRows({
+ includeAllPlatforms: allPlatforms,
+ toolkitFilter,
+ });
+ const metaPath = getLocalToolsMetaPath();
+
+ const payload = {
+ currentPlatform: detectCliPlatform(),
+ metadataPath: metaPath,
+ toolkits: rows,
+ };
+
+ if (json) {
+ yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
+ return;
+ }
+
+ yield* ui.log.message(formatHumanRows(rows, metaPath));
+ })
+).pipe(
+ Command.withDescription(
+ [
+ 'List registered local CLI toolkits and tools that can be injected into Tool Router search sessions.',
+ '',
+ 'Examples:',
+ ' composio local-tools list',
+ ' composio local-tools list --json',
+ ' composio local-tools list --toolkits <toolkit> --all-platforms',
+ ].join('\n')
+ )
+);
diff --git a/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts b/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts
new file mode 100644
index 000000000..5d283e3fb
--- /dev/null
+++ b/ts/packages/cli/src/commands/local-tools/commands/local-tools.meta.cmd.ts
@@ -0,0 +1,82 @@
+import { Command, Options } from '@effect/cli';
+import {
+ createEmptyLocalToolsMeta,
+ getLocalToolsMetaPath,
+ readLocalToolsMeta,
+ writeLocalToolsMeta,
+} from '@composio/cli-local-tools';
+import { Effect } from 'effect';
+import { TerminalUI } from 'src/services/terminal-ui';
+import { bold, gray } from 'src/ui/colors';
+
+const json = Options.boolean('json').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Print the metadata file contents as JSON')
+);
+
+const init = Options.boolean('init').pipe(
+ Options.withDefault(false),
+ Options.withDescription('Create ~/composio/local_tools.json if it does not exist')
+);
+
+export const localToolsCmd$Meta = Command.make('meta', { json, init }, ({ json, init }) =>
+ Effect.gen(function* () {
+ const ui = yield* TerminalUI;
+ const metadataPath = getLocalToolsMetaPath();
+ const meta = init
+ ? yield* Effect.tryPromise(async () => {
+ const existing = await readLocalToolsMeta();
+ const next =
+ Object.keys(existing.tools).length === 0 && Object.keys(existing.toolkits).length === 0
+ ? createEmptyLocalToolsMeta()
+ : existing;
+ await writeLocalToolsMeta(next);
+ return next;
+ })
+ : yield* Effect.tryPromise(() => readLocalToolsMeta());
+
+ const payload = {
+ metadataPath,
+ ...meta,
+ };
+
+ if (json) {
+ yield* ui.output(JSON.stringify(payload, null, 2), { force: true });
+ return;
+ }
+
+ yield* ui.log.message(
+ [
+ `${bold('Local tools metadata')}`,
+ `${gray('Path:')} ${metadataPath}`,
+ `${gray('Version:')} ${meta.version}`,
+ `${gray('Toolkits:')} ${Object.keys(meta.toolkits).length}`,
+ `${gray('Tools:')} ${Object.keys(meta.tools).length}`,
+ init ? `${gray('Status:')} initialized` : undefined,
+ '',
+ 'Use this file for local auth/install state, for example:',
+ '{',
+ ' "toolkits": {',
+ ' "example_toolkit": { "installation": { "command": "/path/to/tool" } }',
+ ' },',
+ ' "tools": {',
+ ' "LOCAL_EXAMPLE_TOOLKIT_RUN": { "authenticated": true }',
+ ' }',
+ '}',
+ ]
+ .filter((line): line is string => line !== undefined)
+ .join('\n')
+ );
+ })
+).pipe(
+ Command.withDescription(
+ [
+ 'Inspect or initialize the local tools metadata file at ~/composio/local_tools.json.',
+ '',
+ 'Examples:',
+ ' composio local-tools meta',
+ ' composio local-tools meta --init',
+ ' composio local-tools meta --json',
+ ].join('\n')
+ )
+);
diff --git a/ts/packages/cli/src/commands/local-tools/local-tools.cmd.ts b/ts/packages/cli/src/commands/local-tools/local-tools.cmd.ts
new file mode 100644
index 000000000..e7e2442d6
--- /dev/null
+++ b/ts/packages/cli/src/commands/local-tools/local-tools.cmd.ts
@@ -0,0 +1,15 @@
+import { Command } from '@effect/cli';
+import { localToolsCmd$Configure } from './commands/local-tools.configure.cmd';
+import { localToolsCmd$Doctor } from './commands/local-tools.doctor.cmd';
+import { localToolsCmd$List } from './commands/local-tools.list.cmd';
+import { localToolsCmd$Meta } from './commands/local-tools.meta.cmd';
+
+export const localToolsCmd = Command.make('local-tools').pipe(
+ Command.withDescription('Inspect and configure registered local CLI tools.'),
+ Command.withSubcommands([
+ localToolsCmd$List,
+ localToolsCmd$Doctor,
+ localToolsCmd$Configure,
+ localToolsCmd$Meta,
+ ])
+);
diff --git a/ts/packages/cli/src/commands/root-help.ts b/ts/packages/cli/src/commands/root-help.ts
index 1203fd8e2..11761dcd3 100644
--- a/ts/packages/cli/src/commands/root-help.ts
+++ b/ts/packages/cli/src/commands/root-help.ts
@@ -182,6 +182,26 @@ const FULL_COMMANDS: ReadonlyArray<TaggedValue<CompactCommand>> = [
full({ name: 'triggers info', description: 'Inspect a trigger type and schema summary' }),
full({ name: 'connections list', description: 'Print toolkit connection statuses as JSON' }),
full({ name: 'connections remove', description: 'Interactively remove a toolkit connection' }),
+ full({ name: 'local-tools list', description: 'List registered local CLI toolkits and tools' }, [
+ CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
+ ]),
+ full(
+ {
+ name: 'local-tools doctor',
+ description: 'Check local toolkit readiness and setup hints',
+ },
+ [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
+ ),
+ full(
+ {
+ name: 'local-tools configure',
+ description: 'Set local toolkit/tool metadata overrides',
+ },
+ [CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS]
+ ),
+ full({ name: 'local-tools meta', description: 'Inspect or initialize local tools metadata' }, [
+ CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS,
+ ]),
full({ name: 'generate ts', description: 'Generate TypeScript stubs for selected toolkits' }),
full({ name: 'generate py', description: 'Generate Python stubs for selected toolkits' }),
full({
@@ -572,6 +592,100 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
'composio link <toolkit> Reconnect a toolkit account',
],
},
+ 'local-tools': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
+ usage: 'composio local-tools <list|doctor|configure|meta>',
+ description:
+ 'Inspect local CLI tools that the Tool Router can search and execute alongside hosted Composio tools.',
+ examples: [
+ 'composio local-tools list',
+ 'composio local-tools doctor',
+ 'composio local-tools configure <toolkit> --command /path/to/tool',
+ ],
+ seeAlso: [
+ 'composio local-tools doctor Check installed local tool readiness',
+ 'composio local-tools meta --init Initialize local tools metadata',
+ ],
+ }),
+ 'local-tools list': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
+ usage: 'composio local-tools list [--json] [--all-platforms] [--toolkits <text>]',
+ description:
+ 'List registered local toolkits and the exact LOCAL_* tool slugs exposed to Tool Router.',
+ options: [
+ { name: '--json', description: 'Print structured declarations' },
+ {
+ name: '--all-platforms',
+ description: 'Include unsupported toolkits for the current platform',
+ },
+ { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
+ ],
+ examples: [
+ 'composio local-tools list',
+ 'composio local-tools list --json',
+ 'composio local-tools list --toolkits <toolkit> --all-platforms',
+ ],
+ seeAlso: ['composio local-tools meta Inspect local metadata state'],
+ }),
+ 'local-tools doctor': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
+ usage: 'composio local-tools doctor [--json] [--all-platforms] [--toolkits <text>] [--strict]',
+ description:
+ 'Check command availability, platform support, and setup hints for registered local toolkits.',
+ options: [
+ { name: '--json', description: 'Print structured readiness report' },
+ {
+ name: '--all-platforms',
+ description: 'Include unsupported toolkits for the current platform',
+ },
+ { name: '--toolkits <text>', description: 'Comma-separated local toolkit slug filter' },
+ { name: '--strict', description: 'Exit non-zero if any visible local tool is not ready' },
+ ],
+ examples: [
+ 'composio local-tools doctor',
+ 'composio local-tools doctor --json',
+ 'composio local-tools doctor --toolkits <toolkit> --strict',
+ ],
+ seeAlso: ['composio local-tools meta Inspect local metadata state'],
+ }),
+ 'local-tools configure': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
+ usage:
+ 'composio local-tools configure <selector> [--command <text>] [--enable|--disable] [--authenticated|--unauthenticated] [--json]',
+ description:
+ 'Configure ~/composio/local_tools.json for a local toolkit slug or LOCAL_* tool slug without hand-editing JSON.',
+ args: [
+ {
+ name: '<selector>',
+ description: 'Local toolkit slug or LOCAL_* tool slug',
+ },
+ ],
+ options: [
+ { name: '--command <text>', description: 'Override the local binary/launcher command' },
+ { name: '--json', description: 'Print the updated metadata entry as JSON' },
+ ],
+ flags: [
+ { name: '--enable', description: 'Clear disabled state' },
+ { name: '--disable', description: 'Disable this local toolkit/tool' },
+ { name: '--authenticated', description: 'Mark this local toolkit/tool authenticated' },
+ { name: '--unauthenticated', description: 'Mark this local toolkit/tool unauthenticated' },
+ ],
+ examples: [
+ 'composio local-tools configure <toolkit> --command /path/to/tool',
+ 'composio local-tools configure LOCAL_EXAMPLE_RUN --disable',
+ 'composio local-tools configure <toolkit> --authenticated --json',
+ ],
+ seeAlso: ['composio local-tools doctor Validate the configured command'],
+ }),
+ 'local-tools meta': experimental(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS, {
+ usage: 'composio local-tools meta [--json] [--init]',
+ description: 'Inspect or initialize ~/composio/local_tools.json for local auth/install state.',
+ options: [
+ { name: '--json', description: 'Print metadata state as JSON' },
+ { name: '--init', description: 'Create the metadata file if needed' },
+ ],
+ examples: [
+ 'composio local-tools meta',
+ 'composio local-tools meta --init',
+ 'composio local-tools meta --json',
+ ],
+ }),
run: {
usage: 'composio run <code> [-- ...args] | run -f <file> [-- ...args]',
description:
@@ -1113,12 +1227,13 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp | TaggedValue<SubcommandHel
usage: 'composio config experimental [<feature>] [on|off]',
description: 'View or toggle experimental feature flags.',
args: [
- { name: '<feature>', description: 'Feature name (e.g., listen, multi_account)' },
+ { name: '<feature>', description: 'Feature name (e.g., listen, local_tools, multi_account)' },
{ name: 'on|off', description: 'Enable or disable the feature' },
],
examples: [
'composio config experimental # List all features',
'composio config experimental listen # Show current state',
+ 'composio config experimental local_tools on # Enable local toolkits',
'composio config experimental multi_account on # Enable multi_account',
],
},
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
index c45f3de4f..f83deca5c 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
@@ -1,5 +1,6 @@
import { Args, Command, Options } from '@effect/cli';
import type { Composio } from '@composio/client';
+import { isLocalToolSlug } from '@composio/cli-local-tools';
import util from 'node:util';
import { Effect, Option, Either, Exit, Fiber, Cause } from 'effect';
import { encodingForModel } from 'js-tiktoken';
@@ -1012,12 +1013,22 @@ const resolveExecuteContext = (params: RunToolsExecuteParams) =>
projectId: resolvedProject.projectId,
});
const cliConfig = yield* ComposioCliUserConfig;
+ if (
+ isLocalToolSlug(params.slug) &&
+ !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
+ ) {
+ return yield* Effect.fail(
+ new Error(
+ `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`
+ )
+ );
+ }
const accountSelector = cliConfig.isExperimentalFeatureEnabled(
CLI_EXPERIMENTAL_FEATURES.MULTI_ACCOUNT
)
? params.account
: Option.none<string>();
- const toolkitSlug = toolkitFromToolSlug(params.slug);
+ const toolkitSlug = isLocalToolSlug(params.slug) ? undefined : toolkitFromToolSlug(params.slug);
const selectedConnectedAccountId = yield* resolveExplicitConnectedAccount({
client,
toolkitSlug,
@@ -1111,6 +1122,7 @@ const runConnectedToolkitFailFast = (params: {
return;
}
if (params.resolvedProject.projectType !== 'CONSUMER') return;
+ if (isLocalToolSlug(params.slug)) return;
perfDebugLog('execute.connected_toolkits.refresh_start', {
slug: params.slug,
@@ -1454,6 +1466,18 @@ const runToolsExecute = (params: RunToolsExecuteParams) =>
Effect.gen(function* () {
if (!(yield* requireAuth)) return;
+ const cliConfig = yield* ComposioCliUserConfig;
+ if (
+ isLocalToolSlug(params.slug) &&
+ !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
+ ) {
+ return yield* Effect.fail(
+ new Error(
+ `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${params.slug}.`
+ )
+ );
+ }
+
if (params.getSchema) {
const context = yield* resolveSchemaContext(params);
const definition = yield* getOrFetchToolInputDefinition(params.slug, {
@@ -1697,6 +1721,7 @@ const checkConnectedToolkitOrFail = (params: {
Effect.gen(function* () {
if (params.skipConnectionCheck || params.skipChecks) return;
if (params.resolvedProject.projectType !== 'CONSUMER') return;
+ if (isLocalToolSlug(params.slug)) return;
yield* refreshConsumerConnectedToolkitsCache({
orgId: params.resolvedProject.orgId,
diff --git a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
index 7c551d8d7..faf18471f 100644
--- a/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
+++ b/ts/packages/cli/src/commands/tools/commands/tools.search.cmd.ts
@@ -1,4 +1,5 @@
import { Args, Command, Options } from '@effect/cli';
+import { isLocalToolkitSlug } from '@composio/cli-local-tools';
import { Effect, Option } from 'effect';
import { TerminalUI } from 'src/services/terminal-ui';
import { requireAuth } from 'src/effects/require-auth';
@@ -153,7 +154,7 @@ const buildSearchNextSteps = (params: {
rootOnly: boolean;
}) => {
const steps: Array<{ action: string; command: string }> = [];
- if (params.firstToolkit) {
+ if (params.firstToolkit && !isLocalToolkitSlug(params.firstToolkit)) {
steps.push({
action: 'Link a user account',
command: params.rootOnly
@@ -282,7 +283,8 @@ const emitHumanSearchOutput = (params: {
userId: '<user-id>',
data: params.firstDataArg,
});
- yield* params.ui.log.step([linkHint, executeHint].join('\n'));
+ const steps = params.firstSlug.startsWith('LOCAL_') ? [executeHint] : [linkHint, executeHint];
+ yield* params.ui.log.step(steps.join('\n'));
}
if (params.error) {
diff --git a/ts/packages/cli/src/effects/create-tool-router-session.ts b/ts/packages/cli/src/effects/create-tool-router-session.ts
index f98a4826f..c82a88161 100644
--- a/ts/packages/cli/src/effects/create-tool-router-session.ts
+++ b/ts/packages/cli/src/effects/create-tool-router-session.ts
@@ -1,11 +1,17 @@
import { Effect, Option } from 'effect';
import type { Composio } from '@composio/client';
+import {
+ createLocalToolRouterExperimentalPayload,
+ getAllLocalToolkitSlugs,
+} from '@composio/cli-local-tools';
import {
getFreshConsumerToolRouterAuthConfigsFromCache,
getFreshConsumerToolRouterConnectedAccountsFromCache,
writeConsumerConnectedToolkitsCache,
} from 'src/services/consumer-short-term-cache';
import { resolveToolRouterSessionConnections } from 'src/services/tool-router-session-connections';
+import { ComposioCliUserConfig } from 'src/services/cli-user-config';
+import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
export interface CreateToolRouterSessionOptions {
/** Enable auto connection management. Default: false. */
@@ -27,6 +33,10 @@ export interface CreateToolRouterSessionOptions {
readonly maxAccountsPerToolkit?: number;
readonly requireExplicitSelection?: boolean;
};
+ /** Include bundled local CLI toolkits as Tool Router custom toolkits. Default: true. */
+ readonly localTools?: {
+ readonly enable?: boolean;
+ };
}
/**
@@ -47,6 +57,33 @@ export const createToolRouterSession = (
const merged = Object.assign({}, ...mappings.filter(Boolean));
return Object.keys(merged).length > 0 ? merged : undefined;
};
+ const requestedToolkits = options?.toolkits ?? [];
+ const cliConfig = yield* ComposioCliUserConfig;
+ const localToolsEnabled =
+ options?.localTools?.enable ??
+ cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS);
+ const localToolkitSlugs = new Set(getAllLocalToolkitSlugs());
+ const requestedLocalToolkits = requestedToolkits.filter(toolkit =>
+ localToolkitSlugs.has(toolkit.toLowerCase())
+ );
+ const remoteToolkits = requestedToolkits.filter(
+ toolkit => !localToolkitSlugs.has(toolkit.toLowerCase())
+ );
+ const shouldIncludeLocalToolkits =
+ requestedToolkits.length === 0 || requestedLocalToolkits.length > 0;
+ if (!localToolsEnabled && requestedLocalToolkits.length > 0) {
+ return yield* Effect.fail(
+ new Error(
+ `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before using toolkit filter(s): ${requestedLocalToolkits.join(', ')}.`
+ )
+ );
+ }
+ const localExperimentalPayload =
+ !localToolsEnabled || !shouldIncludeLocalToolkits
+ ? undefined
+ : createLocalToolRouterExperimentalPayload({
+ toolkits: requestedToolkits.length > 0 ? requestedLocalToolkits : undefined,
+ });
const excludedToolkits = new Set(
(options?.excludeConnectedAccountsForToolkits ?? []).map(toolkit => toolkit.toLowerCase())
);
@@ -62,20 +99,20 @@ export const createToolRouterSession = (
? yield* getFreshConsumerToolRouterAuthConfigsFromCache({
orgId: options.cacheScope.orgId,
consumerUserId: options.cacheScope.consumerUserId,
- toolkits: options.toolkits,
+ toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
})
: Option.none();
const cachedConnectedAccounts = options?.cacheScope
? yield* getFreshConsumerToolRouterConnectedAccountsFromCache({
orgId: options.cacheScope.orgId,
consumerUserId: options.cacheScope.consumerUserId,
- toolkits: options.toolkits,
+ toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
})
: Option.none();
const connectionContext = Option.isSome(cachedAuthConfigs)
? {
- connectedToolkits: options?.toolkits ?? [],
+ connectedToolkits: remoteToolkits,
authConfigs: cachedAuthConfigs.value.authConfigs,
connectedAccounts: mergeConnectedAccounts(
filterConnectedAccounts(
@@ -90,7 +127,7 @@ export const createToolRouterSession = (
: undefined,
}
: yield* resolveToolRouterSessionConnections(client, userId, {
- toolkits: options?.toolkits,
+ toolkits: remoteToolkits.length > 0 ? remoteToolkits : undefined,
}).pipe(
Effect.map(connectionContext => ({
...connectionContext,
@@ -129,10 +166,8 @@ export const createToolRouterSession = (
require_explicit_selection: options.multiAccount.requireExplicitSelection,
}
: undefined,
- toolkits:
- options?.toolkits && options.toolkits.length > 0
- ? { enable: [...options.toolkits] }
- : undefined,
+ toolkits: remoteToolkits.length > 0 ? { enable: [...remoteToolkits] } : undefined,
+ experimental: localExperimentalPayload,
})
).pipe(Effect.map(session => session.session_id));
});
diff --git a/ts/packages/cli/src/experimental-features.ts b/ts/packages/cli/src/experimental-features.ts
index 99d45e25d..5a7098c48 100644
--- a/ts/packages/cli/src/experimental-features.ts
+++ b/ts/packages/cli/src/experimental-features.ts
@@ -7,6 +7,7 @@
*/
export const CLI_EXPERIMENTAL_FEATURES = {
LISTEN: 'listen',
+ LOCAL_TOOLS: 'local_tools',
MULTI_ACCOUNT: 'multi_account',
} as const;
@@ -25,6 +26,7 @@ export const isExperimentalFeatureEnabledByDefault = (
case CLI_EXPERIMENTAL_FEATURES.MULTI_ACCOUNT:
return true;
case CLI_EXPERIMENTAL_FEATURES.LISTEN:
+ case CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS:
return channel === 'beta';
default:
return channel === 'beta';
diff --git a/ts/packages/cli/src/services/tool-input-validation.ts b/ts/packages/cli/src/services/tool-input-validation.ts
index cfeae48c6..639778569 100644
--- a/ts/packages/cli/src/services/tool-input-validation.ts
+++ b/ts/packages/cli/src/services/tool-input-validation.ts
@@ -2,6 +2,7 @@ import path from 'node:path';
import { FileSystem } from '@effect/platform';
import { Effect, Option } from 'effect';
import { jsonSchemaToZodSchema } from '@composio/core';
+import { getLocalToolInputDefinition } from '@composio/cli-local-tools';
import { z } from 'zod/v3';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { ComposioToolkitsRepository, getLatestToolVersion } from 'src/services/composio-clients';
@@ -170,9 +171,25 @@ const fetchAndCacheToolInputDefinition = (
const fs = yield* FileSystem.FileSystem;
const repo = yield* ComposioToolkitsRepository;
const cacheDir = yield* setupCacheDir;
- const schemaPath = toolDefinitionPath(cacheDir, slug);
+ const localDefinition = getLocalToolInputDefinition(slug);
+ const schemaPath = toolDefinitionPath(cacheDir, localDefinition?.finalSlug ?? slug);
yield* ensureToolDefinitionsDir(fs, cacheDir);
+ if (localDefinition) {
+ yield* fs.writeFileString(
+ schemaPath,
+ serializeCachedToolDefinition({
+ version: localDefinition.version,
+ inputSchema: localDefinition.schema,
+ })
+ );
+ return {
+ schemaPath,
+ schema: localDefinition.schema,
+ version: localDefinition.version,
+ };
+ }
+
const tool = yield* repo.getToolDetailed(slug);
toolDebugLog('tool_detail', {
slug,
diff --git a/ts/packages/cli/src/services/tools-executor.ts b/ts/packages/cli/src/services/tools-executor.ts
index bc2a21b6f..04d0e2c51 100644
--- a/ts/packages/cli/src/services/tools-executor.ts
+++ b/ts/packages/cli/src/services/tools-executor.ts
@@ -1,6 +1,7 @@
import { FileSystem } from '@effect/platform';
import { Context, Effect, Layer } from 'effect';
import type { Composio } from '@composio/client';
+import { executeLocalToolBySlug, isLocalToolSlug } from '@composio/cli-local-tools';
import type {
SessionExecuteResponse,
SessionExecuteMetaResponse,
@@ -18,6 +19,8 @@ import type { NodeOs } from 'src/services/node-os';
import type { NodeProcess } from 'src/services/node-process';
import type { ComposioUserContext } from 'src/services/user-context';
import type { ComposioToolkitsRepository } from 'src/services/composio-clients';
+import { ComposioCliUserConfig } from 'src/services/cli-user-config';
+import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
/**
* Parameters accepted by the Tool Router-based executor.
@@ -50,7 +53,12 @@ export interface ToolsExecutor {
) => Effect.Effect<
ToolExecuteResponse,
unknown,
- FileSystem.FileSystem | NodeOs | NodeProcess | ComposioUserContext | ComposioToolkitsRepository
+ | FileSystem.FileSystem
+ | NodeOs
+ | NodeProcess
+ | ComposioUserContext
+ | ComposioToolkitsRepository
+ | ComposioCliUserConfig
>;
}
@@ -133,6 +141,30 @@ export const ToolsExecutorLive = Layer.effect(
return ToolsExecutor.of({
execute: (slug, params) =>
Effect.gen(function* () {
+ const cliConfig = yield* ComposioCliUserConfig;
+ if (
+ isLocalToolSlug(slug) &&
+ !cliConfig.isExperimentalFeatureEnabled(CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS)
+ ) {
+ return yield* Effect.fail(
+ new Error(
+ `Local tools are experimental. Enable them with \`composio config experimental ${CLI_EXPERIMENTAL_FEATURES.LOCAL_TOOLS} on\` before executing ${slug}.`
+ )
+ );
+ }
+
+ const localResult = yield* Effect.tryPromise(() =>
+ executeLocalToolBySlug(slug, params.arguments)
+ );
+ if (localResult) {
+ return {
+ successful: true,
+ data: localResult as Record<string, unknown>,
+ error: null,
+ logId: '',
+ } satisfies ToolExecuteResponse;
+ }
+
const client = yield* clientSingleton.get();
const resolvedClient = params.client ?? client;
// One session per invocation — CLI runs one tool per process.
diff --git a/ts/packages/cli/test/src/commands/feature-visibility.test.ts b/ts/packages/cli/test/src/commands/feature-visibility.test.ts
index 530aa4b3a..31967ad85 100644
--- a/ts/packages/cli/test/src/commands/feature-visibility.test.ts
+++ b/ts/packages/cli/test/src/commands/feature-visibility.test.ts
@@ -27,9 +27,11 @@ const getSubcommandNames = (visibility: typeof stableVisibility) =>
);
describe('CLI experimental feature visibility', () => {
- it('hides listen from the stable root command graph', () => {
+ it('hides experimental root commands from the stable root command graph', () => {
expect(getSubcommandNames(stableVisibility)).not.toContain('listen');
+ expect(getSubcommandNames(stableVisibility)).not.toContain('local-tools');
expect(getSubcommandNames(betaVisibility)).toContain('listen');
+ expect(getSubcommandNames(betaVisibility)).toContain('local-tools');
});
it('hides listen help when the feature is disabled', () => {
@@ -41,11 +43,20 @@ describe('CLI experimental feature visibility', () => {
);
});
- it('hides contextual listen help when the feature is disabled', () => {
+ it('hides contextual experimental help when the feature is disabled', () => {
expect(matchCommandFromArgv(['bun', 'composio', 'listen'], stableVisibility)).toBe(undefined);
expect(matchCommandFromArgv(['bun', 'composio', 'listen'], betaVisibility)).toBe('listen');
expect(getCommandHelpText('listen', stableVisibility)).toBe(undefined);
expect(getCommandHelpText('listen', betaVisibility)).toContain('composio listen');
+
+ expect(matchCommandFromArgv(['bun', 'composio', 'local-tools'], stableVisibility)).toBe(
+ undefined
+ );
+ expect(matchCommandFromArgv(['bun', 'composio', 'local-tools'], betaVisibility)).toBe(
+ 'local-tools'
+ );
+ expect(getCommandHelpText('local-tools', stableVisibility)).toBe(undefined);
+ expect(getCommandHelpText('local-tools', betaVisibility)).toContain('composio local-tools');
});
it('accepts help mode suffixes when matching subcommand help', () => {
diff --git a/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts b/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts
new file mode 100644
index 000000000..e41046ffd
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/local-tools.cmd.test.ts
@@ -0,0 +1,91 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { describe, expect, layer } from '@effect/vitest';
+import { Effect } from 'effect';
+import { cli, MockConsole, TestLive } from 'test/__utils__';
+
+const withLocalToolsPath = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ Effect.acquireUseRelease(
+ Effect.sync(() => {
+ const previous = process.env.COMPOSIO_LOCAL_TOOLS_PATH;
+ process.env.COMPOSIO_LOCAL_TOOLS_PATH = path.join(
+ os.tmpdir(),
+ `composio-local-tools-${Date.now()}.json`
+ );
+ return previous;
+ }),
+ () => effect,
+ previous =>
+ Effect.sync(() => {
+ if (previous === undefined) {
+ delete process.env.COMPOSIO_LOCAL_TOOLS_PATH;
+ } else {
+ process.env.COMPOSIO_LOCAL_TOOLS_PATH = previous;
+ }
+ })
+ );
+
+describe('CLI: composio local-tools', () => {
+ layer(TestLive())(it => {
+ it.scoped('[Given] --json [Then] lists bundled local toolkits', () =>
+ Effect.gen(function* () {
+ yield* cli(['local-tools', 'list', '--json', '--all-platforms']);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const payload = JSON.parse(lines.at(-1) ?? '') as {
+ currentPlatform: string;
+ metadataPath: string;
+ toolkits: Array<{ slug: string }>;
+ };
+
+ expect(payload.currentPlatform).toBeTruthy();
+ expect(payload.metadataPath).toContain('local_tools.json');
+ expect(payload.toolkits.map(toolkit => toolkit.slug)).toEqual(
+ expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
+ );
+ })
+ );
+
+ it.scoped('[Given] doctor --json [Then] reports local toolkit readiness', () =>
+ Effect.gen(function* () {
+ yield* cli(['local-tools', 'doctor', '--json', '--all-platforms']);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const payload = JSON.parse(lines.at(-1) ?? '') as {
+ metadataPath: string;
+ toolkits: Array<{ slug: string }>;
+ };
+
+ expect(payload.metadataPath).toContain('local_tools.json');
+ expect(payload.toolkits.map(toolkit => toolkit.slug)).toEqual(
+ expect.arrayContaining(['BEEPER_IMESSAGE', 'CHROME_DEVTOOLS', 'PEEKABOO'])
+ );
+ })
+ );
+
+ it.scoped('[Given] meta --init --json [Then] writes local metadata file', () =>
+ withLocalToolsPath(
+ Effect.gen(function* () {
+ yield* cli(['local-tools', 'meta', '--init', '--json']);
+
+ const lines = yield* MockConsole.getLines({ stripAnsi: true });
+ const payload = JSON.parse(lines.at(-1) ?? '') as {
+ metadataPath: string;
+ version: number;
+ toolkits: Record<string, unknown>;
+ tools: Record<string, unknown>;
+ };
+ const file = JSON.parse(
+ yield* Effect.tryPromise(() => fs.readFile(payload.metadataPath, 'utf8'))
+ ) as typeof payload;
+
+ expect(payload.version).toBe(1);
+ expect(payload.toolkits).toEqual({});
+ expect(payload.tools).toEqual({});
+ expect(file.version).toBe(1);
+ })
+ )
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
index 5201d4009..826b62602 100644
--- a/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/tools/tools.search.cmd.test.ts
@@ -441,12 +441,49 @@ describe('CLI: composio search', () => {
yield* cli(['search', 'send', '--toolkits', 'gmail,outlook']).pipe(Effect.provide(live));
expect(createParams?.toolkits).toEqual({ enable: ['gmail', 'outlook'] });
+ expect(createParams?.experimental).toBeUndefined();
expect(searchParams?.queries[0]?.use_case).toBe('send');
})
);
}
);
+ layer(TestLive(testLiveOptions))(
+ '[Given] unknown local-style toolkit filter [Then] it is still sent as a remote toolkit',
+ it => {
+ it.scoped('does not inject experimental custom toolkits in the foundation package', () =>
+ Effect.gen(function* () {
+ let createParams: SessionCreateParams | undefined;
+
+ const live = TestLive({
+ baseConfigProvider: testConfigProvider,
+ toolkitsData,
+ fixture: 'global-test-user-id',
+ toolRouter: {
+ create: async params => {
+ createParams = params;
+ return {
+ session_id: 'trs_test_session',
+ config: { user_id: params.user_id, preload: { tools: [] } },
+ config_version: 1,
+ mcp: { type: 'http', url: 'https://mcp.test.composio.dev' },
+ tool_router_tools: ['COMPOSIO_SEARCH_TOOLS'],
+ };
+ },
+ },
+ });
+
+ yield* cli(['search', 'inspect local app', '--toolkits', 'local_app']).pipe(
+ Effect.provide(live)
+ );
+
+ expect(createParams?.toolkits).toEqual({ enable: ['local_app'] });
+ expect(createParams?.experimental).toBeUndefined();
+ })
+ );
+ }
+ );
+
layer(TestLive(testLiveOptions))(
'[Given] multiple queries [Then] search passes all queries to the tool-router session',
it => {
diff --git a/ts/packages/cli/tsconfig.src.json b/ts/packages/cli/tsconfig.src.json
index 9a1792271..b8d3541ae 100644
--- a/ts/packages/cli/tsconfig.src.json
+++ b/ts/packages/cli/tsconfig.src.json
@@ -11,7 +11,8 @@
"rootDir": ".",
"paths": {
"src/*": ["./src/*"],
- "effect-errors/*": ["./src/effect-errors/*"]
+ "effect-errors/*": ["./src/effect-errors/*"],
+ "@composio/cli-local-tools": ["../cli-local-tools/src/index.ts"]
},
"types": ["@types/bun"]
},
diff --git a/ts/packages/cli/tsconfig.test.json b/ts/packages/cli/tsconfig.test.json
index b8352e395..38ec08c95 100644
--- a/ts/packages/cli/tsconfig.test.json
+++ b/ts/packages/cli/tsconfig.test.json
@@ -11,6 +11,7 @@
"paths": {
"src/*": ["./src/*"],
"effect-errors/*": ["./src/effect-errors/*"],
+ "@composio/cli-local-tools": ["../cli-local-tools/src/index.ts"],
"test/*": ["./test/*"]
},
"types": ["@types/bun", "vitest/importMeta"]
diff --git a/ts/packages/cli/tsdown.config.ts b/ts/packages/cli/tsdown.config.ts
index b3114cc2d..47447622d 100644
--- a/ts/packages/cli/tsdown.config.ts
+++ b/ts/packages/cli/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../tsdown.config.base';
+import { baseConfig } from '../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
@@ -12,9 +12,10 @@ export default defineConfig({
],
format: ['esm'],
tsconfig: './tsconfig.src.json',
- external: undefined,
+ external: [/^bun:/],
noExternal: [
'@composio/core',
+ '@composio/cli-local-tools',
/^zod(?:\/.*)?$/,
/^@agentclientprotocol\/sdk(?:\/.*)?$/,
/^@modelcontextprotocol\/sdk(?:\/.*)?$/,
diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.ts
index 998265892..d174453c1 100644
--- a/ts/packages/cli/vitest.config.ts
+++ b/ts/packages/cli/vitest.config.ts
@@ -5,6 +5,7 @@ const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));
const coreDir = path.resolve(__dirname, '../core');
const tsBuildersDir = path.resolve(__dirname, '../ts-builders');
const jsonSchemaToZodDir = path.resolve(__dirname, '../json-schema-to-zod');
+const cliLocalToolsDir = path.resolve(__dirname, '../cli-local-tools');
export default defineConfig({
resolve: {
@@ -15,6 +16,7 @@ export default defineConfig({
'@composio/core': path.join(coreDir, 'src/index.ts'),
'@composio/ts-builders': path.join(tsBuildersDir, 'src/index.ts'),
'@composio/json-schema-to-zod': path.join(jsonSchemaToZodDir, 'src/index.ts'),
+ '@composio/cli-local-tools': path.join(cliLocalToolsDir, 'src/index.ts'),
'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
// @composio/core uses package.json "imports" (#config_defaults, #platform, etc.)
// Vitest/Vite does not resolve these for workspace deps, so alias them explicitly
diff --git a/ts/packages/core/tsdown.config.ts b/ts/packages/core/tsdown.config.ts
index 4721e6e89..d08b9f596 100644
--- a/ts/packages/core/tsdown.config.ts
+++ b/ts/packages/core/tsdown.config.ts
@@ -1,5 +1,5 @@
-import { defineConfig, UserConfig } from 'tsdown';
-import { baseConfig } from '../../../tsdown.config.base';
+import { defineConfig } from 'tsdown';
+import { baseConfig } from '../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/json-schema-to-zod/tsdown.config.ts b/ts/packages/json-schema-to-zod/tsdown.config.ts
index b1be8d9fc..c7792da3b 100644
--- a/ts/packages/json-schema-to-zod/tsdown.config.ts
+++ b/ts/packages/json-schema-to-zod/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../tsdown.config.base';
+import { baseConfig } from '../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/anthropic/tsdown.config.ts b/ts/packages/providers/anthropic/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/anthropic/tsdown.config.ts
+++ b/ts/packages/providers/anthropic/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/claude-agent-sdk/tsdown.config.ts b/ts/packages/providers/claude-agent-sdk/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/claude-agent-sdk/tsdown.config.ts
+++ b/ts/packages/providers/claude-agent-sdk/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/cloudflare/tsdown.config.ts b/ts/packages/providers/cloudflare/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/cloudflare/tsdown.config.ts
+++ b/ts/packages/providers/cloudflare/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/google/tsdown.config.ts b/ts/packages/providers/google/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/google/tsdown.config.ts
+++ b/ts/packages/providers/google/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/langchain/tsdown.config.ts b/ts/packages/providers/langchain/tsdown.config.ts
index 4bb27177e..c242a227c 100644
--- a/ts/packages/providers/langchain/tsdown.config.ts
+++ b/ts/packages/providers/langchain/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/llamaindex/tsdown.config.ts b/ts/packages/providers/llamaindex/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/llamaindex/tsdown.config.ts
+++ b/ts/packages/providers/llamaindex/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/mastra/tsdown.config.ts b/ts/packages/providers/mastra/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/mastra/tsdown.config.ts
+++ b/ts/packages/providers/mastra/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/openai-agents/tsdown.config.ts b/ts/packages/providers/openai-agents/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/openai-agents/tsdown.config.ts
+++ b/ts/packages/providers/openai-agents/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/openai/tsdown.config.ts b/ts/packages/providers/openai/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/openai/tsdown.config.ts
+++ b/ts/packages/providers/openai/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/providers/vercel/tsdown.config.ts b/ts/packages/providers/vercel/tsdown.config.ts
index fa478cbd3..a1602691f 100644
--- a/ts/packages/providers/vercel/tsdown.config.ts
+++ b/ts/packages/providers/vercel/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../../tsdown.config.base';
+import { baseConfig } from '../../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,
diff --git a/ts/packages/ts-builders/tsdown.config.ts b/ts/packages/ts-builders/tsdown.config.ts
index b1be8d9fc..c7792da3b 100644
--- a/ts/packages/ts-builders/tsdown.config.ts
+++ b/ts/packages/ts-builders/tsdown.config.ts
@@ -1,5 +1,5 @@
import { defineConfig } from 'tsdown';
-import { baseConfig } from '../../../tsdown.config.base';
+import { baseConfig } from '../../../tsdown.config.base.ts';
export default defineConfig({
...baseConfig,