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
fix(examples): align Python and TypeScript examples with current backend (#4107)
Alberto Schiabel8086ef02cb02
diff --git a/.github/workflows/py.check.yaml b/.github/workflows/py.check.yamlindex d1a0bb7fc..82c4a2f4c 100644--- a/.github/workflows/py.check.yaml+++ b/.github/workflows/py.check.yaml@@ -76,6 +76,12 @@ jobs:cd python/uv run nox -s chk+ - name: Example type checks+ shell: bash+ run: |+ cd python/+ uv run nox -s chk_examples+- name: Type inference testsshell: bashrun: |diff --git a/.gitignore b/.gitignoreindex e1572b91e..d20273ad8 100644--- a/.gitignore+++ b/.gitignore@@ -4,6 +4,8 @@ node_modules# outputoutdist+# wrangler deploy --dry-run --outdir, used by the examples' cf:dry-run script+dist-worker*.tgz# code coveragediff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 405e01566..009babb42 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -639,6 +639,9 @@ importers:'@cloudflare/vitest-pool-workers':specifier: 'catalog:'version: 0.20.1(@cloudflare/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])+ '@types/node':+ specifier: ^26.1.2+ version: 26.1.2typescript:specifier: 'catalog:'version: 7.0.2@@ -4098,9 +4101,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}- '@types/[email protected]':- resolution: {integrity: sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==}-'@types/[email protected]':resolution: {integrity: sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==}@@ -9564,10 +9564,6 @@ snapshots:dependencies:undici-types: 7.18.2- '@types/[email protected]':- dependencies:- undici-types: 8.3.0-'@types/[email protected]':dependencies:undici-types: 8.3.0@@ -9580,7 +9576,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 26.1.1+ '@types/node': 26.1.2'@types/[email protected]':dependencies:diff --git a/python/examples/README.md b/python/examples/README.mdnew file mode 100644index 000000000..9c5132818--- /dev/null+++ b/python/examples/README.md@@ -0,0 +1,34 @@+# Composio Python examples++Most scripts live directly in this directory (`tools.py`, `auth_configs.py`, `connected_accounts.py`, `triggers.py`, `mcp_example.py`, ...); the tool-router scripts group into the `tool_router/` subdirectory.++## Run one example++```bash+cd python+uv sync+out=$(node ../scripts/examples-provision.mjs) && eval "$out"+uv run python examples/tools.py+```++`uv run python examples/<file>.py` runs a script against the workspace's virtual environment without needing to activate it first. Scripts in subdirectories take their subpath too, e.g. `uv run python examples/tool_router/tools.py`.++## Configuration++Examples read configuration from environment variables and raise a `KeyError` naming the missing variable if one isn't set:++- `COMPOSIO_API_KEY` — always required.+- `COMPOSIO_EXAMPLES_USER_ID` — the user id examples act as.+- `COMPOSIO_EXAMPLES_{GMAIL,GITHUB,SLACK}_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_{GMAIL,GITHUB,SLACK}_CONNECTED_ACCOUNT_ID` — per-toolkit auth config and standing connected account.+- `COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER` — the serpapi API-key auth config and its placeholder key value.+- `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` — only needed by examples that call that LLM provider.++`node ../scripts/examples-provision.mjs` (run from `python/`, or `node scripts/examples-provision.mjs` from the repo root) checks a Composio project for this state, prints a report to stderr, and prints `export COMPOSIO_EXAMPLES_*=...` lines to stdout. Load them with `out=$(node ../scripts/examples-provision.mjs) && eval "$out"`. Capture first, then eval. `eval "$(...)"` reports the status of the text it evaluates, so it would hide a failed provisioning run. It's idempotent — it verifies what already exists and only creates what's missing — and it never prints credential values.++Add `--initiate-missing` to also start an OAuth connection request for any toolkit (gmail, googledrive, github, slack) that has no active connected account yet; it prints an authorization URL to visit once in a browser. The serpapi API-key auth config is created automatically, no browser step needed.++Run `node ../scripts/examples-provision.mjs --gc` to delete what example runs leave behind: connected accounts that never reached ACTIVE, surplus serpapi demo accounts, and MCP configs from earlier runs. It skips anything created in the last 24h and only touches resources the examples created. It deletes for real, so preview it with `--gc --dry-run` first and point it only at the disposable examples project.++## A note on connection examples++`connected_accounts.py` demonstrates _creating_ a connection: it calls `initiate()`, prints `Visit this URL to authorize: ...`, then calls `wait_for_connection()`, which returns once the account is active or gives up after its default timeout. That wait needs a person to open the URL, so the example cannot finish on its own and automated runs skip it. Examples that _use_ a connection (calling a tool through Gmail, GitHub, or Slack) rely on the standing connected accounts that the provisioning script already verified are active.diff --git a/python/examples/auth_configs.py b/python/examples/auth_configs.pyindex 4470c9a67..a982e675c 100644--- a/python/examples/auth_configs.py+++ b/python/examples/auth_configs.py@@ -16,7 +16,7 @@ auth_config = composio.auth_configs.create(print(auth_config)# Use custom auth-auth_config = composio.auth_configs.create(+auth_config = composio.auth_configs.create( # type: ignore[call-overload] # credentials TypedDict omits client_id/client_secret/oauth_redirect_uri; API accepts themtoolkit="notion",options={"name": "Notion Auth",@@ -50,7 +50,7 @@ required_input_fields = [print(required_input_fields)# Update an auth config-auth_config_updated = composio.auth_configs.update(+auth_config_updated = composio.auth_configs.update( # type: ignore[call-overload] # credentials TypedDict omits client_id/client_secret, which the API acceptsauth_config.id,options={"type": "custom",@@ -59,7 +59,7 @@ auth_config_updated = composio.auth_configs.update("client_secret": "1234567890",},"tool_access_config": {- "tools_for_connected_account_creation": ["github"],+ "tools_for_connected_account_creation": ["NOTION_ADD_PAGE_CONTENT"],},},)diff --git a/python/examples/connected_accounts.py b/python/examples/connected_accounts.pyindex 1c48eb4e6..20f35293c 100644--- a/python/examples/connected_accounts.py+++ b/python/examples/connected_accounts.py@@ -1,30 +1,42 @@+import os+from composio import Composiofrom composio.types import auth_schemecomposio = Composio()+# Auth config to connect against and the connecting user (raise KeyError when unset)+gmail_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"]+user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]+# List all connected accountsconnected_accounts = composio.connected_accounts.list()print(connected_accounts)-# Create a new connected account (OAuth)+# Create a new connected account (OAuth). The user may already have a+# connected account for this auth config, so allow another one.connection_request = composio.connected_accounts.initiate(- user_id="1234567890",- auth_config_id="1234567890",+ user_id=user_id,+ auth_config_id=gmail_auth_config_id,+ allow_multiple=True,)-print(connection_request)++# Send the user to this URL to authorize the connection+print(f"Visit this URL to authorize: {connection_request.redirect_url}")# Wait for the connection to be established (OAuth)connected_account = connection_request.wait_for_connection()-print(connected_account)+# Print identifying fields only: the full object carries live OAuth credentials.+print(f"Connected account {connected_account.id} is {connected_account.status}")# Create a new connected account (API Key)connection_request = composio.connected_accounts.initiate(- user_id="1234567890",- auth_config_id="1234567890",+ user_id=user_id,+ auth_config_id=os.environ["COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID"],+ allow_multiple=True,config=auth_scheme.api_key(- options={- "api_key": "1234567890",+ options={ # type: ignore[arg-type] # api_key() injects "status"; the field is Required on the generated TypedDict but not needed here+ "generic_api_key": os.environ["COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER"],},),)diff --git a/python/examples/custom_tools_agent_test.py b/python/examples/custom_tools_agent_test.pyindex 045da900d..6d2fa0b26 100644--- a/python/examples/custom_tools_agent_test.py+++ b/python/examples/custom_tools_agent_test.py@@ -21,7 +21,6 @@ from composio import Composiofrom composio_openai_agents import OpenAIAgentsProvidercomposio = Composio(- base_url=os.environ.get("COMPOSIO_BASE_URL"),provider=OpenAIAgentsProvider(),)@@ -164,20 +163,14 @@ async def run_test(prompt, test_name):async def main():+ # One test per custom-tool pattern: standalone, custom toolkit, extension.tests = [("Look up user-2", "Standalone (inferred slug/name)"),- ("Generate a formal greeting for Alice", "Standalone (overridden slug/name)"),("Set user-1 role to developer", "Toolkit tool"),- ("Look up user-1 and set their role to viewer", "Mixed local tools"),- ("What is the weather in Tokyo?", "Remote (weathermap)"),('Draft an email to [email protected] with subject "Test" and body "Hello!"',"Gmail proxy",),- (- "Look up user-1, draft them an email saying hi, include weather in SF",- "Mixed all",- ),]results = []@@ -192,6 +185,9 @@ async def main():print(f" [{'PASS' if ok else 'FAIL'}] {name}")print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")+ if not all(ok for _, ok in results):+ sys.exit(1)+if __name__ == "__main__":if not os.environ.get("OPENAI_API_KEY"):diff --git a/python/examples/experimental_tool_router_advanced_example.py b/python/examples/experimental_tool_router_advanced_example.pyindex 6e9b62e56..3734124c5 100644--- a/python/examples/experimental_tool_router_advanced_example.py+++ b/python/examples/experimental_tool_router_advanced_example.py@@ -5,18 +5,30 @@ This example shows various ways to configure tool router sessions withdifferent parameters matching the TypeScript implementation."""+import os+from composio import Composio# Initialize Composio SDKcomposio = Composio()+# Provisioned project state (raise KeyError when unset). Auth config and+# connected account ids are validated by the backend, so real ids are required.+user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]+github_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GITHUB_AUTH_CONFIG_ID"]+slack_auth_config_id = os.environ["COMPOSIO_EXAMPLES_SLACK_AUTH_CONFIG_ID"]+github_connected_account_id = os.environ[+ "COMPOSIO_EXAMPLES_GITHUB_CONNECTED_ACCOUNT_ID"+]+slack_connected_account_id = os.environ["COMPOSIO_EXAMPLES_SLACK_CONNECTED_ACCOUNT_ID"]+def example_with_specific_toolkits():"""Create a session with specific toolkits enabled."""print("=== Specific Toolkits Example ===")session = composio.tool_router.create(- user_id="user_toolkit", toolkits=["github", "slack", "linear"]+ user_id=user_id, toolkits=["github", "slack", "linear"])print(f"Session ID: {session.session_id}")@@ -29,7 +41,7 @@ def example_with_disabled_toolkits():print("\n=== Disabled Toolkits Example ===")session = composio.tool_router.create(- user_id="user_disabled", toolkits={"disabled": ["linear", "jira"]}+ user_id=user_id, toolkits={"disable": ["linear", "jira"]})print(f"Session ID: {session.session_id}")@@ -42,10 +54,10 @@ def example_with_connection_management_config():print("\n=== Connection Management with Callback Example ===")session = composio.tool_router.create(- user_id="user_callback",+ user_id=user_id,manage_connections={- "enabled": True,- "callback_uri": "https://myapp.com/oauth/callback",+ "enable": True,+ "callback_url": "https://myapp.com/oauth/callback",},)@@ -59,13 +71,15 @@ def example_with_auth_configs():print("\n=== Auth Configs Example ===")session = composio.tool_router.create(- user_id="user_auth",+ user_id=user_id,toolkits=["github", "slack"],- auth_configs={"github": "ac_github_123", "slack": "ac_slack_456"},+ auth_configs={"github": github_auth_config_id, "slack": slack_auth_config_id},)print(f"Session ID: {session.session_id}")- print("Auth configs: github → ac_github_123, slack → ac_slack_456")+ print(+ f"Auth configs: github → {github_auth_config_id}, slack → {slack_auth_config_id}"+ )return session@@ -74,13 +88,19 @@ def example_with_connected_accounts():print("\n=== Connected Accounts Example ===")session = composio.tool_router.create(- user_id="user_connected",+ user_id=user_id,toolkits=["github", "slack"],- connected_accounts={"github": "ca_github_789", "slack": "ca_slack_012"},+ connected_accounts={+ "github": github_connected_account_id,+ "slack": slack_connected_account_id,+ },)print(f"Session ID: {session.session_id}")- print("Connected accounts: github → ca_github_789, slack → ca_slack_012")+ print(+ f"Connected accounts: github → {github_connected_account_id}, "+ f"slack → {slack_connected_account_id}"+ )return session@@ -89,24 +109,26 @@ def example_with_all_parameters():print("\n=== All Parameters Example ===")session = composio.tool_router.create(- user_id="user_complete",- toolkits=["github", "slack", "notion"],+ user_id=user_id,+ toolkits=["github", "slack"],manage_connections={- "enabled": True,- "callback_uri": "https://myapp.com/callback",+ "enable": True,+ "callback_url": "https://myapp.com/callback",},auth_configs={- "github": "ac_github_xyz",- "slack": "ac_slack_abc",- "notion": "ac_notion_def",+ "github": github_auth_config_id,+ "slack": slack_auth_config_id,+ },+ connected_accounts={+ "github": github_connected_account_id,+ "slack": slack_connected_account_id,},- connected_accounts={"github": "ca_github_111", "slack": "ca_slack_222"},)print(f"✓ Session ID: {session.session_id}")- print("✓ Toolkits: github, slack, notion")+ print("✓ Toolkits: github, slack")print("✓ Connection management: enabled with callback")- print("✓ Auth configs: configured for 3 toolkits")+ print("✓ Auth configs: configured for 2 toolkits")print("✓ Connected accounts: 2 pre-configured")return session@@ -117,16 +139,16 @@ def example_minimal_vs_maximal():print("\n=== Minimal vs Maximal Example ===")# Minimal - just user ID- minimal_session = composio.tool_router.create(user_id="user_minimal")+ minimal_session = composio.tool_router.create(user_id=user_id)print(f"Minimal session: {minimal_session.session_id}")# Maximal - all optionsmaximal_session = composio.tool_router.create(- user_id="user_maximal",+ user_id=user_id,toolkits=["github", "slack"],- manage_connections={"enabled": True, "callback_uri": "https://app.com/cb"},- auth_configs={"github": "ac_1", "slack": "ac_2"},- connected_accounts={"github": "ca_1"},+ manage_connections={"enable": True, "callback_url": "https://app.com/cb"},+ auth_configs={"github": github_auth_config_id, "slack": slack_auth_config_id},+ connected_accounts={"github": github_connected_account_id},)print(f"Maximal session: {maximal_session.session_id}")@@ -139,21 +161,20 @@ def example_type_safe_configuration():from composio.core.models.tool_router import (ToolRouterManageConnectionsConfig,- ToolRouterToolkitsDisabledConfig,+ ToolRouterToolkitsDisableConfig,)# Type-safe toolkit config- toolkit_config: ToolRouterToolkitsDisabledConfig = {"disabled": ["linear", "asana"]}+ toolkit_config: ToolRouterToolkitsDisableConfig = {"disable": ["linear", "asana"]}# Type-safe connection management configconnection_config: ToolRouterManageConnectionsConfig = {- "enabled": True,- "callback_uri": "https://secure.app.com/oauth",- "infer_scopes_from_tools": False,+ "enable": True,+ "callback_url": "https://secure.app.com/oauth",}session = composio.tool_router.create(- user_id="user_typesafe",+ user_id=user_id,toolkits=toolkit_config,manage_connections=connection_config,)@@ -184,6 +205,4 @@ if __name__ == "__main__":except Exception as e:print(f"\n✗ Error running examples: {e}")- import traceback-- traceback.print_exc()+ raisediff --git a/python/examples/experimental_tool_router_example.py b/python/examples/experimental_tool_router_example.pyindex 4600b7356..f5cda451a 100644--- a/python/examples/experimental_tool_router_example.py+++ b/python/examples/experimental_tool_router_example.py@@ -5,21 +5,27 @@ This example shows how to create a tool router session for a user,get provider-wrapped tools, and authorize toolkits."""+import os+from composio import Composio# Initialize Composio SDKcomposio = Composio()+# Provisioned project state (raises KeyError when unset). The backend validates+# auth config ids, so a placeholder would abort session creation.+user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]+github_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GITHUB_AUTH_CONFIG_ID"]+# Example 1: Create a basic tool router sessiondef basic_session_example():"""Create a basic tool router session."""print("=== Basic Session Example ===")- user_id = "user_123"-- # Create a tool router session- session = composio.tool_router.create(user_id=user_id)+ # Create a tool router session. mcp=True surfaces session.mcp on the+ # returned type; without it the endpoint exists but is not typed.+ session = composio.tool_router.create(user_id=user_id, mcp=True)print(f"Session ID: {session.session_id}")print(f"MCP Server Type: {session.mcp.type}")@@ -39,8 +45,6 @@ def session_with_connections_example():"""Create a session with connection management enabled."""print("\n=== Session with Connection Management ===")- user_id = "user_456"-# Create a tool router session with connection managementsession = composio.tool_router.create(user_id=user_id, manage_connections=True)@@ -61,8 +65,6 @@ def authorize_toolkit_example():"""Demonstrate toolkit authorization."""print("\n=== Authorize Toolkit Example ===")- user_id = "user_789"-# Create a sessionsession = composio.tool_router.create(user_id=user_id)@@ -80,7 +82,7 @@ def authorize_toolkit_example():return connection_requestexcept Exception as e:print(f"Error authorizing toolkit: {e}")- return None+ raise# Example 4: Get toolkit connection states@@ -88,8 +90,6 @@ def get_toolkits_example():"""Get toolkit connection states for a session."""print("\n=== Get Toolkits Example ===")- user_id = "user_101"-# Create a sessionsession = composio.tool_router.create(user_id=user_id)@@ -106,14 +106,12 @@ def full_workflow_example():"""Complete workflow with session, tools, and authorization."""print("\n=== Full Workflow Example ===")- user_id = "user_full"-# 1. Create session with multiple configurationssession = composio.tool_router.create(user_id=user_id,toolkits=["github", "slack"],manage_connections=True,- auth_configs={"github": "ac_demo_123"},+ auth_configs={"github": github_auth_config_id},)print(f"✓ Created session: {session.session_id}")@@ -135,6 +133,7 @@ def full_workflow_example():print(f" → Redirect URL: {connection_request.redirect_url}")except Exception as e:print(f"✗ Authorization error: {e}")+ raisereturn session@@ -144,18 +143,14 @@ def session_with_modifiers_example():"""Create a session and use tools with custom modifiers."""print("\n=== Session with Modifiers Example ===")- user_id = "user_modifiers"-# Create sessionsession = composio.tool_router.create(user_id=user_id)- # Get tools with custom modifiers- modifiers = {- # Add any custom modifiers here- # Example: timeout, custom headers, etc.- }+ # Modifiers are a list of before/after execute hooks; an empty list means+ # "no modifiers", which is what this example passes.+ modifiers: list = []- tools = session.tools(modifiers=modifiers if modifiers else None)+ tools = session.tools(modifiers=modifiers or None)print(f"✓ Retrieved {len(tools) if isinstance(tools, list) else 'N/A'} tools with modifiers")@@ -182,6 +177,4 @@ if __name__ == "__main__":except Exception as e:print(f"\n✗ Error running examples: {e}")- import traceback-- traceback.print_exc()+ raisediff --git a/python/examples/fastapi_app.py b/python/examples/fastapi_app.pyindex f9cfa796e..8862df23b 100644--- a/python/examples/fastapi_app.py+++ b/python/examples/fastapi_app.py@@ -1,3 +1,5 @@+import os+from fastapi import FastAPIfrom fastapi.responses import RedirectResponse@@ -13,10 +15,10 @@ composio = Composio()@app.get("/authorize/{toolkit}")def authorize_app(toolkit: str):# retrieve the user id from your app- user_id = ""+ user_id = os.environ.get("COMPOSIO_EXAMPLES_USER_ID", "")# retrieve the auth config id from your app- auth_config_id = ""+ auth_config_id = os.environ.get("COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID", "")# initiate the connection requestconnection_request = composio.connected_accounts.initiate(@@ -24,3 +26,16 @@ def authorize_app(toolkit: str):auth_config_id=auth_config_id,)return RedirectResponse(url=connection_request.redirect_url) # type: ignore+++if __name__ == "__main__":+ import uvicorn++ for var in ("COMPOSIO_EXAMPLES_USER_ID", "COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"):+ if not os.environ.get(var):+ raise SystemExit(f"{var} is required")++ # Fail fast on bad credentials or a stale auth config before serving requests+ composio.auth_configs.get(os.environ["COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"])++ uvicorn.run(app, host="127.0.0.1", port=8000)diff --git a/python/examples/mcp.py b/python/examples/mcp.pydeleted file mode 100644index 5b0c26409..000000000--- a/python/examples/mcp.py+++ /dev/null@@ -1,34 +0,0 @@-import asyncio--from langchain_mcp_adapters.client import MultiServerMCPClient-from langgraph.prebuilt import create_react_agent--from composio import Composio--composio = Composio()--mcp_config = composio.mcp.create(- name="langchain-slack-mcp",- toolkits=[{"toolkit": "slack", "auth_config_id": "<auth-config-id>"}],-)--mcp_server = mcp_config.generate(user_id="<user-id>")--client = MultiServerMCPClient(- {- "composio": {- "url": mcp_server["url"],- "transport": "streamable_http",- }- }-)---async def langchain_mcp(message: str):- tools = await client.get_tools()- agent = create_react_agent("openai:gpt-4.1", tools)- response = await agent.ainvoke({"messages": message})- return response---mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))diff --git a/python/examples/mcp_example.py b/python/examples/mcp_example.pynew file mode 100644index 000000000..95fb4f461--- /dev/null+++ b/python/examples/mcp_example.py@@ -0,0 +1,47 @@+import asyncio+import os+import time++from langchain_mcp_adapters.client import MultiServerMCPClient+from langgraph.prebuilt import create_react_agent++from composio import Composio++composio = Composio()++# Slack auth config and user id (raise KeyError when unset)+slack_auth_config_id = os.environ["COMPOSIO_EXAMPLES_SLACK_AUTH_CONFIG_ID"]+user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]++mcp_config = composio.mcp.create(+ # Named `examples-<label>-<unix-seconds>` so the provisioning script's --gc+ # can tell this throwaway config from one created by hand. The API caps+ # this name at 30 characters, so the label stays short.+ name=f"examples-lc-slack-{int(time.time())}",+ toolkits=[{"toolkit": "slack", "auth_config_id": slack_auth_config_id}],+ # Keep the exposed tool list small; LLM providers cap tools per request+ allowed_tools=["SLACK_LIST_ALL_CHANNELS", "SLACK_SEARCH_MESSAGES"],+)++mcp_server = mcp_config.generate(user_id=user_id) # type: ignore[call-arg] # generate is typed as a bare Callable; runtime accepts the user_id keyword++client = MultiServerMCPClient(+ {+ "composio": {+ "url": mcp_server["url"],+ "transport": "streamable_http",+ # The MCP endpoint authenticates with your Composio API key+ "headers": {"x-api-key": os.environ["COMPOSIO_API_KEY"]},+ }+ }+)+++async def langchain_mcp(message: str):+ tools = await client.get_tools()+ agent = create_react_agent("openai:gpt-4.1", tools)+ response = await agent.ainvoke({"messages": message})+ return response+++mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))diff --git a/python/examples/tool_router/claude_agent.py b/python/examples/tool_router/claude_agent.pyindex e7c584d18..0994722be 100644--- a/python/examples/tool_router/claude_agent.py+++ b/python/examples/tool_router/claude_agent.py@@ -1,4 +1,5 @@import asyncio+import osfrom claude_agent_sdk import ClaudeAgentOptions, queryfrom composio_claude_agent_sdk import ClaudeAgentSDKProvider@@ -7,7 +8,10 @@ from composio import Composiocomposio = Composio(provider=ClaudeAgentSDKProvider())session = composio.create(- user_id="user_123",+ # A user with a connected Gmail account (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)diff --git a/python/examples/tool_router/crewai_agent.py b/python/examples/tool_router/crewai_agent.pyindex 33e4c5a4c..a90d3ae72 100644--- a/python/examples/tool_router/crewai_agent.py+++ b/python/examples/tool_router/crewai_agent.py@@ -1,3 +1,5 @@+import os+from crewai import Agent, Crew, Taskfrom crewai.mcp import MCPServerHTTP@@ -5,7 +7,10 @@ from composio import Composiocomposio = Composio()session = composio.create(- user_id="user_123",+ # A user with a connected Gmail account (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)agent = Agent(@@ -15,7 +20,7 @@ agent = Agent(mcps=[MCPServerHTTP(url=session.mcp.url,- headers=session.mcp.headers,+ headers=session.mcp.headers, # type: ignore[arg-type] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values)],)diff --git a/python/examples/tool_router/direct_tools_preset.py b/python/examples/tool_router/direct_tools_preset.pyindex b5f8b7656..503ed4069 100644--- a/python/examples/tool_router/direct_tools_preset.py+++ b/python/examples/tool_router/direct_tools_preset.py@@ -27,7 +27,6 @@ def require_env(name: str) -> str:composio = Composio(api_key=require_env("COMPOSIO_API_KEY"),- base_url=os.environ.get("COMPOSIO_BASE_URL"),provider=OpenAIAgentsProvider(),)require_env("OPENAI_API_KEY")diff --git a/python/examples/tool_router/langchain_agent.py b/python/examples/tool_router/langchain_agent.pyindex b8e8bb765..1a6cd2c76 100644--- a/python/examples/tool_router/langchain_agent.py+++ b/python/examples/tool_router/langchain_agent.py@@ -1,4 +1,5 @@import asyncio+import osfrom langchain.agents import create_agentfrom langchain_mcp_adapters.client import MultiServerMCPClient@@ -8,40 +9,40 @@ from composio import Composiocomposio = Composio()session = composio.create(- user_id="user_123",+ # A user with a connected Gmail account (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)async def main():- try:- mcp_client = MultiServerMCPClient(- {- "composio": {- "transport": "streamable_http",- "url": session.mcp.url,- "headers": session.mcp.headers,- }+ mcp_client = MultiServerMCPClient(+ {+ "composio": {+ "transport": "streamable_http",+ "url": session.mcp.url,+ "headers": session.mcp.headers,}- )+ }+ )- tools = await mcp_client.get_tools()+ tools = await mcp_client.get_tools()- agent = create_agent(- tools=tools,- model=ChatOpenAI(model="gpt-4o"),- )+ agent = create_agent(+ tools=tools,+ model=ChatOpenAI(model="gpt-4o"),+ )- result = await agent.ainvoke(- {- "messages": [- {"role": "user", "content": "Fetch my last email and summarize?"}- ]- }- )+ result = await agent.ainvoke(+ {+ "messages": [+ {"role": "user", "content": "Fetch my last email and summarize?"}+ ]+ }+ )- print(result)- except Exception as e:- print(e)+ print(result)if __name__ == "__main__":diff --git a/python/examples/tool_router/openai_agents.py b/python/examples/tool_router/openai_agents.pyindex 37b248990..79eab418a 100644--- a/python/examples/tool_router/openai_agents.py+++ b/python/examples/tool_router/openai_agents.py@@ -1,10 +1,15 @@+import os+from agents import Agent, HostedMCPTool, Runnerfrom composio import Composiocomposio = Composio()session = composio.create(- user_id="user_123",+ # A user with a connected Gmail account (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)print(session.mcp)@@ -15,7 +20,7 @@ composio_mcp = HostedMCPTool("server_label": "tool_router","server_url": session.mcp.url,"require_approval": "never",- "headers": session.mcp.headers,+ "headers": session.mcp.headers, # type: ignore[typeddict-item] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values})diff --git a/python/examples/tool_router/preload.py b/python/examples/tool_router/preload.pyindex c9325c561..1c7aeed4d 100644--- a/python/examples/tool_router/preload.py+++ b/python/examples/tool_router/preload.py@@ -58,7 +58,6 @@ INTERNAL_USERS = {composio = Composio(api_key=require_env("COMPOSIO_API_KEY"),- base_url=os.environ.get("COMPOSIO_BASE_URL"),provider=OpenAIAgentsProvider(),)require_env("OPENAI_API_KEY")diff --git a/python/examples/tool_router/session_update.py b/python/examples/tool_router/session_update.pyindex 543227448..ae88618c0 100644--- a/python/examples/tool_router/session_update.py+++ b/python/examples/tool_router/session_update.py@@ -10,11 +10,12 @@ import osfrom composio import Composio-composio = Composio(base_url=os.environ.get("COMPOSIO_BASE_URL"))+composio = Composio()# Create a session with gmail onlysession = composio.create(- user_id="session-update-demo",+ # The provisioned examples user (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],toolkits=["gmail"],manage_connections=False,)diff --git a/python/examples/tool_router/tool_router_mcp.py b/python/examples/tool_router/tool_router_mcp.pyindex 0287e69e6..79998b337 100644--- a/python/examples/tool_router/tool_router_mcp.py+++ b/python/examples/tool_router/tool_router_mcp.py@@ -28,8 +28,11 @@ async def main():# Create a tool router sessionsession = composio.create(- user_id="user_123",+ # A user with connected GitHub and Gmail accounts (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],toolkits=["github", "gmail"],+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)mcpTool = HostedMCPTool(@@ -38,7 +41,7 @@ async def main():"server_label": "tool_router","server_url": session.mcp.url,"require_approval": "never",- "headers": session.mcp.headers,+ "headers": session.mcp.headers, # type: ignore[typeddict-item] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values})diff --git a/python/examples/tool_router/toolkits.py b/python/examples/tool_router/toolkits.pyindex a87b470af..931c615f7 100644--- a/python/examples/tool_router/toolkits.py+++ b/python/examples/tool_router/toolkits.py@@ -5,6 +5,8 @@ This example demonstrates how to retrieve available toolkitsand their connection status in a Tool Router session."""+import os+from composio import Composiocomposio = Composio()@@ -12,8 +14,11 @@ composio = Composio()# Create a tool router session# When manage_connections is enabled, tools for managing connections are includedsession = composio.create(- user_id="pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b",+ # The provisioned examples user (raises KeyError when unset)+ user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],manage_connections=True,+ # mcp=True surfaces session.mcp on the returned type+ mcp=True,)print(f"Session created: {session.session_id}")diff --git a/python/examples/tools.py b/python/examples/tools.pyindex 21c97507b..4861a8efc 100644--- a/python/examples/tools.py+++ b/python/examples/tools.py@@ -1,7 +1,14 @@+import os+from composio import Composiocomposio = Composio()+# Connected account with GitHub access (raises KeyError when unset)+github_connected_account_id = os.environ[+ "COMPOSIO_EXAMPLES_GITHUB_CONNECTED_ACCOUNT_ID"+]+# Get all tools by toolkittools = composio.tools.get(user_id="default", toolkits=["GITHUB"])@@ -24,7 +31,7 @@ print(response)proxy_response = composio.tools.proxy(endpoint="/repos/composiohq/composio/issues/1",method="GET",- connected_account_id="ac_1234", # use connected account for github+ connected_account_id=github_connected_account_id, # use connected account for githubparameters=[{"name": "Accept",diff --git a/python/examples/triggers.py b/python/examples/triggers.pyindex 144630f35..795563398 100644--- a/python/examples/triggers.py+++ b/python/examples/triggers.py@@ -1,7 +1,13 @@+import os+from composio import Composiocomposio = Composio()+# Connected account with Gmail access and its owner (raise KeyError when unset)+gmail_connected_account_id = os.environ["COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID"]+user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]+# List all triggerstriggers = composio.triggers.list()@@ -16,41 +22,35 @@ trigger_enums = composio.triggers.list_enum()print(trigger_enums)# Get a trigger by id-trigger = composio.triggers.get_type(slug="GITHUB_COMMIT_EVENT")+trigger = composio.triggers.get_type(slug="GMAIL_NEW_GMAIL_MESSAGE")print(trigger)-# Create a trigger instance+# Create a trigger instance pinned to a connected accountinstance = composio.triggers.create(- slug="GITHUB_COMMIT_EVENT",- connected_account_id="123",- trigger_config={- "repo": "composio",- "owner": "composiohq",- },+ slug="GMAIL_NEW_GMAIL_MESSAGE",+ connected_account_id=gmail_connected_account_id,+ trigger_config={},)print(instance)-# Or use user ID+# Or use user ID and let the backend resolve the active connectioninstance = composio.triggers.create(- slug="GITHUB_COMMIT_EVENT",- user_id="[email protected]",- trigger_config={- "repo": "composio",- "owner": "composiohq",- },+ slug="GMAIL_NEW_GMAIL_MESSAGE",+ user_id=user_id,+ trigger_config={},)print(instance)# Disable a trigger instance-disabled_instance = composio.triggers.disable(trigger_id="123")+disabled_instance = composio.triggers.disable(trigger_id=instance.trigger_id)print(disabled_instance)# Enable a trigger instance-enabled_instance = composio.triggers.enable(trigger_id="123")+enabled_instance = composio.triggers.enable(trigger_id=instance.trigger_id)print(enabled_instance)# Delete a trigger instance-deleted_instance = composio.triggers.delete(trigger_id="123")+deleted_instance = composio.triggers.delete(trigger_id=instance.trigger_id)print(deleted_instance)@@ -92,4 +92,5 @@ def handle_slack_event(data):print(data)+print("Subscribed to triggers. Waiting for events...", flush=True)subscription.wait_forever()diff --git a/python/noxfile.py b/python/noxfile.pyindex d94e5ed58..8372ef2af 100644--- a/python/noxfile.py+++ b/python/noxfile.py@@ -75,6 +75,31 @@ def fix(session: Session):session.run(*ruff, "check", "--fix", *modules_for_ruff)+def chk_examples(session: Session):+ """Type-check example scripts against the SDK surface.++ Examples run one mypy invocation per file: duplicate basenames+ (examples/tools.py, examples/tool_router/tools.py) collide as module+ names inside a single run. Third-party agent frameworks stay+ unresolved on purpose; the check targets composio API usage.+ """+ from pathlib import Path++ session.install(".", "--group", "dev", mypy, *type_stubs)+ for path in sorted(Path("examples").rglob("*.py")):+ session.run(+ "mypy",+ "--config-file",+ "config/mypy.ini",+ "--ignore-missing-imports",+ # Examples wrap their bodies in unannotated main()s; without this+ # mypy skips those bodies entirely and the gate checks almost nothing.+ "--check-untyped-defs",+ str(path),+ )++@nox.sessiondef tst(session: Session):"""Run the Python unit test suite."""diff --git a/scripts/examples-provision.mjs b/scripts/examples-provision.mjsnew file mode 100644index 000000000..275955164--- /dev/null+++ b/scripts/examples-provision.mjs@@ -0,0 +1,314 @@+#!/usr/bin/env node+// Idempotent provisioning check for the live example runs.+//+// Verifies that the dedicated (disposable) Composio project holds the auth+// configs and connected accounts the tier-2/3 examples need, creates whatever+// can be created without a human (API-key auth config), and+// prints the remaining one-time OAuth authorizations.+//+// node scripts/examples-provision.mjs # report (stderr) + exports (stdout)+// out=$(node scripts/examples-provision.mjs) && eval "$out"+// load COMPOSIO_EXAMPLES_* into the shell. Do NOT collapse this into+// eval "$(...)": eval reports the status of the text it evaluates, so a+// failed provisioning run would look like success.+// node scripts/examples-provision.mjs --initiate-missing+// also starts an OAuth connection request for each missing account and+// prints the redirect URL to authorize it (one browser visit per toolkit)+// node scripts/examples-provision.mjs --gc [--dry-run]+// DESTRUCTIVE. Deletes resources example runs leak into the project:+// connected accounts that never became ACTIVE, surplus serpapi demo+// accounts, and MCP configs named `examples-<label>-<unix-seconds>`,+// which is the name every example gives the configs it creates.+// Configs from runs predating that convention are not matched.+// Connected accounts are only ever deleted when they are bound to an+// `examples-<slug>` auth config, which only this script creates. An+// account the examples did not create is never touched, whatever user+// owns it. Only resources older than 24h are removed, so a concurrent run+// is safe. Preview with --dry-run.+//+// Auth config ids and connected account ids are not secrets; no credential+// values are ever printed. The API-key demo value stored for serpapi is a+// deliberately fake placeholder, not a real key.++const BASE_URL = process.env.COMPOSIO_BASE_URL ?? 'https://backend.composio.dev';+const API_KEY = process.env.COMPOSIO_API_KEY;+const USER_ID = process.env.COMPOSIO_EXAMPLES_USER_ID ?? 'examples';+const INITIATE_MISSING = process.argv.includes('--initiate-missing');+const GC = process.argv.includes('--gc');+const DRY_RUN = process.argv.includes('--dry-run');++// The examples only ever run against the production backend with the+// disposable project key. Allowlist the Composio hosts rather than denylisting+// loopback spellings: the API key travels in every request, so anything that is+// not a Composio backend must be refused, not just localhost.+const { baseHost, baseProtocol } = (() => {+ try {+ const url = new URL(BASE_URL);+ return { baseHost: url.hostname, baseProtocol: url.protocol };+ } catch {+ return { baseHost: null, baseProtocol: null };+ }+})();+if (!baseHost || !(baseHost === 'composio.dev' || baseHost.endsWith('.composio.dev'))) {+ console.error(`refusing non-Composio COMPOSIO_BASE_URL: ${BASE_URL}`);+ process.exit(1);+}+if (baseProtocol !== 'https:') {+ // The API key is sent on every request. Plain http would put it on the wire.+ console.error(`refusing non-https COMPOSIO_BASE_URL: ${BASE_URL}`);+ process.exit(1);+}+if (!API_KEY) {+ console.error('COMPOSIO_API_KEY is required (dedicated examples-project key)');+ process.exit(1);+}++// Toolkits the tier-2/3 entries depend on. OAuth toolkits need a one-time human+// browser authorization. Only export ids that examples consume directly.+const BROWSER_GRANT_TOOLKITS = [+ { exportPrefix: 'GMAIL', slug: 'gmail' },+ // googledrive exports nothing: examples reach Drive through the user's+ // standing connection (COMPOSIO_EXAMPLES_USER_ID), never through ids.+ { slug: 'googledrive' },+ { exportPrefix: 'GITHUB', slug: 'github' },+ { exportPrefix: 'SLACK', slug: 'slack' },+];+const DEMO_TOOLKIT = { exportPrefix: 'APIKEY', slug: 'serpapi', demoValue: 'examples-demo-key' };++const report = line => console.error(line);++async function api(method, path, body) {+ const res = await fetch(`${BASE_URL}${path}`, {+ method,+ headers: { 'x-api-key': API_KEY, 'content-type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ // Without this a hung backend hangs the whole run instead of failing it.+ signal: AbortSignal.timeout(30_000),+ // The host allowlist above only checks BASE_URL. fetch follows redirects by+ // default and forwards x-api-key across origins (only Authorization is+ // stripped), so a 3xx would hand the key to whatever host it names.+ redirect: 'error',+ });+ const text = await res.text();+ if (!res.ok) {+ throw new Error(`${method} ${path} -> ${res.status}: ${text.slice(0, 300)}`);+ }+ return text ? JSON.parse(text) : undefined;+}++// Two pagination shapes are in play. Most v3.1 collections (auth_configs,+// connected_accounts) return `next_cursor`; /mcp/servers never does and reports+// current_page/total_pages instead. Follow whichever the response actually+// offers, otherwise the MCP cleanup silently stops after one page.+const MAX_PAGES = 50;++async function listAll(path, key = 'items') {+ const out = [];+ let cursor;+ let pageNo = 1;+ for (let page = 0; page < MAX_PAGES; page++) {+ const sep = path.includes('?') ? '&' : '?';+ let query = 'limit=100';+ if (cursor) query += `&cursor=${encodeURIComponent(cursor)}`;+ else if (pageNo > 1) query += `&page_no=${pageNo}`;++ const data = await api('GET', `${path}${sep}${query}`);+ out.push(...(data?.[key] ?? []));++ if (data?.next_cursor) {+ if (data.next_cursor === cursor) {+ report(`warning: ${path} repeated cursor ${cursor}; stopping to avoid a loop`);+ return out;+ }+ cursor = data.next_cursor;+ continue;+ }++ const totalPages = Number(data?.total_pages);+ const currentPage = Number(data?.current_page ?? pageNo);+ if (Number.isFinite(totalPages) && Number.isFinite(currentPage) && currentPage < totalPages) {+ // Clear the cursor before falling back to page numbers. Leaving it set+ // would resend the same cursor every iteration and repeat one page until+ // the page cap.+ cursor = undefined;+ pageNo = currentPage + 1;+ continue;+ }+ return out;+ }+ report(`warning: stopped paginating ${path} after ${MAX_PAGES} pages; results may be incomplete`);+ return out;+}++const [authConfigs, accounts] = await Promise.all([+ listAll('/api/v3.1/auth_configs'),+ listAll(`/api/v3.1/connected_accounts?user_ids=${encodeURIComponent(USER_ID)}`),+]);++if (GC) {+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;+ // Fail closed: a missing or unparseable created_at must not read as "old+ // enough to delete", which `new Date(0)` would.+ const stale = r => {+ const created = new Date(r.created_at ?? '').getTime();+ return Number.isFinite(created) && created < cutoff;+ };+ const gcDelete = async (kind, path, item) => {+ const label = `${kind} ${item.id} (${item.toolkit?.slug ?? item.name}, created ${item.created_at})`;+ if (DRY_RUN) {+ report(`gc: would delete ${label}`);+ return;+ }+ await api('DELETE', path);+ report(`gc: deleted ${label}`);+ };++ // Ownership marker: this script is the only thing that creates auth configs+ // named `examples-<slug>`, so an account bound to one of them was created by+ // an example run. Match the name exactly. findAuthConfig's fallback to any+ // config for the toolkit is fine for reading, but must never authorise a+ // delete, or a project's own gmail config would look example-owned.+ // Keying on the auth config rather than the user id matters: some examples+ // connect as 'default' rather than COMPOSIO_EXAMPLES_USER_ID.+ const ownedNames = new Set(+ [...BROWSER_GRANT_TOOLKITS, DEMO_TOOLKIT].map(({ slug }) => `examples-${slug}`)+ );+ const ownedAuthConfigIds = new Set(+ authConfigs.filter(c => ownedNames.has(c.name)).map(c => c.id)+ );+ const isExampleOwned = a => ownedAuthConfigIds.has(a.auth_config?.id);++ if (ownedAuthConfigIds.size === 0) {+ report('gc: no examples-* auth configs in this project; skipping account cleanup');+ }++ // Among example-created accounts only: ones that never became ACTIVE are dead+ // weight from OAuth-initiating runs, and surplus serpapi demo accounts pile up+ // from api-key runs. The newest standing account per toolkit is never touched.+ const allAccounts = (await listAll('/api/v3.1/connected_accounts')).filter(isExampleOwned);+ const serpapiActive = allAccounts+ .filter(a => a.toolkit?.slug === 'serpapi' && a.status === 'ACTIVE')+ .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));+ const doomedAccounts = [+ ...allAccounts.filter(a => a.status !== 'ACTIVE' && stale(a)),+ ...serpapiActive.slice(1).filter(stale),+ ];+ for (const account of doomedAccounts) {+ await gcDelete('connected account', `/api/v3.1/connected_accounts/${account.id}`, account);+ }++ // Example runs name their MCP configs `examples-<label>-<unix-seconds>`.+ // Both halves are load-bearing. The reserved `examples-` prefix is what proves+ // an example created it, and the trailing timestamp keeps a hand-made+ // `examples-scratch` out of the delete set. Matching a bare trailing digit run+ // instead would also claim names like `release-1754923456`. Seconds, not+ // milliseconds: the API caps MCP names at 30 characters.+ const EXAMPLE_MCP_NAME = /^examples-[a-z0-9-]+-\d{10}$/;+ const mcpServers = await listAll('/api/v3.1/mcp/servers');+ for (const server of mcpServers.filter(s => EXAMPLE_MCP_NAME.test(s.name ?? '') && stale(s))) {+ await gcDelete('mcp config', `/api/v3.1/mcp/${server.id}`, server);+ }+}++const exports = { COMPOSIO_EXAMPLES_USER_ID: USER_ID };+const pendingGrants = [];+let ok = true;++function findAuthConfig(slug) {+ // Only the exactly-named config counts. Adopting a project's own config for+ // the same toolkit would bind example-created accounts to a config --gc does+ // not recognise, so they could never be cleaned up, and it would point the+ // examples at credentials the examples do not own.+ return authConfigs.find(+ c => c.toolkit?.slug === slug && c.status !== 'DISABLED' && c.name === `examples-${slug}`+ );+}+function findActiveAccount(slug, authConfigId) {+ // Must agree with findAuthConfig. Accepting any ACTIVE account for the toolkit+ // would pair a freshly created examples-<slug> config with an account bound to+ // a different one, report the run complete, and leave the examples-owned+ // config with no connection --initiate-missing would ever create.+ return accounts.find(+ a => a.toolkit?.slug === slug && a.status === 'ACTIVE' && a.auth_config?.id === authConfigId+ );+}++for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {+ let config = findAuthConfig(slug);+ if (!config) {+ const created = await api('POST', '/api/v3.1/auth_configs', {+ toolkit: { slug },+ auth_config: { type: 'use_composio_managed_auth', name: `examples-${slug}` },+ });+ config = { id: created.auth_config?.id ?? created.id };+ report(`created auth config for ${slug}: ${config.id}`);+ }+ if (exportPrefix) {+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;+ }++ const account = findActiveAccount(slug, config.id);+ if (account) {+ if (exportPrefix) {+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_CONNECTED_ACCOUNT_ID`] = account.id;+ }+ report(`${slug}: ACTIVE connection ${account.id} (user ${USER_ID})`);+ } else {+ ok = false;+ if (INITIATE_MISSING) {+ const created = await api('POST', '/api/v3.1/connected_accounts', {+ auth_config: { id: config.id },+ connection: { user_id: USER_ID },+ });+ pendingGrants.push(+ `${slug}: authorize in a browser -> ${created.connectionData?.val?.redirectUrl ?? created.redirect_url ?? created.redirect_uri ?? '(no redirect url returned)'}`+ );+ } else {+ pendingGrants.push(+ `${slug}: no ACTIVE connection for user ${USER_ID} — rerun with --initiate-missing to get an authorization URL`+ );+ }+ }+}++// API-key toolkit: create the auth config automatically. The examples create+// their own connected accounts to demonstrate that API. The stored value is a+// placeholder; serpapi only validates it at tool-execution time and no example+// executes a serpapi tool.+{+ const { exportPrefix, slug, demoValue } = DEMO_TOOLKIT;+ let config = findAuthConfig(slug);+ if (!config) {+ const created = await api('POST', '/api/v3.1/auth_configs', {+ toolkit: { slug },+ auth_config: { type: 'use_custom_auth', authScheme: 'API_KEY', name: `examples-${slug}` },+ });+ config = { id: created.auth_config?.id ?? created.id };+ report(`created API-key auth config for ${slug}: ${config.id}`);+ }+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;+ exports[`COMPOSIO_EXAMPLES_${exportPrefix}_PLACEHOLDER`] = demoValue;+}++if (pendingGrants.length) {+ report('');+ report('OAuth connections still needing a one-time human authorization:');+ for (const line of pendingGrants) report(` - ${line}`);+}+report('');+report(ok ? 'provisioned state: complete' : 'provisioned state: INCOMPLETE (see above)');++// stdout is meant to be eval'd, so every value is single-quoted: an id the+// backend returned with a space or a shell metacharacter must not become code.+const shellQuote = value => `'${String(value).replace(/'/g, `'\\''`)}'`;++for (const [name, value] of Object.entries(exports)) {+ if (value === undefined || value === null) {+ ok = false;+ report(`error: ${name} could not be resolved; not exporting it`);+ continue;+ }+ console.log(`export ${name}=${shellQuote(value)}`);+}++process.exitCode = ok ? 0 : 1;diff --git a/ts/examples/README.md b/ts/examples/README.mdnew file mode 100644index 000000000..7ed55f805--- /dev/null+++ b/ts/examples/README.md@@ -0,0 +1,34 @@+# Composio TypeScript examples++Each directory here is its own private workspace package (`<name>-example`) showing one integration or feature: `openai/`, `anthropic/`, `langchain/`, `connected-accounts/`, `tools/`, `triggers/`, `mcp/`, `tool-router/`, and more.++## Run one example++```bash+cd ts+pnpm install+out=$(node ../scripts/examples-provision.mjs) && eval "$out"+pnpm --filter openai-example start+```++`pnpm --filter <package-name> start` runs the example with bun (see the `scripts.start` entry in that package's `package.json`). Some packages expose extra entrypoints alongside `start`, for example `openai-example` also has `start:chat-completion`, `start:assistant`, and `start:mcp` — check the package's `package.json` for the full list.++## Configuration++Examples read configuration from environment variables and fail loudly, naming the missing variable, if one isn't set:++- `COMPOSIO_API_KEY` — always required.+- `COMPOSIO_EXAMPLES_USER_ID` — the user id examples act as.+- `COMPOSIO_EXAMPLES_{GMAIL,GITHUB,SLACK}_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_{GMAIL,GITHUB,SLACK}_CONNECTED_ACCOUNT_ID` — per-toolkit auth config and standing connected account.+- `COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER` — the serpapi API-key auth config and its placeholder key value.+- `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` — only needed by examples that call that LLM provider.++`node ../scripts/examples-provision.mjs` (run from `ts/`, or `node scripts/examples-provision.mjs` from the repo root) checks a Composio project for this state, prints a report to stderr, and prints `export COMPOSIO_EXAMPLES_*=...` lines to stdout. Load them with `out=$(node ../scripts/examples-provision.mjs) && eval "$out"`. Capture first, then eval. `eval "$(...)"` reports the status of the text it evaluates, so it would hide a failed provisioning run. It's idempotent — it verifies what already exists and only creates what's missing — and it never prints credential values.++Add `--initiate-missing` to also start an OAuth connection request for any toolkit (gmail, googledrive, github, slack) that has no active connected account yet; it prints an authorization URL to visit once in a browser. The serpapi API-key auth config is created automatically, no browser step needed.++Run `node ../scripts/examples-provision.mjs --gc` to delete what example runs leave behind: connected accounts that never reached ACTIVE, surplus serpapi demo accounts, and MCP configs from earlier runs. It skips anything created in the last 24h and only touches resources the examples created. It deletes for real, so preview it with `--gc --dry-run` first and point it only at the disposable examples project.++## A note on connection examples++Examples that demonstrate _creating_ a connection (for example `connected-accounts/`) only initiate the OAuth flow and print a line like `Please visit the following URL to authorize the user: ...` — running them does not require you to complete that authorization. Examples that _use_ a connection (calling a tool through Gmail, GitHub, or Slack) rely on the standing connected accounts that the provisioning script already verified are active.diff --git a/ts/examples/anthropic/package.json b/ts/examples/anthropic/package.jsonindex e0d20084a..d9f334041 100644--- a/ts/examples/anthropic/package.json+++ b/ts/examples/anthropic/package.json@@ -6,6 +6,7 @@"main": "index.js","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","start:claude-agents-sdk": "bun src/claude-agents-sdk.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -29,5 +30,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/anthropic/src/experimental.mcp.ts b/ts/examples/anthropic/src/experimental.mcp.tsindex 977328b3d..5071bcc97 100644--- a/ts/examples/anthropic/src/experimental.mcp.ts+++ b/ts/examples/anthropic/src/experimental.mcp.ts@@ -8,39 +8,32 @@ const composio = new Composio({provider: new AnthropicProvider({ cacheTools: true }),});-const authConfigId = '<auth_config_id>'; // Use your auth config ID-const externalUserId = '<external_user_id>'; // Replace it with the your user id-const allowedTools = ['GMAIL_FETCH_EMAILS'];+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}-// 2. Create an MCP config-const mcpConfig = await composio.mcp.create(`${Date.now()}`, {- toolkits: [- {- toolkit: 'gmail',- authConfigId,- },- ],- allowedTools,- manuallyManageConnections: true,+// 2. Create a session scoped to the Gmail toolkit; it exposes a hosted MCP endpoint+const session = await composio.sessions.create(externalUserId, {+ toolkits: ['gmail'],+ mcp: true,});-// 3. Retrieve the MCP server instance for the connected accounts-const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);--// 4. Initialize Anthropic client.+// 3. Initialize Anthropic client.const anthropic = new Anthropic({apiKey: process.env.ANTHROPIC_API_KEY,});-// 5. Pass servers to Anthropic-specific Agent.+// 4. Pass the session's MCP endpoint to Anthropic-specific Agent.const stream = anthropic.beta.messages.stream({- model: 'claude-4-sonnet-20250514',+ model: 'claude-sonnet-5',max_tokens: 64_000,mcp_servers: [{- name: mcp.name,- url: mcp.url,+ name: 'composio-gmail',+ url: session.mcp.url,type: 'url',+ authorization_token: process.env.COMPOSIO_API_KEY,},],messages: [diff --git a/ts/examples/anthropic/src/index.ts b/ts/examples/anthropic/src/index.tsindex 5a2c58e9e..15e807ea8 100644--- a/ts/examples/anthropic/src/index.ts+++ b/ts/examples/anthropic/src/index.ts@@ -43,7 +43,7 @@ async function main() {* Create a message with Anthropic that may use tools*/const message = await anthropic.messages.create({- model: 'claude-3-7-sonnet-latest',+ model: 'claude-sonnet-5',max_tokens: 1024,tools: tools,messages,@@ -75,7 +75,7 @@ async function main() {* Send a follow-up message with the tool results*/const followUpMessage = await anthropic.messages.create({- model: 'claude-3-7-sonnet-latest',+ model: 'claude-sonnet-5',max_tokens: 1024,messages,});@@ -105,6 +105,7 @@ async function main() {}} catch (error) {console.error('Error:', error);+ process.exitCode = 1;}}diff --git a/ts/examples/anthropic/src/mcp.ts b/ts/examples/anthropic/src/mcp.tsindex a403a88e7..e16f7d0b6 100644--- a/ts/examples/anthropic/src/mcp.ts+++ b/ts/examples/anthropic/src/mcp.ts@@ -2,8 +2,8 @@* Anthropic MCP Gmail Example** This example demonstrates how to use Composio SDK with Anthropic to:- * 1. Create an MCP server for Gmail toolkit- * 2. Connect to the server and use it with Anthropic's API+ * 1. Create a tool-router session scoped to the Gmail toolkit+ * 2. Connect Anthropic's MCP client to the session's hosted MCP endpoint* 3. Fetch and summarize emails using the MCP tools** Prerequisites:@@ -30,35 +30,33 @@ const composio = new Composio({provider,});-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'];+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user ID from your database+if (!externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}-// Create an MCP server with Gmail toolkit-const mcpConfig = await composio.mcp.create('gmail-anthropic-' + Date.now(), {- toolkits: [- {- toolkit: 'gmail',- authConfigId,- },- ],- allowedTools,+// Create a session scoped to the Gmail toolkit; every session exposes a hosted MCP endpoint+const session = await composio.sessions.create(externalUserId, {+ toolkits: ['gmail'],+ mcp: true,});-console.log(`✅ MCP server created: ${mcpConfig.id}`);-console.log(`🔧 Available toolkits: ${mcpConfig.allowedTools.join(', ')}`);--// Generate a user-scoped MCP endpoint and adapt it for Anthropic's MCP beta.-const mcp = await mcpConfig.generate(externalUserId);-const servers = provider.wrapMcpServerResponse([{ name: mcp.name, url: mcp.url }]);+console.log(`✅ MCP session created: ${session.sessionId}`);console.log('\n=== Fetching and Summarizing Recent Emails ===');-// Use Anthropic with the MCP servers+// Use Anthropic with the session's MCP endpointconst stream = anthropic.beta.messages.stream({- model: 'claude-4-sonnet-20250514',+ model: 'claude-sonnet-5',max_tokens: 64_000,- mcp_servers: servers,+ mcp_servers: [+ {+ type: 'url',+ url: session.mcp.url,+ name: 'composio-gmail',+ authorization_token: process.env.COMPOSIO_API_KEY,+ },+ ],messages: [{role: 'user',diff --git a/ts/examples/anthropic/src/streaming.ts b/ts/examples/anthropic/src/streaming.tsindex 30ffd722d..a08d6fc6b 100644--- a/ts/examples/anthropic/src/streaming.ts+++ b/ts/examples/anthropic/src/streaming.ts@@ -31,7 +31,7 @@ async function main() {console.log('🔄 Creating message with Anthropic...');const stream = await anthropic.messages.stream({- model: 'claude-3-5-sonnet-latest',+ model: 'claude-sonnet-5',max_tokens: 1024,messages: [{@@ -70,7 +70,7 @@ async function main() {*/const followUpStream = await anthropic.messages.stream({- model: 'claude-3-7-sonnet-latest',+ model: 'claude-sonnet-5',max_tokens: 1024,messages: [{diff --git a/ts/examples/anthropic/tsconfig.json b/ts/examples/anthropic/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/anthropic/tsconfig.json+++ b/ts/examples/anthropic/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/cloudflare-wrangler/package.json b/ts/examples/cloudflare-wrangler/package.jsonindex fb37f367a..12d864da7 100644--- a/ts/examples/cloudflare-wrangler/package.json+++ b/ts/examples/cloudflare-wrangler/package.json@@ -7,10 +7,12 @@"dev": "wrangler dev","start": "wrangler dev","test": "vitest",- "cf-typegen": "wrangler types"+ "cf-typegen": "wrangler types",+ "typecheck": "tsc --noEmit -p ./tsconfig.json"},"devDependencies": {"@cloudflare/vitest-pool-workers": "catalog:",+ "@types/node": "^26.1.2","typescript": "catalog:","vitest": "catalog:","wrangler": "catalog:"@@ -19,5 +21,6 @@"@composio/core": "workspace:^","hono": "catalog:","openai": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/cloudflare-wrangler/tsconfig.json b/ts/examples/cloudflare-wrangler/tsconfig.jsonindex ca1f83e3b..2093cfe84 100644--- a/ts/examples/cloudflare-wrangler/tsconfig.json+++ b/ts/examples/cloudflare-wrangler/tsconfig.json@@ -36,9 +36,7 @@/* Skip type checking all .d.ts files. */"skipLibCheck": true,- "types": [- "./worker-configuration.d.ts"- ]+ "types": ["node", "./worker-configuration.d.ts"]},"exclude": ["test"],"include": ["worker-configuration.d.ts", "src/**/*.ts"]diff --git a/ts/examples/connected-accounts/package.json b/ts/examples/connected-accounts/package.jsonindex a678f0e53..4de089f17 100644--- a/ts/examples/connected-accounts/package.json+++ b/ts/examples/connected-accounts/package.json@@ -6,6 +6,7 @@"main": "index.js","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","test": "echo \"Error: no test specified\" && exit 1"},@@ -19,5 +20,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/connected-accounts/src/api-key.ts b/ts/examples/connected-accounts/src/api-key.tsindex 7b89fc72e..4ec5ad9b7 100644--- a/ts/examples/connected-accounts/src/api-key.ts+++ b/ts/examples/connected-accounts/src/api-key.ts@@ -4,9 +4,20 @@ const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,});-const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {+const authConfigId = process.env.COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID; // an API-key-scheme auth config ID+const apiKey = process.env.COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER; // the service API key to store+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!authConfigId || !apiKey || !userId) {+ throw new Error(+ 'Set COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID, COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER and COMPOSIO_EXAMPLES_USER_ID'+ );+}++const connectionRequest = await composio.connectedAccounts.initiate(userId, authConfigId, {+ // Allow more than one connected account per user for this auth config+ allowMultiple: true,config: AuthScheme.APIKey({- api_key: 'your_api_key',+ generic_api_key: apiKey,}),});diff --git a/ts/examples/connected-accounts/src/multiple-connected-accounts.ts b/ts/examples/connected-accounts/src/multiple-connected-accounts.tsindex 4b0a990f4..293a8cf67 100644--- a/ts/examples/connected-accounts/src/multiple-connected-accounts.ts+++ b/ts/examples/connected-accounts/src/multiple-connected-accounts.ts@@ -4,7 +4,12 @@ const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,});-const connectionRequest = await composio.connectedAccounts.initiate('default', 'ac_NSC2s9WqTE4n', {+const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your auth config ID+if (!authConfigId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID');+}++const connectionRequest = await composio.connectedAccounts.initiate('default', authConfigId, {allowMultiple: true,});diff --git a/ts/examples/connected-accounts/src/scopes.ts b/ts/examples/connected-accounts/src/scopes.tsindex 49088bde8..b2274a06a 100644--- a/ts/examples/connected-accounts/src/scopes.ts+++ b/ts/examples/connected-accounts/src/scopes.ts@@ -2,6 +2,11 @@ import { Composio } from '@composio/core';const composio = new Composio();-const response = await composio.authConfigs.get('ac_3COrKCdQYLNu');+const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your auth config ID+if (!authConfigId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID');+}++const response = await composio.authConfigs.get(authConfigId);console.log(JSON.stringify(response, null, 2));diff --git a/ts/examples/connected-accounts/tsconfig.json b/ts/examples/connected-accounts/tsconfig.jsonindex 7bb456e7a..546f6578e 100644--- a/ts/examples/connected-accounts/tsconfig.json+++ b/ts/examples/connected-accounts/tsconfig.json@@ -9,7 +9,8 @@"strict": true,"esModuleInterop": true,"moduleResolution": "bundler",- "skipLibCheck": true+ "skipLibCheck": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/error-handling-demo/package.json b/ts/examples/error-handling-demo/package.jsonindex 8adfb3085..041f7539b 100644--- a/ts/examples/error-handling-demo/package.json+++ b/ts/examples/error-handling-demo/package.json@@ -6,6 +6,7 @@"main": "index.js","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","test": "echo \"Error: no test specified\" && exit 1"},@@ -19,5 +20,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/error-handling-demo/tsconfig.json b/ts/examples/error-handling-demo/tsconfig.jsonindex 7bb456e7a..546f6578e 100644--- a/ts/examples/error-handling-demo/tsconfig.json+++ b/ts/examples/error-handling-demo/tsconfig.json@@ -9,7 +9,8 @@"strict": true,"esModuleInterop": true,"moduleResolution": "bundler",- "skipLibCheck": true+ "skipLibCheck": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/file-handling/package.json b/ts/examples/file-handling/package.jsonindex ab3c6ace9..5937118f3 100644--- a/ts/examples/file-handling/package.json+++ b/ts/examples/file-handling/package.json@@ -5,6 +5,7 @@"description": "Example project for File-handling","main": "src/index.ts","scripts": {+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -23,5 +24,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/file-handling/tsconfig.json b/ts/examples/file-handling/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/file-handling/tsconfig.json+++ b/ts/examples/file-handling/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/google/package.json b/ts/examples/google/package.jsonindex 9ee24a531..a01d3e1b7 100644--- a/ts/examples/google/package.json+++ b/ts/examples/google/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -29,5 +30,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/google/src/experimental.mcp.ts b/ts/examples/google/src/experimental.mcp.tsindex 44d758282..ecd9c49f3 100644--- a/ts/examples/google/src/experimental.mcp.ts+++ b/ts/examples/google/src/experimental.mcp.ts@@ -2,7 +2,7 @@ import { Composio } from '@composio/core';import { GoogleGenAI, mcpToTool } from '@google/genai';import { GoogleProvider } from '@composio/google';import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';-import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';function wrapTools(client: MCPClient) {return [mcpToTool(client)];@@ -14,44 +14,42 @@ const composio = new Composio({provider: new GoogleProvider(),});-const authConfigId = '<auth_config_id>'; // Use your auth config ID-const externalUserId = '<externalUserId>'; // Replace it with the user id from your database-const allowedTools = ['GMAIL_FETCH_EMAILS'];+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}-// 2. Create an MCP config-const mcpConfig = await composio.experimental.mcp.create(`${Date.now()}`, {- toolkits: [- {- toolkit: 'gmail',- authConfigId,- allowedTools,- },- ],- manuallyManageConnections: true,+// 2. Create a session scoped to the Gmail toolkit; it exposes a hosted MCP endpoint.+// manageConnections defaults to true, which would add connection-management tools+// this example does not use. The config it replaced set manuallyManageConnections.+const session = await composio.sessions.create(externalUserId, {+ toolkits: ['gmail'],+ manageConnections: false,+ mcp: true,});-// 3. Retrieve the MCP server instance for the user-const server = await composio.experimental.mcp.generate(externalUserId, mcpConfig.id);--// 4. Create a generic MCP client.+// 3. Create a generic MCP client.// This client needs to remain "alive" not be dropped by the GC until// the tools are retrieved from it.-const serverParams = new SSEClientTransport(new URL(server.url));+// session.mcp.headers carries the credentials the endpoint requires.+const serverParams = new StreamableHTTPClientTransport(new URL(session.mcp.url), {+ requestInit: { headers: session.mcp.headers },+});const mcpClient = new MCPClient({name: 'composio-mcp-client',version: '1.0.0',});-// 5. Retrieve tools.+// 4. Retrieve tools.await mcpClient.connect(serverParams);const tools = wrapTools(mcpClient);-// 6. Initialize Google Gemini client.+// 5. Initialize Google Gemini client.const gemini = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY,});-// 7. Pass tools to Google Gemini-specific Agent.+// 6. Pass tools to Google Gemini-specific Agent.const stream = await gemini.models.generateContentStream({model: 'gemini-2.5-flash',contents: `Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email.`,@@ -60,10 +58,10 @@ const stream = await gemini.models.generateContentStream({},});-// 8. Execute the Google Gemini-specific Agent.+// 7. Execute the Google Gemini-specific Agent.for await (const chunk of stream) {console.log(chunk.text);}-// 9. Close the generic MCP client.+// 8. Close the generic MCP client.await mcpClient.close();diff --git a/ts/examples/google/src/index.ts b/ts/examples/google/src/index.tsindex 26c2c6aba..9b4c657aa 100644--- a/ts/examples/google/src/index.ts+++ b/ts/examples/google/src/index.ts@@ -62,8 +62,12 @@ async function main() {}} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/google/tsconfig.json b/ts/examples/google/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/google/tsconfig.json+++ b/ts/examples/google/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/json-schema-to-zod/package.json b/ts/examples/json-schema-to-zod/package.jsonindex fc84be928..40e848208 100644--- a/ts/examples/json-schema-to-zod/package.json+++ b/ts/examples/json-schema-to-zod/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -26,5 +27,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/json-schema-to-zod/src/index.ts b/ts/examples/json-schema-to-zod/src/index.tsindex 92468e10d..7cbbf28a1 100644--- a/ts/examples/json-schema-to-zod/src/index.ts+++ b/ts/examples/json-schema-to-zod/src/index.ts@@ -38,8 +38,12 @@ async function main() {console.log('📝 Implement your json-schema-to-zod logic here!');} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/json-schema-to-zod/tsconfig.json b/ts/examples/json-schema-to-zod/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/json-schema-to-zod/tsconfig.json+++ b/ts/examples/json-schema-to-zod/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/langchain/package.json b/ts/examples/langchain/package.jsonindex 6580e9253..b252e315c 100644--- a/ts/examples/langchain/package.json+++ b/ts/examples/langchain/package.json@@ -6,6 +6,7 @@"main": "index.js","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","test": "echo \"Error: no test specified\" && exit 1"},@@ -25,5 +26,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/langchain/src/openai.ts b/ts/examples/langchain/src/openai.tsindex 25b584b5a..22c104df0 100644--- a/ts/examples/langchain/src/openai.ts+++ b/ts/examples/langchain/src/openai.ts@@ -1,6 +1,6 @@import { Composio } from '@composio/core';import { LangchainProvider } from '@composio/langchain';-import { createAgent } from "langchain";+import { createAgent } from 'langchain';import { ChatOpenAI } from '@langchain/openai';// initiate composio@@ -8,15 +8,20 @@ const composio = new Composio({provider: new LangchainProvider(),});-const githubTool = await composio.tools.get('jkomyno', 'GMAIL_FETCH_EMAILS');+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}++const gmailTool = await composio.tools.get(userId, 'GMAIL_FETCH_EMAILS');const agent = createAgent({- model: new ChatOpenAI({ model: "gpt-5" }),- tools: githubTool,- });-- console.log(- await agent.invoke({- messages: [{ role: "user", content: "Provide a summary of my last email received." }],- })- );\ No newline at end of file+ model: new ChatOpenAI({ model: 'gpt-5' }),+ tools: gmailTool,+});++console.log(+ await agent.invoke({+ messages: [{ role: 'user', content: 'Provide a summary of my last email received.' }],+ })+);diff --git a/ts/examples/langchain/tsconfig.json b/ts/examples/langchain/tsconfig.jsonindex 7bb456e7a..546f6578e 100644--- a/ts/examples/langchain/tsconfig.json+++ b/ts/examples/langchain/tsconfig.json@@ -9,7 +9,8 @@"strict": true,"esModuleInterop": true,"moduleResolution": "bundler",- "skipLibCheck": true+ "skipLibCheck": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/llamaindex/package.json b/ts/examples/llamaindex/package.jsonindex 5faddcc12..885bff5f3 100644--- a/ts/examples/llamaindex/package.json+++ b/ts/examples/llamaindex/package.json@@ -5,6 +5,7 @@"description": "Example project for Llamaindex","main": "src/index.ts","scripts": {+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -27,5 +28,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/llamaindex/src/index.ts b/ts/examples/llamaindex/src/index.tsindex d9e8136c9..1d792dca4 100644--- a/ts/examples/llamaindex/src/index.ts+++ b/ts/examples/llamaindex/src/index.ts@@ -71,8 +71,12 @@ async function main() {}} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/llamaindex/tsconfig.json b/ts/examples/llamaindex/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/llamaindex/tsconfig.json+++ b/ts/examples/llamaindex/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/mcp/package.json b/ts/examples/mcp/package.jsonindex ea2c6d6a8..ddf499056 100644--- a/ts/examples/mcp/package.json+++ b/ts/examples/mcp/package.json@@ -5,6 +5,7 @@"description": "Example project for Mcp","main": "src/index.ts","scripts": {+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -29,5 +30,6 @@"@types/bun": "catalog:","@types/node": "^26.1.2","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/mcp/src/index.ts b/ts/examples/mcp/src/index.tsindex 278ad0678..2c820c697 100644--- a/ts/examples/mcp/src/index.ts+++ b/ts/examples/mcp/src/index.ts@@ -2,7 +2,7 @@ import { createMCPClient } from '@ai-sdk/mcp';import { openai } from '@ai-sdk/openai';import { Composio } from '@composio/core';import { VercelProvider } from '@composio/vercel';-import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';import { stepCountIs, streamText } from 'ai';import 'dotenv/config';@@ -12,12 +12,18 @@ const composio = new Composio({provider: new VercelProvider(),});-const authConfigId = '<auth_config_id>'; // Use your auth config ID-const externalUserId = '<extern_user_id>'; // Replace it with the user id+const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config ID+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!authConfigId || !externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');+}const allowedTools = ['GMAIL_FETCH_EMAILS'];// 2. Create an MCP config-const mcpConfig = await composio.mcp.create(`${Date.now()}`, {+// Named `examples-<label>-<unix-seconds>` so the provisioning script's --gc can+// tell an example's throwaway config from one someone created by hand. The API+// caps this name at 30 characters, so keep the label short and use seconds.+const mcpConfig = await composio.mcp.create(`examples-gmail-${Math.floor(Date.now() / 1000)}`, {toolkits: [{toolkit: 'gmail',@@ -31,7 +37,10 @@ const mcpConfig = await composio.mcp.create(`${Date.now()}`, {// 3. Retrieve the MCP server instance for the userconst server = await composio.mcp.generate(externalUserId, mcpConfig.id);-const serverParams = new SSEClientTransport(new URL(server.url));+// The MCP endpoint authenticates with your Composio API key+const serverParams = new StreamableHTTPClientTransport(new URL(server.url), {+ requestInit: { headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! } },+});const mcpClient = await createMCPClient({name: 'composio-mcp-client',diff --git a/ts/examples/modifiers/package.json b/ts/examples/modifiers/package.jsonindex 070f2f55d..b5cca2b04 100644--- a/ts/examples/modifiers/package.json+++ b/ts/examples/modifiers/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","test": "echo \"Error: no test specified\" && exit 1"},@@ -21,5 +22,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/modifiers/tsconfig.json b/ts/examples/modifiers/tsconfig.jsonindex 7bb456e7a..546f6578e 100644--- a/ts/examples/modifiers/tsconfig.json+++ b/ts/examples/modifiers/tsconfig.json@@ -9,7 +9,8 @@"strict": true,"esModuleInterop": true,"moduleResolution": "bundler",- "skipLibCheck": true+ "skipLibCheck": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/openai/src/agents-api/experiment.mcp.ts b/ts/examples/openai/src/agents-api/experiment.mcp.tsindex 827ecdfea..5f682d12c 100644--- a/ts/examples/openai/src/agents-api/experiment.mcp.ts+++ b/ts/examples/openai/src/agents-api/experiment.mcp.ts@@ -11,13 +11,16 @@ const composio = new Composio({allowTracking: false,});-const authConfigId = '<auth_config_id>'; // Use your auth config ID+const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config IDconst toolkit = 'gmail'; // slug of the toolkit-const externalUserId = '<external_user_id>'; // Replace it with the userId from your database+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the userId from your database+if (!authConfigId || !externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');+}const allowedTools = ['GMAIL_FETCH_EMAILS'];-// 2. Create an MCP config-const mcpConfig = await composio.mcp.create(externalUserId, {+// 2. Create an MCP config (names must be unique within a project)+const mcpConfig = await composio.mcp.create(`examples-gm-agents-${Math.floor(Date.now() / 1000)}`, {toolkits: [{ toolkit, authConfigId }],allowedTools,});@@ -29,6 +32,8 @@ const tools: HostedMCPTool[] = [hostedMcpTool({serverLabel: server.name,serverUrl: server.url,+ // The MCP endpoint authenticates with your Composio API key+ headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },requireApproval: {never: {toolNames: ['GMAIL_FETCH_EMAILS'],@@ -60,5 +65,5 @@ console.log('\n📬 Email Summary:');const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);-// @ts-ignore+// @ts-expect-error: the agents SDK types `output` as a union whose message variant is not narrowed by the `type` filter aboveconsole.log(output?.content[0].text);diff --git a/ts/examples/openai/src/agents-api/experiment.tool-router.ts b/ts/examples/openai/src/agents-api/experiment.tool-router.tsindex 00605ed03..22fd8ce48 100644--- a/ts/examples/openai/src/agents-api/experiment.tool-router.ts+++ b/ts/examples/openai/src/agents-api/experiment.tool-router.ts@@ -25,8 +25,10 @@ const session = await composio.sessions.create(externalUserId, {const tools: HostedMCPTool[] = [hostedMcpTool({- serverLabel: 'composio tool router',+ serverLabel: 'composio-tool-router',serverUrl: session.mcp.url,+ // The MCP endpoint authenticates with your Composio API key+ headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },requireApproval: {never: {toolNames: ['HACKERNEWS_GET_USER_BY_USERNAME'],@@ -57,5 +59,5 @@ console.log('\n📰 HackerNews Profile:');const output = response.output.filter(({ type }) => type === 'message').at(0);-// @ts-ignore+// @ts-expect-error: the agents SDK types `output` as a union whose message variant is not narrowed by the `type` filter aboveconsole.log(output?.content[0].text);diff --git a/ts/examples/openai/src/chat-completions.ts b/ts/examples/openai/src/chat-completions.tsindex bffaf7f18..7bc8a3fcf 100644--- a/ts/examples/openai/src/chat-completions.ts+++ b/ts/examples/openai/src/chat-completions.ts@@ -86,6 +86,7 @@ async function main() {}} catch (error) {console.error('❌ Error:', error);+ process.exitCode = 1;}}diff --git a/ts/examples/openai/src/responses-api/experiment.mcp.ts b/ts/examples/openai/src/responses-api/experiment.mcp.tsindex a4ca8307b..6bae47a1e 100644--- a/ts/examples/openai/src/responses-api/experiment.mcp.ts+++ b/ts/examples/openai/src/responses-api/experiment.mcp.ts@@ -10,12 +10,15 @@ const composio = new Composio({allowTracking: false,});-const authConfigId = '<auth_config_id>'; // Use your auth config ID-const externalUserId = '<external_user_id>'; // Replace it with the user id from your database+const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config ID+const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!authConfigId || !externalUserId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');+}const allowedTools = ['GMAIL_FETCH_EMAILS'];// 2. Create an MCP config-const mcpConfig = await composio.mcp.create(`gmail-mcp-${Date.now()}`, {+const mcpConfig = await composio.mcp.create(`examples-gm-resp-${Math.floor(Date.now() / 1000)}`, {toolkits: [{toolkit: 'gmail',@@ -34,9 +37,10 @@ const tools = [type: 'mcp' as const,server_label: mcp.name,server_url: mcp.url,+ // The MCP endpoint authenticates with your Composio API key+ headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },},];-console.log({ tools });// 4. Pass tools to OpenAI-specific Agent.const openai = new OpenAI();@@ -51,8 +55,6 @@ const emailResponse = await openai.responses.create({tools: tools,});-console.log(JSON.stringify(emailResponse, null, 2));-const result = await composio.provider.handleToolCalls('default', emailResponse.output);console.log({ result });diff --git a/ts/examples/session-management/package.json b/ts/examples/session-management/package.jsonindex f3db853d4..bb7d3f68c 100644--- a/ts/examples/session-management/package.json+++ b/ts/examples/session-management/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -24,5 +25,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/session-management/src/index.ts b/ts/examples/session-management/src/index.tsindex 270131e72..91b66b6c4 100644--- a/ts/examples/session-management/src/index.ts+++ b/ts/examples/session-management/src/index.ts@@ -37,8 +37,12 @@ async function main() {console.log(`✅ Found ${tools.length} tools`);} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/session-management/tsconfig.json b/ts/examples/session-management/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/session-management/tsconfig.json+++ b/ts/examples/session-management/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/tool-router/package.json b/ts/examples/tool-router/package.jsonindex 4fd62c722..1d9af42e6 100644--- a/ts/examples/tool-router/package.json+++ b/ts/examples/tool-router/package.json@@ -44,5 +44,6 @@"@types/bun": "catalog:","@types/node": "^26.1.2","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/tool-router/src/authorize.ts b/ts/examples/tool-router/src/authorize.tsindex d7226864a..4a661b2ba 100644--- a/ts/examples/tool-router/src/authorize.ts+++ b/ts/examples/tool-router/src/authorize.ts@@ -1,14 +1,19 @@import { Composio } from '@composio/core';const composio = new Composio();-const session = await composio.create('user_123', { toolkits: ['gmail'] });-const connectionRequest = await session.authorize("gmail", {- callbackUrl: "https://google.com"-});-console.log(connectionRequest);+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}-const connectedAccount = await connectionRequest.waitForConnection();-console.log(connectedAccount);+const session = await composio.create(userId, { toolkits: ['gmail'] });+const connectionRequest = await session.authorize('gmail', {+ callbackUrl: 'https://google.com',+});+console.log(`Visit this URL to authorize: ${connectionRequest.redirectUrl}`);+const connectedAccount = await connectionRequest.waitForConnection();+// Print identifying fields only: the full object carries live OAuth credentials.+console.log(`Connected account ${connectedAccount.id} is ${connectedAccount.status}`);diff --git a/ts/examples/tool-router/src/langchain.ts b/ts/examples/tool-router/src/langchain.tsindex 8eae65e07..5a971c637 100644--- a/ts/examples/tool-router/src/langchain.ts+++ b/ts/examples/tool-router/src/langchain.ts@@ -12,10 +12,15 @@ const llm = new ChatOpenAI({});async function main() {- const session = await composio.create('user_123', { toolkits: ['gmail'], mcp: true });+ const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a connected Gmail account+ if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+ }++ const session = await composio.create(userId, { toolkits: ['gmail'], mcp: true });const client = new MultiServerMCPClient({- math: {+ composio: {transport: 'http',url: session.mcp.url,headers: session.mcp.headers,@@ -25,7 +30,7 @@ async function main() {const tools = await client.getTools();const agent = createAgent({- name: 'Gmail Assistant',+ name: 'gmail-assistant',systemPrompt: 'You are a helpful gmail assistant.',model: llm,tools,diff --git a/ts/examples/tool-router/src/multi-account.ts b/ts/examples/tool-router/src/multi-account.tsindex 88993ca03..aa42bb79f 100644--- a/ts/examples/tool-router/src/multi-account.ts+++ b/ts/examples/tool-router/src/multi-account.ts@@ -7,9 +7,14 @@ const composio = new Composio({provider: new VercelProvider(),});+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database+if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}+// Enable multi-account mode so the user can connect multiple accounts// per toolkit (e.g. two Gmail accounts).-const session = await composio.create('user_123', {+const session = await composio.create(userId, {toolkits: ['gmail'],multiAccount: {enable: true,@@ -19,10 +24,16 @@ const session = await composio.create('user_123', {});// Set an alias while authorizing a connected account for easier identification.-await session.authorize('gmail', {- alias: 'work-gmail',+// Aliases are unique per entity and toolkit, so suffix to keep reruns working.+const connectionRequest = await session.authorize('gmail', {+ alias: `work-gmail-${Date.now()}`,});+console.log(`Visit this URL to authorize: ${connectionRequest.redirectUrl}`);++// requireExplicitSelection means the new alias is only usable once it is ACTIVE.+await connectionRequest.waitForConnection();+const tools = await session.tools();const stream = await streamText({diff --git a/ts/examples/toolkits/package.json b/ts/examples/toolkits/package.jsonindex c49b6fb30..0d2b0fe88 100644--- a/ts/examples/toolkits/package.json+++ b/ts/examples/toolkits/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","test": "echo \"Error: no test specified\" && exit 1"},@@ -21,5 +22,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/toolkits/tsconfig.json b/ts/examples/toolkits/tsconfig.jsonindex 7bb456e7a..546f6578e 100644--- a/ts/examples/toolkits/tsconfig.json+++ b/ts/examples/toolkits/tsconfig.json@@ -9,7 +9,8 @@"strict": true,"esModuleInterop": true,"moduleResolution": "bundler",- "skipLibCheck": true+ "skipLibCheck": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/tools/package.json b/ts/examples/tools/package.jsonindex dcf25e121..1ba5f990b 100644--- a/ts/examples/tools/package.json+++ b/ts/examples/tools/package.json@@ -5,6 +5,7 @@"description": "Example project for Tools","main": "src/index.ts","scripts": {+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -29,5 +30,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/tools/src/ai.ts b/ts/examples/tools/src/ai.tsindex 726683e51..0a272e917 100644--- a/ts/examples/tools/src/ai.ts+++ b/ts/examples/tools/src/ai.ts@@ -12,20 +12,28 @@ const openai = new OpenAI({*/const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,+ // Local file paths under fileUploadDirs are uploaded automatically when the tool expects a file+ dangerouslyAllowAutoUploadDownloadFiles: true,+ fileUploadDirs: [import.meta.dirname],});+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a Google Drive connection+if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}+/*** Get the tools* This tool is automatically typed and wrapped with the OpenAI Provider*/console.log('🔄 Getting tools...');-const tools = await composio.tools.get('default', 'GOOGLEDRIVE_UPLOAD_FILE');+const tools = await composio.tools.get(userId, 'GOOGLEDRIVE_UPLOAD_FILE');console.log('✅ Tools fetched successfully...');console.log(JSON.stringify(tools, null, 2));/*** Define a task for the assistant based on the tools in hand*/-const fileToUpload = path.join(__dirname, 'image.png');+const fileToUpload = path.join(import.meta.dirname, 'image.png');const task = `Upload the file ${fileToUpload} to Google Drive`;/**@@ -51,9 +59,12 @@ console.log('✅ Chat completion created successfully...');* If the assistant has tool calls, execute them and log the result*/console.log('🔄 Calling tool...');-if (response.choices[0].message.tool_calls && response.choices[0].message.tool_calls[0].type === 'function') {+if (+ response.choices[0].message.tool_calls &&+ response.choices[0].message.tool_calls[0].type === 'function'+) {console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);- const result = await composio.provider.handleToolCalls('default', response);+ const result = await composio.provider.handleToolCalls(userId, response);console.log(result);}console.log('✅ Tool called successfully...');diff --git a/ts/examples/tools/src/index.ts b/ts/examples/tools/src/index.tsindex 702f8c8e7..1db5eb077 100644--- a/ts/examples/tools/src/index.ts+++ b/ts/examples/tools/src/index.ts@@ -18,8 +18,16 @@ import path from 'path';const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,allowTracking: false,+ // Local file paths under fileUploadDirs are uploaded automatically when the tool expects a file+ dangerouslyAllowAutoUploadDownloadFiles: true,+ fileUploadDirs: [import.meta.dirname],});+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a Google Drive connection+if (!userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');+}+/*** Main function to run the example*/@@ -31,9 +39,9 @@ async function main() {const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {dangerouslySkipVersionCheck: true,arguments: {- file_to_upload: path.join(__dirname, 'image.png'),+ file_to_upload: path.join(import.meta.dirname, 'image.png'),},- userId: 'default',+ userId,});console.log('✅ File uploaded successfully...');console.log(JSON.stringify(result, null, 2));@@ -42,16 +50,20 @@ async function main() {const result2 = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {dangerouslySkipVersionCheck: true,arguments: {- file_id: (result.data.response_data as unknown as { id: string }).id,+ file_id: (result.data as unknown as { id: string }).id,},- userId: 'default',+ userId,});console.log('✅ File downloaded successfully...');console.log(JSON.stringify(result2, null, 2));} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/tools/tsconfig.json b/ts/examples/tools/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/tools/tsconfig.json+++ b/ts/examples/tools/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/triggers/package.json b/ts/examples/triggers/package.jsonindex 749c3388d..128f0e9ec 100644--- a/ts/examples/triggers/package.json+++ b/ts/examples/triggers/package.json@@ -6,6 +6,7 @@"main": "src/index.ts","scripts": {"clean": "git clean -xdf node_modules",+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","webhook:server": "bun src/webhook-server.ts",@@ -25,5 +26,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/triggers/src/create.ts b/ts/examples/triggers/src/create.tsindex 051d9bfd1..096bc0403 100644--- a/ts/examples/triggers/src/create.ts+++ b/ts/examples/triggers/src/create.ts@@ -9,9 +9,15 @@ const triggerType = await composio.triggers.getType('GMAIL_NEW_GMAIL_MESSAGE');console.log(JSON.stringify(triggerType, null, 2));+const connectedAccountId = process.env.COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID; // your Gmail connected account ID+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user that owns the connected account+if (!connectedAccountId || !userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID and COMPOSIO_EXAMPLES_USER_ID');+}+// create a trigger-const trigger = await composio.triggers.create('default', triggerType.slug, {- connectedAccountId: 'ca_uQvmu9uZOhQo',+const trigger = await composio.triggers.create(userId, triggerType.slug, {+ connectedAccountId,triggerConfig: {},});diff --git a/ts/examples/triggers/src/index.ts b/ts/examples/triggers/src/index.tsindex 9af768f85..4801b53f3 100644--- a/ts/examples/triggers/src/index.ts+++ b/ts/examples/triggers/src/index.ts@@ -41,13 +41,18 @@ async function main() {'📝 Go to https://app.composio.dev to create an app and add a trigger, Once you have an incoming trigger, you will see the events');- composio.triggers.subscribe(data => {+ await composio.triggers.subscribe(data => {console.log('🔔 Trigger received:', JSON.stringify(data, null, 2));});+ console.log('Subscribed to trigger events');} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/triggers/src/subscribe.ts b/ts/examples/triggers/src/subscribe.tsindex 0d0db6822..42549fcbc 100644--- a/ts/examples/triggers/src/subscribe.ts+++ b/ts/examples/triggers/src/subscribe.ts@@ -5,9 +5,15 @@ const composio = new Composio({apiKey: process.env.COMPOSIO_API_KEY,});+const connectedAccountId = process.env.COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID; // your Gmail connected account ID+const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user that owns the connected account+if (!connectedAccountId || !userId) {+ throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID and COMPOSIO_EXAMPLES_USER_ID');+}+// create a trigger-const { triggerId } = await composio.triggers.create('default','GMAIL_NEW_GMAIL_MESSAGE', {- connectedAccountId: 'ca_uQvmu9uZOhQo',+const { triggerId } = await composio.triggers.create(userId, 'GMAIL_NEW_GMAIL_MESSAGE', {+ connectedAccountId,triggerConfig: {},});diff --git a/ts/examples/triggers/tsconfig.json b/ts/examples/triggers/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/triggers/tsconfig.json+++ b/ts/examples/triggers/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}diff --git a/ts/examples/vercel/package.json b/ts/examples/vercel/package.jsonindex 77eebc7be..cee30f38d 100644--- a/ts/examples/vercel/package.json+++ b/ts/examples/vercel/package.json@@ -29,5 +29,6 @@"@types/bun": "catalog:","@types/node": "^26.1.2","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/vercel/src/stream.ts b/ts/examples/vercel/src/stream.tsindex db56c27a2..e12931b86 100644--- a/ts/examples/vercel/src/stream.ts+++ b/ts/examples/vercel/src/stream.ts@@ -11,7 +11,7 @@ const composio = new Composio({provider: new VercelProvider(),});-const tools = await composio.tools.get('test-user-id', 'HACKERNEWS_GET_FRONTPAGE');+const tools = await composio.tools.get('test-user-id', 'HACKERNEWS_GET_TOP_STORIES');const stream = await streamText({model: openai('gpt-4o-mini'),tools,diff --git a/ts/examples/versioning/package.json b/ts/examples/versioning/package.jsonindex 54f0ee4d3..44fd0143a 100644--- a/ts/examples/versioning/package.json+++ b/ts/examples/versioning/package.json@@ -5,6 +5,7 @@"description": "Example project for Versioning","main": "src/index.ts","scripts": {+ "typecheck": "tsc --noEmit -p ./tsconfig.json","start": "bun src/index.ts","dev": "bun --watch src/index.ts","test": "echo \"Error: no test specified\" && exit 1"@@ -23,5 +24,6 @@"devDependencies": {"@types/bun": "catalog:","typescript": "catalog:"- }+ },+ "type": "module"}diff --git a/ts/examples/versioning/src/index.ts b/ts/examples/versioning/src/index.tsindex d93eac858..e36d7f7fa 100644--- a/ts/examples/versioning/src/index.ts+++ b/ts/examples/versioning/src/index.ts@@ -42,8 +42,12 @@ async function main() {} catch (error) {console.error('❌ Error running example:', error);+ process.exitCode = 1;}}// Run the example-main().catch(console.error);+main().catch(error => {+ console.error(error);+ process.exitCode = 1;+});diff --git a/ts/examples/versioning/tsconfig.json b/ts/examples/versioning/tsconfig.jsonindex f736a53ab..b33909549 100644--- a/ts/examples/versioning/tsconfig.json+++ b/ts/examples/versioning/tsconfig.json@@ -10,7 +10,8 @@"esModuleInterop": true,"moduleResolution": "bundler","skipLibCheck": true,- "resolveJsonModule": true+ "resolveJsonModule": true,+ "types": ["bun"]},"include": ["src"]}