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

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

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

Synced Nov 21, 19:45 UTC

feat(examples): executable, CI-linked Mastra example (Tool Router + Workers) (#3788)

## What Turns the **Mastra** example into an executable reference that doubles as a test, and wires the examples into CI for the first time. First slice of the v1 "executable examples" workstream — the pattern here is the template for the other TS providers, then Python. ## Why Examples under `ts/examples/*` were unverified: the only CI tie-in is `validate-examples.ts`, which is transpile-only (no cross-file types, no lint, no execution) and passes on exactly the schema-conversion regressions we keep hitting in the Mastra provider — all closed but unprotected: - https://github.com/ComposioHQ/composio/issues/2109 (zod→json serialization crash) - https://github.com/ComposioHQ/composio/issues/3307 (`$defs` dropped while `$ref` kept) - https://github.com/mastra-ai/mastra/issues/13909 (already-JSON-Schema tools crash serialization) ## Changes **Canonical Mastra example** (`ts/examples/mastra`) - `src/index.ts` — direct tools on the unauthenticated `HACKERNEWS` toolkit - `src/tool-router.ts` — v1-canonical `composio.sessions.create(...)` → `session.tools()` (drops the deprecated bare `composio.create` alias) - `src/cloudflare.ts` — the same wrapping path on the Cloudflare Workers runtime (`export default { fetch }`) - `src/smoke.ts` — deterministic wrapping + tool-router assertions (needs only `COMPOSIO_API_KEY`) - Removed the old Gmail/MCP entries that used deprecated APIs and required auth - Runnable via `bun ts/examples/mastra/src/{index,tool-router}.ts` **Real typecheck + lint** (examples previously escaped both) - Example now has a `typecheck` script (Node + Worker tsconfigs); `typecheck:examples` / `lint:examples` scripts added - eslint now covers `ts/examples/**` with type-safety rules kept (`no-explicit-any`) and console noise allowed **Two-tier CI** - `ts.examples.yml` — per-PR **blocking**, no secrets: build → typecheck → lint → `wrangler deploy --dry-run`. This is the tier that catches the schema-conversion regressions, since a dropped `$defs`/`$ref` surfaces as a **type** error. - `ts.examples-nightly.yml` — **non-blocking**, scheduled: executes against the **staging** backend with secrets; runs the deterministic smoke always and the full agent examples when an LLM key is set. ## Verification Locally against staging: `smoke` passes (5 direct + 6 tool-router tools), `typecheck:examples` and `lint:examples` are green, the Worker `wrangler deploy --dry-run` bundles, and seeded regressions (a type error / an `any`) correctly fail their gate. ## Notes - No changeset — example packages are private/unpublished. - Follow-ups (separate PRs): template the pattern to the other TS providers, then port to `python/examples/*`.

Alberto Schiabel committed Jul 10, 2026 at 01:40 UTC 76881491d0d91877e8aa0eaab34c37e9b4156751
19 files changed +455 -371
.github/workflows/ts.examples-nightly.yml new
+65
@@ -0,0 +1,65 @@
1 +name: Examples Nightly (staging)
2 +
3 +# Executes the provider examples against the STAGING backend with real
4 +# credentials. Non-blocking by design: it runs on a schedule (and on demand),
5 +# never as a required PR check, so staging/LLM flakiness cannot gate merges.
6 +on:
7 + schedule:
8 + - cron: '0 6 * * *' # 06:00 UTC nightly
9 + workflow_dispatch:
10 +
11 +concurrency:
12 + group: ${{ github.workflow }}
13 + cancel-in-progress: false
14 +
15 +permissions:
16 + contents: read
17 +
18 +env:
19 + # Staging is not a secret; the API keys are.
20 + COMPOSIO_BASE_URL: https://staging-backend.composio.dev
21 + COMPOSIO_API_KEY: ${{ secrets.COMPOSIO_API_KEY }}
22 + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
23 +
24 +jobs:
25 + examples-staging:
26 + name: Examples against staging
27 + runs-on: ubuntu-latest
28 +
29 + steps:
30 + - name: Checkout Code
31 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
32 +
33 + - name: Setup Node.js, pnpm, Bun
34 + uses: ./.github/actions/setup-node-pnpm-bun
35 + with:
36 + enable-turbo-cache: 'true'
37 +
38 + - name: Install Dependencies
39 + run: pnpm install --frozen-lockfile
40 +
41 + - name: Build SDK packages
42 + run: pnpm run build:packages
43 +
44 + # On the schedule the secret must be present. Without this, a rotated/renamed/
45 + # empty COMPOSIO_API_KEY would make smoke self-skip (exit 0) and every LLM step
46 + # no-op, leaving the whole "regression net" green while testing nothing.
47 + - name: Require COMPOSIO_API_KEY on scheduled runs
48 + if: ${{ github.event_name == 'schedule' && env.COMPOSIO_API_KEY == '' }}
49 + run: |
50 + echo "::error::COMPOSIO_API_KEY is empty on a scheduled run — smoke would no-op and mask regressions."
51 + exit 1
52 +
53 + # Deterministic regression net — needs only COMPOSIO_API_KEY, no LLM.
54 + # Self-skips when the secret is absent (e.g. fork-triggered dispatch).
55 + - name: Mastra smoke (wrapping + tool-router)
56 + run: pnpm --filter mastra-example run smoke
57 +
58 + # Full agent run — only when an LLM key is configured.
59 + - name: Mastra direct-tools example
60 + if: ${{ env.OPENAI_API_KEY != '' }}
61 + run: bun ts/examples/mastra/src/index.ts
62 +
63 + - name: Mastra tool-router example
64 + if: ${{ env.OPENAI_API_KEY != '' }}
65 + run: bun ts/examples/mastra/src/tool-router.ts
.github/workflows/ts.examples.yml new
+67
@@ -0,0 +1,67 @@
1 +name: Examples TypeScript SDK
2 +
3 +on:
4 + push:
5 + branches: [master, next]
6 + paths:
7 + - 'ts/examples/**'
8 + - 'ts/packages/core/**'
9 + - 'ts/packages/providers/**'
10 + - 'eslint.config.mjs'
11 + - '.github/actions/setup-node-pnpm-bun/action.yml'
12 + - '.github/workflows/ts.examples.yml'
13 + - 'mise.toml'
14 + - 'mise.lock'
15 + - 'turbo.jsonc'
16 + pull_request:
17 + branches: [master, next]
18 + paths:
19 + - 'ts/examples/**'
20 + - 'ts/packages/core/**'
21 + - 'ts/packages/providers/**'
22 + - 'eslint.config.mjs'
23 + - '.github/actions/setup-node-pnpm-bun/action.yml'
24 + - '.github/workflows/ts.examples.yml'
25 + - 'mise.toml'
26 + - 'mise.lock'
27 + - 'turbo.jsonc'
28 +
29 +concurrency:
30 + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
31 + cancel-in-progress: ${{ github.event_name == 'pull_request' }}
32 +
33 +permissions:
34 + contents: read
35 +
36 +jobs:
37 + examples:
38 + name: Examples TypeScript SDK
39 + runs-on: ubuntu-latest
40 +
41 + steps:
42 + - name: Checkout Code
43 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
44 +
45 + - name: Setup Node.js, pnpm, Bun
46 + uses: ./.github/actions/setup-node-pnpm-bun
47 + with:
48 + enable-turbo-cache: 'true'
49 +
50 + - name: Install Dependencies
51 + run: pnpm install --frozen-lockfile
52 +
53 + # Examples depend on the built @composio/* workspace packages for type
54 + # resolution and the Workers bundle. turbo typecheck also builds these via
55 + # ^build, but building explicitly keeps the wrangler step self-contained.
56 + - name: Build SDK packages
57 + run: pnpm run build:packages
58 +
59 + - name: Typecheck examples
60 + run: pnpm run typecheck:examples
61 +
62 + - name: Lint examples
63 + run: pnpm run lint:examples
64 +
65 + # Prove the Cloudflare Workers entry bundles without secrets or deploying.
66 + - name: Cloudflare Workers dry-run build
67 + run: pnpm --filter mastra-example run cf:dry-run
eslint.config.mjs
+23 -2
@@ -10,12 +10,13 @@ export default [
10 'ts/packages/**/acp-adapters/**',
11 'ts/packages/**/node_modules/**',
12 'node_modules/**',
13 - 'examples/',
13 + 'ts/examples/**/dist/**',
14 + 'ts/examples/**/dist-worker/**',
15 'scripts/**',
16 '**/test/**',
17 ],
18 },
18 - { files: ['ts/packages/**/*.ts'] },
19 + { files: ['ts/packages/**/*.ts', 'ts/examples/**/*.ts'] },
20 { languageOptions: { globals: globals.browser } },
21 ...tseslint.configs.recommended,
22 {
@@ -69,4 +70,24 @@ export default [
70 ],
71 },
72 },
73 + {
74 + // Examples are console-driven references. Keep type-safety rules
75 + // (no-explicit-any, unused-vars) but drop console noise. The Buffer/crypto
76 + // restrictions above target SDK/Workers source; Node example scripts may
77 + // legitimately use Node built-ins, so relax them here (see KTD6).
78 + files: ['ts/examples/**/*.ts'],
79 + rules: {
80 + 'no-console': 'off',
81 + 'no-restricted-globals': 'off',
82 + 'no-restricted-imports': 'off',
83 + },
84 + },
85 + {
86 + // The Cloudflare Workers entry stays portable: no Node globals even though
87 + // nodejs_compat is enabled. Re-apply the restriction dropped just above.
88 + files: ['ts/examples/**/cloudflare.ts'],
89 + rules: {
90 + 'no-restricted-globals': ['error', 'Buffer'],
91 + },
92 + },
93 ];
package.json
+2
@@ -37,6 +37,8 @@
37 "test:ui": "vitest --ui",
38 "typecheck": "turbo typecheck --filter=./ts/packages/**",
39 "typecheck:tsc": "turbo typecheck:tsc --filter=./ts/packages/**",
40 + "typecheck:examples": "turbo typecheck --filter=mastra-example",
41 + "lint:examples": "eslint ts/examples/mastra --ext .ts,.tsx",
42 "lint": "eslint ts/packages --ext .ts,.tsx",
43 "lint:packages": "eslint ts/packages --ext .ts,.tsx",
44 "lint:fix": "eslint . --ext .ts,.tsx --fix",
pnpm-lock.yaml
+16 -13
@@ -773,9 +773,6 @@ importers:
773 '@mastra/core':
774 specifier: 'catalog:'
775 version: 1.49.0(@cfworker/json-schema@4.1.1)(ai@6.0.219(zod@4.4.3))(express@5.2.1)(zod@4.4.3)
776 - '@mastra/mcp':
777 - specifier: ^1.13.0
778 - version: 1.13.0(@cfworker/json-schema@4.1.1)(@mastra/core@1.49.0(@cfworker/json-schema@4.1.1)(ai@6.0.219(zod@4.4.3))(express@5.2.1)(zod@4.4.3))(zod@4.4.3)
776 ai:
777 specifier: ^6.0.219
778 version: 6.0.219(zod@4.4.3)
@@ -786,6 +783,9 @@ importers:
783 specifier: 'catalog:'
784 version: 4.4.3
785 devDependencies:
786 + '@cloudflare/workers-types':
787 + specifier: 'catalog:'
788 + version: 4.20260702.1
789 '@types/bun':
790 specifier: 'catalog:'
791 version: 1.3.14
@@ -795,6 +795,9 @@ importers:
795 typescript:
796 specifier: 'catalog:'
797 version: 6.0.3
798 + wrangler:
799 + specifier: 'catalog:'
800 + version: 4.107.0(@cloudflare/workers-types@4.20260702.1)
801
802 ts/examples/mcp:
803 dependencies:
@@ -1155,7 +1158,7 @@ importers:
1158 version: 3.21.4
1159 extract-zip:
1160 specifier: ^2.0.1
1158 - version: 2.0.1
1161 + version: 2.0.1(supports-color@10.2.2)
1162 indent-string:
1163 specifier: ^5.0.0
1164 version: 5.0.0
@@ -1282,7 +1285,7 @@ importers:
1285 version: 1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
1286 extract-zip:
1287 specifier: ^2.0.1
1285 - version: 2.0.1
1288 + version: 2.0.1(supports-color@10.2.2)
1289 zod:
1290 specifier: 'catalog:'
1291 version: 4.4.3
@@ -1366,7 +1369,7 @@ importers:
1369 version: link:../core
1370 '@earendil-works/pi-coding-agent':
1371 specifier: ^0.80.3
1369 - version: 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)
1372 + version: 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.0)(zod@4.4.3)
1373 tsdown:
1374 specifier: 'catalog:'
1375 version: 0.22.3(@arethetypeswrong/core@0.18.4)(@typescript/native-preview@7.0.0-dev.20260703.1)(publint@0.3.21)(tsx@4.22.5)(typescript@6.0.3)(unrun@0.2.27(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1))
@@ -7522,7 +7525,7 @@ snapshots:
7525
7526 '@earendil-works/pi-agent-core@0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)':
7527 dependencies:
7525 - '@earendil-works/pi-ai': 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)
7528 + '@earendil-works/pi-ai': 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.0)(zod@4.4.3)
7529 ignore: 7.0.5
7530 typebox: 1.1.38
7531 yaml: 2.9.0
@@ -7534,7 +7537,7 @@ snapshots:
7537 - ws
7538 - zod
7539
7537 - '@earendil-works/pi-ai@0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)':
7540 + '@earendil-works/pi-ai@0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.0)(zod@4.4.3)':
7541 dependencies:
7542 '@anthropic-ai/sdk': 0.91.1(zod@4.4.3)
7543 '@aws-sdk/client-bedrock-runtime': 3.1048.0
@@ -7542,7 +7545,7 @@ snapshots:
7545 '@mistralai/mistralai': 2.2.6(@opentelemetry/api@1.9.0)
7546 '@opentelemetry/api': 1.9.0
7547 '@smithy/node-http-handler': 4.7.3
7545 - http-proxy-agent: 7.0.2
7548 + http-proxy-agent: 7.0.2(supports-color@10.2.2)
7549 https-proxy-agent: 7.0.6(supports-color@10.2.2)
7550 openai: 6.26.0(ws@8.21.0)(zod@4.4.3)
7551 partial-json: 0.1.7
@@ -7555,10 +7558,10 @@ snapshots:
7558 - ws
7559 - zod
7560
7558 - '@earendil-works/pi-coding-agent@0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)':
7561 + '@earendil-works/pi-coding-agent@0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.0)(zod@4.4.3)':
7562 dependencies:
7563 '@earendil-works/pi-agent-core': 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)
7561 - '@earendil-works/pi-ai': 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.0)(zod@4.4.3)
7564 + '@earendil-works/pi-ai': 0.80.3(@modelcontextprotocol/sdk@1.29.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.0)(zod@4.4.3)
7565 '@earendil-works/pi-tui': 0.80.3
7566 '@silvia-odwyer/photon-node': 0.3.4
7567 chalk: 5.6.2
@@ -10112,7 +10115,7 @@ snapshots:
10115 extended-eventsource@1.7.0:
10116 optional: true
10117
10115 - extract-zip@2.0.1:
10118 + extract-zip@2.0.1(supports-color@10.2.2):
10119 dependencies:
10120 debug: 4.4.3(supports-color@10.2.2)
10121 get-stream: 5.2.0
@@ -10385,7 +10388,7 @@ snapshots:
10388 statuses: 2.0.2
10389 toidentifier: 1.0.1
10390
10388 - http-proxy-agent@7.0.2:
10391 + http-proxy-agent@7.0.2(supports-color@10.2.2):
10392 dependencies:
10393 agent-base: 7.1.4
10394 debug: 4.4.3(supports-color@10.2.2)
ts/examples/mastra/.env.example
+8 -5
@@ -1,7 +1,10 @@
1 +# Composio API key — https://app.composio.dev
2 +COMPOSIO_API_KEY=your_composio_api_key
3
2 -# # Composio API Key - Get it from https://app.composio.dev
3 -# COMPOSIO_API_KEY=your_composio_api_key
4 +# LLM key — the examples default to OpenAI (gpt-5-mini). To use Anthropic instead,
5 +# swap the model import in the source (see README) and set ANTHROPIC_API_KEY.
6 +OPENAI_API_KEY=your_openai_api_key
7 +# ANTHROPIC_API_KEY=your_anthropic_api_key
8
5 -# # Add other environment variables as needed for your example
6 -# OPENAI_API_KEY=your_openai_api_key
7 -# # ANTHROPIC_API_KEY=your_anthropic_api_key_here
9 +# Optional: target the staging backend instead of production.
10 +# COMPOSIO_BASE_URL=https://staging-backend.composio.dev
ts/examples/mastra/README.md
+37 -38
@@ -1,57 +1,56 @@
1 -# Mastra Example
1 +# Mastra × Composio
2
3 -This example demonstrates how to use Composio SDK for mastra.
3 +Runnable references for using Composio tools with [Mastra](https://mastra.ai)
4 +agents. Every example uses the **unauthenticated `HACKERNEWS` toolkit**, so no
5 +connected account is required — set two keys and run.
6
5 -## Setup
7 +These examples double as tests: they are typechecked and linted on every PR, and
8 +executed nightly against the staging backend.
9
7 -1. **Install dependencies:**
10 +## Setup
11
9 - ```bash
10 - pnpm install
11 - ```
12 +```bash
13 +pnpm install
14 +cp .env.example .env # then fill in COMPOSIO_API_KEY and OPENAI_API_KEY
15 +```
16
13 -2. **Configure environment:**
17 +- `COMPOSIO_API_KEY` — [Composio dashboard](https://app.composio.dev)
18 +- `OPENAI_API_KEY` — the examples default to OpenAI (`gpt-5-mini`)
19
15 - ```bash
16 - cp .env.example .env
17 - ```
20 +## Examples
21
19 - Then edit `.env` and add your API keys:
22 +| File | What it shows | Run |
23 +| --- | --- | --- |
24 +| `src/index.ts` | Direct tools: fetch one Composio tool as a Mastra tool | `bun ts/examples/mastra/src/index.ts` |
25 +| `src/tool-router.ts` | **Tool Router** (v1-canonical): `composio.sessions.create(...)` → `session.tools()` | `bun ts/examples/mastra/src/tool-router.ts` |
26 +| `src/cloudflare.ts` | The same wrapping path on the **Cloudflare Workers** runtime | `bun run cf:dev` (then `GET localhost:8787/`) |
27
21 - - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
28 +From this folder you can also use `pnpm start` (index), `pnpm tool-router`, and
29 +`pnpm cf:dev`.
30
23 -## Running the Example
31 +## Using Anthropic instead of OpenAI
32
25 -```bash
26 -# Run the example
27 -pnpm start
33 +Swap the model import and set `ANTHROPIC_API_KEY`:
34
29 -# Run in development mode (with file watching)
30 -pnpm dev
35 +```ts
36 +// import { openai } from '@ai-sdk/openai';
37 +import { anthropic } from '@ai-sdk/anthropic';
38 +// ...
39 +model: anthropic('claude-haiku-4-5'),
40 ```
41
33 -## What This Example Does
34 -
35 -- Initializes Composio SDK
36 -- Fetches available tools
37 -- Demonstrates basic usage patterns
38 -
39 -## Customization
40 -
41 -Edit `src/index.ts` to:
42 -
43 -- Add specific apps you want to integrate with
44 -- Implement your business logic
45 -- Add error handling and logging
42 +(You'll also need to add `@ai-sdk/anthropic` to the dependencies.)
43
47 -## Related Examples
44 +## Runtime notes
45
49 -- [OpenAI Example](../openai) - Shows integration with OpenAI
50 -- [LangChain Example](../langchain) - Shows integration with LangChain
51 -- [More Examples](../) - Browse all available examples
46 +- **Node/Bun:** `src/index.ts` and `src/tool-router.ts` read keys from
47 + `process.env` via `dotenv`.
48 +- **Cloudflare Workers:** `src/cloudflare.ts` reads keys from the Worker `env`
49 + binding (no `process.env`). Provide the key with
50 + `wrangler secret put COMPOSIO_API_KEY`. CI validates the Worker build with
51 + `wrangler deploy --dry-run`.
52
53 ## Support
54
55 - [Documentation](https://docs.composio.dev)
56 -- [Discord Community](https://discord.gg/composio)
57 -- [GitHub Issues](https://github.com/composio/composio/issues)
56 +- [GitHub Issues](https://github.com/ComposioHQ/composio/issues)
ts/examples/mastra/package.json
+8 -6
@@ -8,11 +8,12 @@
8 "scripts": {
9 "clean": "git clean -xdf node_modules",
10 "start": "bun src/index.ts",
11 - "start:node": "tsx src/index.ts",
11 + "tool-router": "bun src/tool-router.ts",
12 + "smoke": "bun src/smoke.ts",
13 "dev": "bun --watch src/index.ts",
13 - "start:mcp": "bun --watch src/mcp.ts",
14 - "start:node:mcp": "tsx src/mcp.ts",
15 - "dev:mcp": "tsx watch src/mcp.ts",
14 + "cf:dev": "wrangler dev",
15 + "cf:dry-run": "wrangler deploy --dry-run --outdir dist-worker",
16 + "typecheck": "tsc --noEmit -p ./tsconfig.json && tsc --noEmit -p ./tsconfig.worker.json",
17 "test": "echo \"Error: no test specified\" && exit 1"
18 },
19 "keywords": [
@@ -27,14 +28,15 @@
28 "@composio/core": "workspace:*",
29 "@composio/mastra": "workspace:*",
30 "@mastra/core": "catalog:",
30 - "@mastra/mcp": "^1.13.0",
31 "ai": "^6.0.219",
32 "dotenv": "catalog:",
33 "zod": "catalog:"
34 },
35 "devDependencies": {
36 + "@cloudflare/workers-types": "catalog:",
37 "@types/bun": "catalog:",
38 "@types/node": "^26.1.0",
38 - "typescript": "catalog:"
39 + "typescript": "catalog:",
40 + "wrangler": "catalog:"
41 }
42 }
ts/examples/mastra/src/cloudflare.ts new
+38
@@ -0,0 +1,38 @@
1 +/**
2 + * Mastra × Composio — Cloudflare Workers
3 + *
4 + * Proves the Mastra provider's tool-wrapping path runs on the Workers runtime,
5 + * not just Node. Reads config from the Worker `env` binding (no `process.env`),
6 + * fetches HackerNews tools wrapped for Mastra, and returns their slugs.
7 + *
8 + * This entry is what the per-PR CI validates with `wrangler deploy --dry-run`.
9 + *
10 + * Local dev:
11 + * cd ts/examples/mastra && bun run cf:dev # then GET http://localhost:8787/
12 + * Deploy config: wrangler.jsonc
13 + */
14 +import { Composio } from '@composio/core';
15 +import { MastraProvider } from '@composio/mastra';
16 +
17 +export interface Env {
18 + COMPOSIO_API_KEY: string;
19 +}
20 +
21 +export default {
22 + async fetch(_request: Request, env: Env): Promise<Response> {
23 + const composio = new Composio({
24 + apiKey: env.COMPOSIO_API_KEY,
25 + provider: new MastraProvider(),
26 + });
27 +
28 + const tools = await composio.tools.get('default', {
29 + toolkits: ['hackernews'],
30 + });
31 +
32 + return Response.json({
33 + runtime: 'cloudflare-workers',
34 + provider: 'mastra',
35 + tools: Object.keys(tools),
36 + });
37 + },
38 +};
ts/examples/mastra/src/experimental.mcp.ts deleted
-70
@@ -1,70 +0,0 @@
1 -import { openai } from '@ai-sdk/openai';
2 -import { Composio } from '@composio/core';
3 -import { MastraProvider } from '@composio/mastra';
4 -import { MCPClient as MastraMCPClient } from '@mastra/mcp';
5 -import { Agent as MastraAgent } from '@mastra/core/agent';
6 -
7 -// 1. Initialize Composio.
8 -const composio = new Composio({
9 - apiKey: process.env.COMPOSIO_API_KEY,
10 - provider: new MastraProvider(),
11 -});
12 -
13 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
14 -const externalUserId = '<external_user_id>'; // Replace it with the user id id
15 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
16 -
17 -// 2. Create an MCP config
18 -const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
19 - toolkits: [
20 - {
21 - toolkit: 'gmail',
22 - authConfigId,
23 - },
24 - ],
25 - allowedTools,
26 - manuallyManageConnections: true,
27 -});
28 -
29 -// 3. Retrieve the MCP server instance for the user
30 -const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
31 -
32 -// 4. Create a Mastra-specific MCP client.
33 -// This client needs to remain "alive" not be dropped by the GC until
34 -// the tools are retrieved from it.
35 -const mcpClient = new MastraMCPClient({
36 - servers: {
37 - composio: {
38 - url: new URL(mcp.url),
39 - },
40 - },
41 -});
42 -
43 -// 5. Retrieve tools.
44 -const tools = await mcpClient.listTools();
45 -
46 -// 6. Pass tools to Mastra-specific Agent.
47 -const agent = new MastraAgent({
48 - id: 'gmail-mcp-assistant',
49 - name: 'Gmail Assistant',
50 - instructions: `
51 - You are a helpful Gmail assistant that fetches and summarizes emails.
52 - When fetching emails, provide a clear summary of the results including sender, subject, and date.
53 - Be concise and provide actionable information based on the email content.
54 - `,
55 - model: openai('gpt-4o-mini'),
56 - tools,
57 -});
58 -
59 -// Fetch and summarize recent emails.
60 -console.log('\n=== Fetching and Summarizing Recent Emails ===');
61 -const emailResponse = await agent.generate(
62 - 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
63 -);
64 -console.log('\n📬 Email Summary:');
65 -console.log(emailResponse.text);
66 -
67 -console.log('\n✅ Gmail MCP Example completed successfully!');
68 -
69 -// 8. Close Mastra-specific MCP client.
70 -await mcpClient.disconnect();
ts/examples/mastra/src/experimental.tool-router.ts deleted
-63
@@ -1,63 +0,0 @@
1 -import { openai } from '@ai-sdk/openai';
2 -import { Composio } from '@composio/core';
3 -import { MastraProvider } from '@composio/mastra';
4 -import { MCPClient as MastraMCPClient } from '@mastra/mcp';
5 -import { Agent as MastraAgent } from '@mastra/core/agent';
6 -
7 -// 1. Initialize Composio.
8 -const composio = new Composio({
9 - apiKey: process.env.COMPOSIO_API_KEY,
10 - provider: new MastraProvider(),
11 -});
12 -
13 -const externalUserId = '<external_user_id>'; // Replace it with the user id id
14 -
15 -// 2. Create a session with a user-scoped MCP endpoint.
16 -const session = await composio.create(externalUserId, {
17 - toolkits: ['gmail'],
18 - manageConnections: true,
19 - mcp: true,
20 -});
21 -
22 -// 3. Create a Mastra-specific MCP client.
23 -// This client needs to remain "alive" not be dropped by the GC until
24 -// the tools are retrieved from it.
25 -const mcpClient = new MastraMCPClient({
26 - servers: {
27 - composio: {
28 - url: new URL(session.mcp.url),
29 - requestInit: {
30 - headers: session.mcp.headers,
31 - },
32 - },
33 - },
34 -});
35 -
36 -// 4. Retrieve tools.
37 -const tools = await mcpClient.listTools();
38 -
39 -// 5. Pass tools to Mastra-specific Agent.
40 -const agent = new MastraAgent({
41 - id: 'gmail-tool-router-assistant',
42 - name: 'Gmail Assistant',
43 - instructions: `
44 - You are a helpful Gmail assistant that fetches and summarizes emails.
45 - When fetching emails, provide a clear summary of the results including sender, subject, and date.
46 - Be concise and provide actionable information based on the email content.
47 - `,
48 - model: openai('gpt-4o-mini'),
49 - tools,
50 -});
51 -
52 -// Fetch and summarize recent emails.
53 -console.log('\n=== Fetching and Summarizing Recent Emails ===');
54 -const emailResponse = await agent.generate(
55 - 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
56 -);
57 -console.log('\n📬 Email Summary:');
58 -console.log(emailResponse.text);
59 -
60 -console.log('\n✅ Gmail MCP Example completed successfully!');
61 -
62 -// 8. Close Mastra-specific MCP client.
63 -await mcpClient.disconnect();
ts/examples/mastra/src/index.ts
+32 -45
@@ -1,70 +1,57 @@
1 /**
2 - * Mastra Example
2 + * Mastra × Composio — direct tools
3 *
4 - * This example demonstrates how to use Composio SDK for mastra.
4 + * Fetches a Composio tool as a Mastra tool and lets a Mastra Agent call it.
5 + * Uses the unauthenticated HACKERNEWS toolkit, so no connected account is
6 + * required — set only the two keys below and run.
7 *
8 * Prerequisites:
7 - * 1. Set up your COMPOSIO_API_KEY in the .env file
8 - * 2. Set up your OPENAI_API_KEY in the .env file
9 - * 3. Run the example: pnpm start
9 + * - COMPOSIO_API_KEY (https://app.composio.dev)
10 + * - OPENAI_API_KEY (or swap the model — see README)
11 + *
12 + * Run:
13 + * bun ts/examples/mastra/src/index.ts
14 */
11 -import { MastraProvider } from '@composio/mastra';
12 -import { Agent } from '@mastra/core/agent';
15 import { openai } from '@ai-sdk/openai';
16 import { Composio } from '@composio/core';
17 +import { MastraProvider } from '@composio/mastra';
18 +import { Agent } from '@mastra/core/agent';
19 import 'dotenv/config';
20
17 -/**
18 - * Initialize Composio
19 - */
21 const composio = new Composio({
22 apiKey: process.env.COMPOSIO_API_KEY,
23 provider: new MastraProvider(),
24 });
25
25 -/**
26 - * Get the tools from Composio
27 - * Attach beforeExecute and afterExecute hooks to the tools for logging
28 - */
29 -const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
30 - modifySchema: ({ toolSlug, toolkitSlug, schema }) => {
31 - console.log(
32 - `🔄 Modifying schema for tool ${toolSlug}/${toolkitSlug} with schema ${JSON.stringify(schema)}`
33 - );
34 - return schema;
35 - },
36 - beforeExecute: ({ toolSlug, toolkitSlug, params }) => {
37 - console.log(
38 - `🔄 Executing tool ${toolSlug}/${toolkitSlug} with input ${JSON.stringify(params)}`
39 - );
26 +// Fetch a single tool from the unauthenticated HackerNews toolkit.
27 +// The modifiers below are optional — they show the schema/execution hooks.
28 +const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER_BY_USERNAME', {
29 + beforeExecute: ({ toolSlug, params }) => {
30 + console.log(`🔧 executing ${toolSlug} with ${JSON.stringify(params.arguments)}`);
31 return params;
32 },
42 - afterExecute: ({ toolSlug, toolkitSlug, result }) => {
43 - console.log(
44 - `✅ Tool ${toolSlug}/${toolkitSlug} executed successfully with output ${JSON.stringify(result)}`
45 - );
33 + afterExecute: ({ toolSlug, result }) => {
34 + console.log(`✅ ${toolSlug} finished`);
35 return result;
36 },
37 });
38
50 -/**
51 - * Create the mastra agent
52 - */
53 -const hackernewsAgent = new Agent({
54 - id: 'test-mastra',
55 - name: 'Weather Agent',
56 - instructions:
57 - 'You are a helpful assistant that can use the Hackernews API to get user information.',
58 - model: openai('gpt-4o-mini'),
59 - tools: tools,
39 +const agent = new Agent({
40 + id: 'hackernews-agent',
41 + name: 'HackerNews Agent',
42 + instructions: 'You are a helpful assistant that looks up HackerNews users.',
43 + model: openai('gpt-5-mini'),
44 + tools,
45 });
46
62 -/**
63 - * Generate a response from the agent
64 - */
65 -const { text } = await hackernewsAgent.generate([
66 - { role: 'user', content: 'Tell me about the user `pg` on hackernews' },
47 +const { text } = await agent.generate([
48 + { role: 'user', content: 'Tell me about the HackerNews user `pg`.' },
49 ]);
50
69 -console.log('\n🤖 Agent Response:\n');
51 +// This example doubles as a test: a healthy run returns non-empty text.
52 +if (!text || text.trim().length === 0) {
53 + throw new Error('Agent returned empty output — expected a non-empty response.');
54 +}
55 +
56 +console.log('\n🤖 Agent response:\n');
57 console.log(text);
ts/examples/mastra/src/mcp.ts deleted
-87
@@ -1,87 +0,0 @@
1 -/**
2 - * Mastra MCP Gmail Example
3 - *
4 - * This example demonstrates how to use Composio SDK with Mastra to:
5 - * 1. Create an MCP server for Gmail toolkit
6 - * 2. Connect to the server and fetch emails using tools
7 - *
8 - * Prerequisites:
9 - * 1. Set up your COMPOSIO_API_KEY and OPENAI_API_KEY the .env file
10 - * 2. Set up Gmail authentication in Composio dashboard
11 - * 3. Run the example: pnpm tsx src/mcp.ts
12 - */
13 -
14 -import { MastraProvider } from '@composio/mastra';
15 -import { Composio } from '@composio/core';
16 -import { MCPClient } from '@mastra/mcp';
17 -import { Agent } from '@mastra/core/agent';
18 -import { openai } from '@ai-sdk/openai';
19 -import type { MastraMCPServerDefinition } from '@mastra/mcp';
20 -import 'dotenv/config';
21 -
22 -/**
23 - * Initialize Composio
24 - */
25 -const composio = new Composio({
26 - apiKey: process.env.COMPOSIO_API_KEY,
27 - provider: new MastraProvider(),
28 -});
29 -
30 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
31 -const externalUserId = '<external_user_id>'; // Replace it with your user ID
32 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
33 -
34 -// Create an MCP server with Gmail toolkit
35 -const mcpConfig = await composio.mcp.create('gmail-mcp-' + Date.now(), {
36 - toolkits: [
37 - {
38 - toolkit: 'gmail',
39 - authConfigId,
40 - },
41 - ],
42 - allowedTools,
43 -});
44 -
45 -console.log(`✅ MCP server created: ${mcpConfig.id}`);
46 -
47 -// Generate a user-scoped MCP endpoint.
48 -const mcp = await mcpConfig.generate(externalUserId);
49 -console.log('MCP server instance:', mcp);
50 -
51 -// Initialize MCPClient with the server URLs
52 -const mcpClient = new MCPClient({
53 - servers: {
54 - composio: {
55 - url: new URL(mcp.url),
56 - },
57 - } satisfies Record<string, MastraMCPServerDefinition>,
58 -});
59 -
60 -// Get available tools from MCP client
61 -const tools = await mcpClient.listTools();
62 -console.log(`🔧 Available tools: ${Object.keys(tools).join(', ')}`);
63 -
64 -// Create a Gmail agent with the MCP tools
65 -const gmailAgent = new Agent({
66 - id: 'gmail-mcp-assistant',
67 - name: 'Gmail Assistant',
68 - instructions: `
69 - You are a helpful Gmail assistant that fetches and summarizes emails.
70 - When fetching emails, provide a clear summary of the results including sender, subject, and date.
71 - Be concise and provide actionable information based on the email content.
72 - `,
73 - model: openai('gpt-4o-mini'),
74 - tools,
75 -});
76 -
77 -// Fetch and summarize recent emails
78 -console.log('\n=== Fetching and Summarizing Recent Emails ===');
79 -const emailResponse = await gmailAgent.generate(
80 - 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
81 -);
82 -console.log('\n📬 Email Summary:');
83 -console.log(emailResponse.text);
84 -
85 -console.log('\n✅ Gmail MCP Example completed successfully!');
86 -
87 -await mcpClient.disconnect();
ts/examples/mastra/src/send-email.ts deleted
-41
@@ -1,41 +0,0 @@
1 -import { openai } from '@ai-sdk/openai'
2 -import { Composio } from "@composio/core";
3 -import { MastraProvider } from "@composio/mastra";
4 -import { Agent } from "@mastra/core/agent";
5 -
6 -const composio = new Composio({
7 - provider: new MastraProvider(),
8 - apiKey: process.env.COMPOSIO_API_KEY,
9 -});
10 -
11 -
12 -const tools = await composio.tools.get(
13 - 'default',
14 - {
15 - tools: ["GMAIL_SEND_EMAIL"],
16 - }
17 -);
18 -
19 -const agent = new Agent({
20 - id: 'test-mastra',
21 - name: "Gmail Agent",
22 - instructions: "You are a helpful Gmail assistant that provides concise answers.",
23 - description: "Gmail agent",
24 - model: openai('gpt-5.2'),
25 - tools: tools,
26 -});
27 -
28 -// const toolsFromAgent = agent.listTools();
29 -// console.dir(toolsFromAgent, { depth: null });
30 -
31 -const { text, error } = await agent.generate([
32 - { role: "user", content: "Send an email to uday@composio.dev saying \"Hi from Mastra\"" },
33 -]);
34 -
35 -if (error) {
36 - console.error("\n🤖 Agent Error:\n");
37 - console.error(error);
38 -} else {
39 - console.log("\n🤖 Agent Response:\n");
40 - console.log(text);
41 -}
ts/examples/mastra/src/smoke.ts new
+68
@@ -0,0 +1,68 @@
1 +/**
2 + * Deterministic smoke test for the Mastra example.
3 + *
4 + * A live integration signal: it exercises the provider tool-wrapping and Tool
5 + * Router session paths end-to-end against a real backend (staging in CI) using
6 + * the unauthenticated HACKERNEWS toolkit, proving the wrapping does not throw
7 + * and returns usable tools.
8 + *
9 + * It intentionally does NOT re-check schema shape. The schema-conversion
10 + * invariants behind the historical regressions —
11 + * - ComposioHQ/composio#2109 (Mastra zod->json serialization crash)
12 + * - ComposioHQ/composio#3307 (dangling $ref when $defs is dropped)
13 + * - mastra-ai/mastra#13909 (already-JSON-Schema tools crash serialization)
14 + * are owned and regression-tested deterministically in the provider itself
15 + * (ts/packages/providers/mastra/test/{mastra-dangling-defs,mastra-ref}.test.ts),
16 + * which run per-PR and blocking with no secrets. Duplicating that here against a
17 + * live toolkit that never emits the pathological schema would only add flake.
18 + *
19 + * It needs only COMPOSIO_API_KEY (no LLM key) so it is cheap and non-flaky.
20 + * When COMPOSIO_API_KEY is absent (e.g. fork PRs) it skips cleanly.
21 + *
22 + * Run: bun ts/examples/mastra/src/smoke.ts
23 + */
24 +import { Composio } from '@composio/core';
25 +import { MastraProvider } from '@composio/mastra';
26 +import 'dotenv/config';
27 +
28 +const TOOLKIT = 'hackernews';
29 +const USER_ID = 'examples-smoke';
30 +
31 +function assert(condition: unknown, message: string): asserts condition {
32 + if (!condition) throw new Error(`SMOKE FAIL: ${message}`);
33 +}
34 +
35 +if (!process.env.COMPOSIO_API_KEY) {
36 + console.log('⏭️ COMPOSIO_API_KEY not set — skipping Mastra smoke.');
37 + process.exit(0);
38 +}
39 +
40 +console.log(`Backend: ${process.env.COMPOSIO_BASE_URL ?? '(default/production)'}`);
41 +
42 +const composio = new Composio({
43 + apiKey: process.env.COMPOSIO_API_KEY,
44 + provider: new MastraProvider(),
45 +});
46 +
47 +// 1. Direct tools: provider wrapping must not throw and must produce tools.
48 +const wrapped = await composio.tools.get(USER_ID, { toolkits: [TOOLKIT] });
49 +const wrappedSlugs = Object.keys(wrapped);
50 +assert(wrappedSlugs.length > 0, `mastra direct wrapping returned 0 tools for ${TOOLKIT}`);
51 +for (const [slug, tool] of Object.entries(wrapped)) {
52 + assert(
53 + (tool as { inputSchema?: unknown }).inputSchema != null,
54 + `mastra tool ${slug} has no inputSchema after wrapping`
55 + );
56 + // Serializing the wrapped schema must not throw (guards the crash-on-serialize path).
57 + JSON.stringify((tool as { inputSchema?: unknown }).inputSchema);
58 +}
59 +console.log(` ✓ direct wrapping: ${wrappedSlugs.length} tools`);
60 +
61 +// 2. Tool Router: the v1-canonical session path must return router tools.
62 +const session = await composio.sessions.create(USER_ID, { toolkits: [TOOLKIT] });
63 +const sessionTools = await session.tools();
64 +const sessionSlugs = Object.keys(sessionTools);
65 +assert(sessionSlugs.length > 0, 'mastra session.tools() returned 0 tools');
66 +console.log(` ✓ tool-router session: ${sessionSlugs.length} tools`);
67 +
68 +console.log('\n✅ Mastra smoke passed.');
ts/examples/mastra/src/tool-router.ts new
+56
@@ -0,0 +1,56 @@
1 +/**
2 + * Mastra × Composio — Tool Router
3 + *
4 + * The v1-canonical way to give an agent tools: create a session scoped to one
5 + * or more toolkits, then hand `session.tools()` to a Mastra Agent. The session
6 + * exposes Composio's router meta-tools (search + multi-execute), so the agent
7 + * discovers and runs the toolkit's tools dynamically.
8 + *
9 + * Uses the unauthenticated HACKERNEWS toolkit — no connected account needed.
10 + *
11 + * Prerequisites:
12 + * - COMPOSIO_API_KEY (https://app.composio.dev)
13 + * - OPENAI_API_KEY (or swap the model — see README)
14 + *
15 + * Run:
16 + * bun ts/examples/mastra/src/tool-router.ts
17 + */
18 +import { openai } from '@ai-sdk/openai';
19 +import { Composio } from '@composio/core';
20 +import { MastraProvider } from '@composio/mastra';
21 +import { Agent } from '@mastra/core/agent';
22 +import 'dotenv/config';
23 +
24 +const composio = new Composio({
25 + apiKey: process.env.COMPOSIO_API_KEY,
26 + provider: new MastraProvider(),
27 +});
28 +
29 +// Canonical session creation. `composio.sessions.create(...)` is the v1 surface;
30 +// the bare `composio.create(...)` alias is deprecated.
31 +const session = await composio.sessions.create('example-user', {
32 + toolkits: ['hackernews'],
33 +});
34 +
35 +const tools = await session.tools();
36 +
37 +const agent = new Agent({
38 + id: 'hackernews-router-agent',
39 + name: 'HackerNews Router Agent',
40 + instructions:
41 + 'You are a helpful assistant. Use the available Composio tools to search for and read HackerNews data before answering.',
42 + model: openai('gpt-5-mini'),
43 + tools,
44 +});
45 +
46 +const { text } = await agent.generate([
47 + { role: 'user', content: 'What are the current top 3 HackerNews stories? Give me their titles.' },
48 +]);
49 +
50 +// This example doubles as a test: a healthy run returns non-empty text.
51 +if (!text || text.trim().length === 0) {
52 + throw new Error('Agent returned empty output — expected a non-empty response.');
53 +}
54 +
55 +console.log('\n🤖 Agent response:\n');
56 +console.log(text);
ts/examples/mastra/tsconfig.json
+2 -1
@@ -13,5 +13,6 @@
13 "resolveJsonModule": true,
14 "types": ["node"]
15 },
16 - "include": ["src"]
16 + "include": ["src"],
17 + "exclude": ["src/cloudflare.ts"]
18 }
ts/examples/mastra/tsconfig.worker.json new
+15
@@ -0,0 +1,15 @@
1 +{
2 + "compilerOptions": {
3 + "target": "es2022",
4 + "lib": ["es2022"],
5 + "module": "esnext",
6 + "moduleResolution": "bundler",
7 + "strict": true,
8 + "esModuleInterop": true,
9 + "skipLibCheck": true,
10 + "resolveJsonModule": true,
11 + "noEmit": true,
12 + "types": ["@cloudflare/workers-types"]
13 + },
14 + "include": ["src/cloudflare.ts"]
15 +}
ts/examples/mastra/wrangler.jsonc new
+18
@@ -0,0 +1,18 @@
1 +/**
2 + * Wrangler config for the Mastra × Composio Workers example.
3 + * https://developers.cloudflare.com/workers/wrangler/configuration/
4 + */
5 +{
6 + "$schema": "node_modules/wrangler/config-schema.json",
7 + "name": "mastra-composio-example",
8 + "main": "src/cloudflare.ts",
9 + "compatibility_date": "2025-06-20",
10 + "compatibility_flags": ["nodejs_compat"],
11 + "observability": {
12 + "enabled": true
13 + }
14 + /**
15 + * COMPOSIO_API_KEY is provided as a Worker secret, not committed here:
16 + * wrangler secret put COMPOSIO_API_KEY
17 + */
18 +}