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(examples): executable, CI-linked Mastra example (Tool Router + Workers) (#3788)

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