Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(examples): make validation provider agnostic (#3790)
Alberto Schiabelb0a02c969334
diff --git a/.github/workflows/ts.examples-nightly.yml b/.github/workflows/ts.examples-nightly.ymlindex 98759ecaa..6bdd8629d 100644--- a/.github/workflows/ts.examples-nightly.yml+++ b/.github/workflows/ts.examples-nightly.yml@@ -23,8 +23,12 @@ env:jobs:examples-staging:- name: Examples against staging+ name: ${{ matrix.provider }} examples against stagingruns-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ provider: [mastra]steps:- name: Checkout Code@@ -52,14 +56,14 @@ jobs:# 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+ - name: ${{ matrix.provider }} smoke (wrapping + tool-router)+ run: pnpm --filter ${{ matrix.provider }}-example --fail-if-no-match run smoke# Full agent run — only when an LLM key is configured.- - name: Mastra direct-tools example+ - name: ${{ matrix.provider }} direct-tools exampleif: ${{ env.OPENAI_API_KEY != '' }}- run: bun ts/examples/mastra/src/index.ts+ run: bun ts/examples/${{ matrix.provider }}/src/index.ts- - name: Mastra tool-router example+ - name: ${{ matrix.provider }} tool-router exampleif: ${{ env.OPENAI_API_KEY != '' }}- run: bun ts/examples/mastra/src/tool-router.ts+ run: bun ts/examples/${{ matrix.provider }}/src/tool-router.tsdiff --git a/.github/workflows/ts.examples.yml b/.github/workflows/ts.examples.ymlindex 409630c5b..5600eeb7a 100644--- a/.github/workflows/ts.examples.yml+++ b/.github/workflows/ts.examples.yml@@ -8,6 +8,7 @@ on:- 'ts/packages/core/**'- 'ts/packages/providers/**'- 'eslint.config.mjs'+ - 'package.json'- '.github/actions/setup-node-pnpm-bun/action.yml'- '.github/workflows/ts.examples.yml'- 'mise.toml'@@ -20,6 +21,7 @@ on:- 'ts/packages/core/**'- 'ts/packages/providers/**'- 'eslint.config.mjs'+ - 'package.json'- '.github/actions/setup-node-pnpm-bun/action.yml'- '.github/workflows/ts.examples.yml'- 'mise.toml'@@ -64,4 +66,4 @@ jobs:# 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+ run: pnpm exec turbo cf:dry-run --filter='./ts/examples/*'diff --git a/package.json b/package.jsonindex b2ee8fe24..e64b6821c 100644--- a/package.json+++ b/package.json@@ -37,8 +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",+ "typecheck:examples": "turbo typecheck --filter='./ts/examples/*'",+ "lint:examples": "turbo lint --filter='./ts/examples/*'","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/ts/examples/mastra/README.md b/ts/examples/mastra/README.mdindex a2e81c0a9..c9b7c6759 100644--- a/ts/examples/mastra/README.md+++ b/ts/examples/mastra/README.md@@ -19,35 +19,41 @@ cp .env.example .env # then fill in COMPOSIO_API_KEY and OPENAI_API_KEY## Examples-| 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/`) |+| 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 Tool Router agent path on the **Cloudflare Workers** runtime | `bun run cf:dev` (then `GET localhost:8787/`) |From this folder you can also use `pnpm start` (index), `pnpm tool-router`, and`pnpm cf:dev`.## Using Anthropic instead of OpenAI-Swap the model import and set `ANTHROPIC_API_KEY`:+The model setup lives in `src/hackernews-agent/direct.ts` and+`src/hackernews-agent/tool-router.ts`. Replace the OpenAI provider in the agent+you want to run and add `ANTHROPIC_API_KEY` to its environment type:```ts-// import { openai } from '@ai-sdk/openai';-import { anthropic } from '@ai-sdk/anthropic';+import { createAnthropic } from '@ai-sdk/anthropic';// ...+const anthropic = createAnthropic({+ apiKey: requireKey(env, 'ANTHROPIC_API_KEY'),+});model: anthropic('claude-haiku-4-5'),```-(You'll also need to add `@ai-sdk/anthropic` to the dependencies.)+Add `@ai-sdk/anthropic` to the dependencies and configure the Anthropic key in+the Node environment or Worker bindings, depending on the runtime.## Runtime notes- **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+ binding (no `process.env`). Provide both keys with+ `wrangler secret put COMPOSIO_API_KEY` and+ `wrangler secret put OPENAI_API_KEY`. CI validates the Worker build with`wrangler deploy --dry-run`.## Supportdiff --git a/ts/examples/mastra/package.json b/ts/examples/mastra/package.jsonindex a0b9d64a7..9a062affb 100644--- a/ts/examples/mastra/package.json+++ b/ts/examples/mastra/package.json@@ -14,6 +14,7 @@"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",+ "lint": "eslint src --ext .ts,.tsx","test": "echo \"Error: no test specified\" && exit 1"},"keywords": [diff --git a/ts/examples/mastra/src/cloudflare.ts b/ts/examples/mastra/src/cloudflare.tsindex 2dbffad4a..f9cf40e2e 100644--- a/ts/examples/mastra/src/cloudflare.ts+++ b/ts/examples/mastra/src/cloudflare.ts@@ -1,9 +1,8 @@/*** 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.+ * Proves the same Tool Router agent path runs on the Workers runtime, not just+ * Node. Reads config from the Worker `env` binding (no `process.env`).** This entry is what the per-PR CI validates with `wrangler deploy --dry-run`.*@@ -11,28 +10,19 @@* 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';+import {+ runToolRouterHackerNewsAgent,+ type ToolRouterHackerNewsAgentEnvironment,+} from './hackernews-agent/tool-router';-export interface Env {- COMPOSIO_API_KEY: string;-}+export type Env = Required<ToolRouterHackerNewsAgentEnvironment>;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'],- });+ const text = await runToolRouterHackerNewsAgent(env);- return Response.json({- runtime: 'cloudflare-workers',- provider: 'mastra',- tools: Object.keys(tools),+ return new Response(text, {+ headers: { 'content-type': 'text/plain; charset=utf-8' },});},};diff --git a/ts/examples/mastra/src/hackernews-agent/direct.ts b/ts/examples/mastra/src/hackernews-agent/direct.tsnew file mode 100644index 000000000..a7290b4fc--- /dev/null+++ b/ts/examples/mastra/src/hackernews-agent/direct.ts@@ -0,0 +1,66 @@+import { createOpenAI } from '@ai-sdk/openai';+import { Composio } from '@composio/core';+import { MastraProvider } from '@composio/mastra';+import { Agent } from '@mastra/core/agent';+import { stepCountIs } from 'ai';++interface DirectHackerNewsAgentEnvironment {+ COMPOSIO_API_KEY?: string;+ OPENAI_API_KEY?: string;+}++function requireKey(+ env: DirectHackerNewsAgentEnvironment,+ name: keyof DirectHackerNewsAgentEnvironment+): string {+ const value = env[name];+ if (!value) {+ throw new Error(`${name} is required to run the HackerNews agent.`);+ }++ return value;+}++export async function runDirectHackerNewsAgent(+ env: DirectHackerNewsAgentEnvironment+): Promise<string> {+ const composioApiKey = requireKey(env, 'COMPOSIO_API_KEY');+ const openaiApiKey = requireKey(env, 'OPENAI_API_KEY');+ const composio = new Composio({+ apiKey: composioApiKey,+ provider: new MastraProvider(),+ });+ 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, result }) => {+ console.log(`✅ ${toolSlug} finished`);+ return result;+ },+ });+ const openai = createOpenAI({+ apiKey: openaiApiKey,+ });+ 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,+ });++ const { text } = await agent.generate(+ [{ role: 'user', content: 'Tell me about the HackerNews user `pg`.' }],+ {+ stopWhen: stepCountIs(10),+ }+ );++ if (!text || text.trim().length === 0) {+ throw new Error('Agent returned empty output — expected a non-empty response.');+ }++ return text;+}diff --git a/ts/examples/mastra/src/hackernews-agent/tool-router.ts b/ts/examples/mastra/src/hackernews-agent/tool-router.tsnew file mode 100644index 000000000..c9bc197e8--- /dev/null+++ b/ts/examples/mastra/src/hackernews-agent/tool-router.ts@@ -0,0 +1,66 @@+import { createOpenAI } from '@ai-sdk/openai';+import { Composio } from '@composio/core';+import { MastraProvider } from '@composio/mastra';+import { Agent } from '@mastra/core/agent';+import { stepCountIs } from 'ai';++export interface ToolRouterHackerNewsAgentEnvironment {+ COMPOSIO_API_KEY?: string;+ OPENAI_API_KEY?: string;+}++function requireKey(+ env: ToolRouterHackerNewsAgentEnvironment,+ name: keyof ToolRouterHackerNewsAgentEnvironment+): string {+ const value = env[name];+ if (!value) {+ throw new Error(`${name} is required to run the HackerNews agent.`);+ }++ return value;+}++export async function runToolRouterHackerNewsAgent(+ env: ToolRouterHackerNewsAgentEnvironment+): Promise<string> {+ const composioApiKey = requireKey(env, 'COMPOSIO_API_KEY');+ const openaiApiKey = requireKey(env, 'OPENAI_API_KEY');+ const composio = new Composio({+ apiKey: composioApiKey,+ provider: new MastraProvider(),+ });+ const session = await composio.sessions.create('example-user', {+ toolkits: ['hackernews'],+ });+ const tools = await session.tools();+ const openai = createOpenAI({+ apiKey: openaiApiKey,+ });+ 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.',+ },+ ],+ {+ stopWhen: stepCountIs(10),+ }+ );++ if (!text || text.trim().length === 0) {+ throw new Error('Agent returned empty output — expected a non-empty response.');+ }++ return text;+}diff --git a/ts/examples/mastra/src/index.ts b/ts/examples/mastra/src/index.tsindex fc4fff0f9..4b0a76be2 100644--- a/ts/examples/mastra/src/index.ts+++ b/ts/examples/mastra/src/index.ts@@ -12,49 +12,11 @@* Run:* bun ts/examples/mastra/src/index.ts*/-import { openai } from '@ai-sdk/openai';-import { Composio } from '@composio/core';-import { MastraProvider } from '@composio/mastra';-import { Agent } from '@mastra/core/agent';-import { stepCountIs } from 'ai';import 'dotenv/config';-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new MastraProvider(),-});+import { runDirectHackerNewsAgent } from './hackernews-agent/direct';-// 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, result }) => {- console.log(`✅ ${toolSlug} finished`);- return result;- },-});--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,-});--// Allow the agent a few steps to call the tool and then summarize the result.-const { text } = await agent.generate(- [{ role: 'user', content: 'Tell me about the HackerNews user `pg`.' }],- { stopWhen: stepCountIs(10) }-);--// 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.');-}+const text = await runDirectHackerNewsAgent(process.env);console.log('\n🤖 Agent response:\n');console.log(text);diff --git a/ts/examples/mastra/src/tool-router.ts b/ts/examples/mastra/src/tool-router.tsindex 5f1761971..980546c7f 100644--- a/ts/examples/mastra/src/tool-router.ts+++ b/ts/examples/mastra/src/tool-router.ts@@ -15,48 +15,11 @@* 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 { stepCountIs } from 'ai';import 'dotenv/config';-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,- provider: new MastraProvider(),-});+import { runToolRouterHackerNewsAgent } from './hackernews-agent/tool-router';-// 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,-});--// Tool Router is a multi-step flow: the agent calls the router's search +-// multi-execute meta-tools, then summarizes. Without a step budget the run-// stops after the first tool call and returns empty text, so allow several-// steps (matches the Mastra tool-router e2e reference).-const { text } = await agent.generate(- [{ role: 'user', content: 'What are the current top 3 HackerNews stories? Give me their titles.' }],- { stopWhen: stepCountIs(10) }-);--// 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.');-}+const text = await runToolRouterHackerNewsAgent(process.env);console.log('\n🤖 Agent response:\n');console.log(text);diff --git a/ts/examples/mastra/wrangler.jsonc b/ts/examples/mastra/wrangler.jsoncindex 97f25869a..894b27fe0 100644--- a/ts/examples/mastra/wrangler.jsonc+++ b/ts/examples/mastra/wrangler.jsonc@@ -9,10 +9,12 @@"compatibility_date": "2025-06-20","compatibility_flags": ["nodejs_compat"],"observability": {- "enabled": true- }+ "enabled": true,+ },/**- * COMPOSIO_API_KEY is provided as a Worker secret, not committed here:+ * COMPOSIO_API_KEY and OPENAI_API_KEY are provided as Worker secrets, not+ * committed here:* wrangler secret put COMPOSIO_API_KEY+ * wrangler secret put OPENAI_API_KEY*/}diff --git a/turbo.jsonc b/turbo.jsoncindex 5d18c988f..6812ad832 100644--- a/turbo.jsonc+++ b/turbo.jsonc@@ -74,6 +74,12 @@"dependsOn": ["^build"],"cache": false},+ "lint": {+ "inputs": ["$TURBO_DEFAULT$", "../../../eslint.config.mjs"]+ },+ "cf:dry-run": {+ "dependsOn": ["^build"]+ },"//#clean": {"cache": false},