@devries-cameron20 / composio-1 / commits / 8086ef02c
Fork 0

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

fix(examples): align Python and TypeScript examples with current backend (#4107)

## Summary - Repairs runnable TypeScript and Python examples for current backend requirements, including authenticated MCP endpoints, current transports, valid tool identifiers, provider limits, and resource uniqueness. - Replaces placeholder resource IDs with explicit `COMPOSIO_EXAMPLES_*` configuration and makes failed examples exit loudly. - Adds `scripts/examples-provision.mjs` as an idempotent provisioning check for a disposable examples project. ## Scope - This PR no longer changes the Python SDK runtime or generated-client dependency. - Python remains pinned to the published `composio-client==1.43.0` in `pyproject.toml`, `setup.py`, and `uv.lock`. - The owned 2.x client integration is deferred until that client completes its release guarantees and is explicitly published. - The scheduled live workflow and manifest remain deferred until their runner is tracked. ## Verification - `make chk` - `make tst` (`927 passed, 33 skipped`) - Hosted checks rerun against commit `12691aca7`.

Alberto Schiabel committed Aug 11, 2026 at 19:45 UTC 8086ef02cb02bb356846f7b9ca763a49f7f5c219
87 files changed +1007 -355
.github/workflows/py.check.yaml
+6
@@ -76,6 +76,12 @@ jobs:
76 cd python/
77 uv run nox -s chk
78
79 + - name: Example type checks
80 + shell: bash
81 + run: |
82 + cd python/
83 + uv run nox -s chk_examples
84 +
85 - name: Type inference tests
86 shell: bash
87 run: |
.gitignore
+2
@@ -4,6 +4,8 @@ node_modules
4 # output
5 out
6 dist
7 +# wrangler deploy --dry-run --outdir, used by the examples' cf:dry-run script
8 +dist-worker
9 *.tgz
10
11 # code coverage
pnpm-lock.yaml
+4 -8
@@ -639,6 +639,9 @@ importers:
639 '@cloudflare/vitest-pool-workers':
640 specifier: 'catalog:'
641 version: 0.20.1(@cloudflare/workers-types@5.20260804.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(vitest@4.1.10)
642 + '@types/node':
643 + specifier: ^26.1.2
644 + version: 26.1.2
645 typescript:
646 specifier: 'catalog:'
647 version: 7.0.2
@@ -4098,9 +4101,6 @@ packages:
4101 '@types/node@24.13.3':
4102 resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}
4103
4101 - '@types/node@26.1.1':
4102 - resolution: {integrity: sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==}
4103 -
4104 '@types/node@26.1.2':
4105 resolution: {integrity: sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==}
4106
@@ -9564,10 +9564,6 @@ snapshots:
9564 dependencies:
9565 undici-types: 7.18.2
9566
9567 - '@types/node@26.1.1':
9568 - dependencies:
9569 - undici-types: 8.3.0
9570 -
9567 '@types/node@26.1.2':
9568 dependencies:
9569 undici-types: 8.3.0
@@ -9580,7 +9576,7 @@ snapshots:
9576
9577 '@types/ws@8.18.1':
9578 dependencies:
9583 - '@types/node': 26.1.1
9579 + '@types/node': 26.1.2
9580
9581 '@types/yauzl@2.10.3':
9582 dependencies:
python/examples/README.md new
+34
@@ -0,0 +1,34 @@
1 +# Composio Python examples
2 +
3 +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.
4 +
5 +## Run one example
6 +
7 +```bash
8 +cd python
9 +uv sync
10 +out=$(node ../scripts/examples-provision.mjs) && eval "$out"
11 +uv run python examples/tools.py
12 +```
13 +
14 +`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`.
15 +
16 +## Configuration
17 +
18 +Examples read configuration from environment variables and raise a `KeyError` naming the missing variable if one isn't set:
19 +
20 +- `COMPOSIO_API_KEY` — always required.
21 +- `COMPOSIO_EXAMPLES_USER_ID` — the user id examples act as.
22 +- `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.
23 +- `COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER` — the serpapi API-key auth config and its placeholder key value.
24 +- `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` — only needed by examples that call that LLM provider.
25 +
26 +`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.
27 +
28 +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.
29 +
30 +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.
31 +
32 +## A note on connection examples
33 +
34 +`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.
python/examples/auth_configs.py
+3 -3
@@ -16,7 +16,7 @@ auth_config = composio.auth_configs.create(
16 print(auth_config)
17
18 # Use custom auth
19 -auth_config = composio.auth_configs.create(
19 +auth_config = composio.auth_configs.create( # type: ignore[call-overload] # credentials TypedDict omits client_id/client_secret/oauth_redirect_uri; API accepts them
20 toolkit="notion",
21 options={
22 "name": "Notion Auth",
@@ -50,7 +50,7 @@ required_input_fields = [
50 print(required_input_fields)
51
52 # Update an auth config
53 -auth_config_updated = composio.auth_configs.update(
53 +auth_config_updated = composio.auth_configs.update( # type: ignore[call-overload] # credentials TypedDict omits client_id/client_secret, which the API accepts
54 auth_config.id,
55 options={
56 "type": "custom",
@@ -59,7 +59,7 @@ auth_config_updated = composio.auth_configs.update(
59 "client_secret": "1234567890",
60 },
61 "tool_access_config": {
62 - "tools_for_connected_account_creation": ["github"],
62 + "tools_for_connected_account_creation": ["NOTION_ADD_PAGE_CONTENT"],
63 },
64 },
65 )
python/examples/connected_accounts.py
+21 -9
@@ -1,30 +1,42 @@
1 +import os
2 +
3 from composio import Composio
4 from composio.types import auth_scheme
5
6 composio = Composio()
7
8 +# Auth config to connect against and the connecting user (raise KeyError when unset)
9 +gmail_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"]
10 +user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
11 +
12 # List all connected accounts
13 connected_accounts = composio.connected_accounts.list()
14 print(connected_accounts)
15
10 -# Create a new connected account (OAuth)
16 +# Create a new connected account (OAuth). The user may already have a
17 +# connected account for this auth config, so allow another one.
18 connection_request = composio.connected_accounts.initiate(
12 - user_id="1234567890",
13 - auth_config_id="1234567890",
19 + user_id=user_id,
20 + auth_config_id=gmail_auth_config_id,
21 + allow_multiple=True,
22 )
15 -print(connection_request)
23 +
24 +# Send the user to this URL to authorize the connection
25 +print(f"Visit this URL to authorize: {connection_request.redirect_url}")
26
27 # Wait for the connection to be established (OAuth)
28 connected_account = connection_request.wait_for_connection()
19 -print(connected_account)
29 +# Print identifying fields only: the full object carries live OAuth credentials.
30 +print(f"Connected account {connected_account.id} is {connected_account.status}")
31
32 # Create a new connected account (API Key)
33 connection_request = composio.connected_accounts.initiate(
23 - user_id="1234567890",
24 - auth_config_id="1234567890",
34 + user_id=user_id,
35 + auth_config_id=os.environ["COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID"],
36 + allow_multiple=True,
37 config=auth_scheme.api_key(
26 - options={
27 - "api_key": "1234567890",
38 + options={ # type: ignore[arg-type] # api_key() injects "status"; the field is Required on the generated TypedDict but not needed here
39 + "generic_api_key": os.environ["COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER"],
40 },
41 ),
42 )
python/examples/custom_tools_agent_test.py
+4 -8
@@ -21,7 +21,6 @@ from composio import Composio
21 from composio_openai_agents import OpenAIAgentsProvider
22
23 composio = Composio(
24 - base_url=os.environ.get("COMPOSIO_BASE_URL"),
24 provider=OpenAIAgentsProvider(),
25 )
26
@@ -164,20 +163,14 @@ async def run_test(prompt, test_name):
163
164
165 async def main():
166 + # One test per custom-tool pattern: standalone, custom toolkit, extension.
167 tests = [
168 ("Look up user-2", "Standalone (inferred slug/name)"),
169 - ("Generate a formal greeting for Alice", "Standalone (overridden slug/name)"),
169 ("Set user-1 role to developer", "Toolkit tool"),
171 - ("Look up user-1 and set their role to viewer", "Mixed local tools"),
172 - ("What is the weather in Tokyo?", "Remote (weathermap)"),
170 (
171 'Draft an email to bob@acme.com with subject "Test" and body "Hello!"',
172 "Gmail proxy",
173 ),
177 - (
178 - "Look up user-1, draft them an email saying hi, include weather in SF",
179 - "Mixed all",
180 - ),
174 ]
175
176 results = []
@@ -192,6 +185,9 @@ async def main():
185 print(f" [{'PASS' if ok else 'FAIL'}] {name}")
186 print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")
187
188 + if not all(ok for _, ok in results):
189 + sys.exit(1)
190 +
191
192 if __name__ == "__main__":
193 if not os.environ.get("OPENAI_API_KEY"):
python/examples/experimental_tool_router_advanced_example.py
+54 -35
@@ -5,18 +5,30 @@ This example shows various ways to configure tool router sessions with
5 different parameters matching the TypeScript implementation.
6 """
7
8 +import os
9 +
10 from composio import Composio
11
12 # Initialize Composio SDK
13 composio = Composio()
14
15 +# Provisioned project state (raise KeyError when unset). Auth config and
16 +# connected account ids are validated by the backend, so real ids are required.
17 +user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
18 +github_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GITHUB_AUTH_CONFIG_ID"]
19 +slack_auth_config_id = os.environ["COMPOSIO_EXAMPLES_SLACK_AUTH_CONFIG_ID"]
20 +github_connected_account_id = os.environ[
21 + "COMPOSIO_EXAMPLES_GITHUB_CONNECTED_ACCOUNT_ID"
22 +]
23 +slack_connected_account_id = os.environ["COMPOSIO_EXAMPLES_SLACK_CONNECTED_ACCOUNT_ID"]
24 +
25
26 def example_with_specific_toolkits():
27 """Create a session with specific toolkits enabled."""
28 print("=== Specific Toolkits Example ===")
29
30 session = composio.tool_router.create(
19 - user_id="user_toolkit", toolkits=["github", "slack", "linear"]
31 + user_id=user_id, toolkits=["github", "slack", "linear"]
32 )
33
34 print(f"Session ID: {session.session_id}")
@@ -29,7 +41,7 @@ def example_with_disabled_toolkits():
41 print("\n=== Disabled Toolkits Example ===")
42
43 session = composio.tool_router.create(
32 - user_id="user_disabled", toolkits={"disabled": ["linear", "jira"]}
44 + user_id=user_id, toolkits={"disable": ["linear", "jira"]}
45 )
46
47 print(f"Session ID: {session.session_id}")
@@ -42,10 +54,10 @@ def example_with_connection_management_config():
54 print("\n=== Connection Management with Callback Example ===")
55
56 session = composio.tool_router.create(
45 - user_id="user_callback",
57 + user_id=user_id,
58 manage_connections={
47 - "enabled": True,
48 - "callback_uri": "https://myapp.com/oauth/callback",
59 + "enable": True,
60 + "callback_url": "https://myapp.com/oauth/callback",
61 },
62 )
63
@@ -59,13 +71,15 @@ def example_with_auth_configs():
71 print("\n=== Auth Configs Example ===")
72
73 session = composio.tool_router.create(
62 - user_id="user_auth",
74 + user_id=user_id,
75 toolkits=["github", "slack"],
64 - auth_configs={"github": "ac_github_123", "slack": "ac_slack_456"},
76 + auth_configs={"github": github_auth_config_id, "slack": slack_auth_config_id},
77 )
78
79 print(f"Session ID: {session.session_id}")
68 - print("Auth configs: github → ac_github_123, slack → ac_slack_456")
80 + print(
81 + f"Auth configs: github → {github_auth_config_id}, slack → {slack_auth_config_id}"
82 + )
83 return session
84
85
@@ -74,13 +88,19 @@ def example_with_connected_accounts():
88 print("\n=== Connected Accounts Example ===")
89
90 session = composio.tool_router.create(
77 - user_id="user_connected",
91 + user_id=user_id,
92 toolkits=["github", "slack"],
79 - connected_accounts={"github": "ca_github_789", "slack": "ca_slack_012"},
93 + connected_accounts={
94 + "github": github_connected_account_id,
95 + "slack": slack_connected_account_id,
96 + },
97 )
98
99 print(f"Session ID: {session.session_id}")
83 - print("Connected accounts: github → ca_github_789, slack → ca_slack_012")
100 + print(
101 + f"Connected accounts: github → {github_connected_account_id}, "
102 + f"slack → {slack_connected_account_id}"
103 + )
104 return session
105
106
@@ -89,24 +109,26 @@ def example_with_all_parameters():
109 print("\n=== All Parameters Example ===")
110
111 session = composio.tool_router.create(
92 - user_id="user_complete",
93 - toolkits=["github", "slack", "notion"],
112 + user_id=user_id,
113 + toolkits=["github", "slack"],
114 manage_connections={
95 - "enabled": True,
96 - "callback_uri": "https://myapp.com/callback",
115 + "enable": True,
116 + "callback_url": "https://myapp.com/callback",
117 },
118 auth_configs={
99 - "github": "ac_github_xyz",
100 - "slack": "ac_slack_abc",
101 - "notion": "ac_notion_def",
119 + "github": github_auth_config_id,
120 + "slack": slack_auth_config_id,
121 + },
122 + connected_accounts={
123 + "github": github_connected_account_id,
124 + "slack": slack_connected_account_id,
125 },
103 - connected_accounts={"github": "ca_github_111", "slack": "ca_slack_222"},
126 )
127
128 print(f"✓ Session ID: {session.session_id}")
107 - print("✓ Toolkits: github, slack, notion")
129 + print("✓ Toolkits: github, slack")
130 print("✓ Connection management: enabled with callback")
109 - print("✓ Auth configs: configured for 3 toolkits")
131 + print("✓ Auth configs: configured for 2 toolkits")
132 print("✓ Connected accounts: 2 pre-configured")
133
134 return session
@@ -117,16 +139,16 @@ def example_minimal_vs_maximal():
139 print("\n=== Minimal vs Maximal Example ===")
140
141 # Minimal - just user ID
120 - minimal_session = composio.tool_router.create(user_id="user_minimal")
142 + minimal_session = composio.tool_router.create(user_id=user_id)
143 print(f"Minimal session: {minimal_session.session_id}")
144
145 # Maximal - all options
146 maximal_session = composio.tool_router.create(
125 - user_id="user_maximal",
147 + user_id=user_id,
148 toolkits=["github", "slack"],
127 - manage_connections={"enabled": True, "callback_uri": "https://app.com/cb"},
128 - auth_configs={"github": "ac_1", "slack": "ac_2"},
129 - connected_accounts={"github": "ca_1"},
149 + manage_connections={"enable": True, "callback_url": "https://app.com/cb"},
150 + auth_configs={"github": github_auth_config_id, "slack": slack_auth_config_id},
151 + connected_accounts={"github": github_connected_account_id},
152 )
153 print(f"Maximal session: {maximal_session.session_id}")
154
@@ -139,21 +161,20 @@ def example_type_safe_configuration():
161
162 from composio.core.models.tool_router import (
163 ToolRouterManageConnectionsConfig,
142 - ToolRouterToolkitsDisabledConfig,
164 + ToolRouterToolkitsDisableConfig,
165 )
166
167 # Type-safe toolkit config
146 - toolkit_config: ToolRouterToolkitsDisabledConfig = {"disabled": ["linear", "asana"]}
168 + toolkit_config: ToolRouterToolkitsDisableConfig = {"disable": ["linear", "asana"]}
169
170 # Type-safe connection management config
171 connection_config: ToolRouterManageConnectionsConfig = {
150 - "enabled": True,
151 - "callback_uri": "https://secure.app.com/oauth",
152 - "infer_scopes_from_tools": False,
172 + "enable": True,
173 + "callback_url": "https://secure.app.com/oauth",
174 }
175
176 session = composio.tool_router.create(
156 - user_id="user_typesafe",
177 + user_id=user_id,
178 toolkits=toolkit_config,
179 manage_connections=connection_config,
180 )
@@ -184,6 +205,4 @@ if __name__ == "__main__":
205
206 except Exception as e:
207 print(f"\n✗ Error running examples: {e}")
187 - import traceback
188 -
189 - traceback.print_exc()
208 + raise
python/examples/experimental_tool_router_example.py
+18 -25
@@ -5,21 +5,27 @@ This example shows how to create a tool router session for a user,
5 get provider-wrapped tools, and authorize toolkits.
6 """
7
8 +import os
9 +
10 from composio import Composio
11
12 # Initialize Composio SDK
13 composio = Composio()
14
15 +# Provisioned project state (raises KeyError when unset). The backend validates
16 +# auth config ids, so a placeholder would abort session creation.
17 +user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
18 +github_auth_config_id = os.environ["COMPOSIO_EXAMPLES_GITHUB_AUTH_CONFIG_ID"]
19 +
20
21 # Example 1: Create a basic tool router session
22 def basic_session_example():
23 """Create a basic tool router session."""
24 print("=== Basic Session Example ===")
25
19 - user_id = "user_123"
20 -
21 - # Create a tool router session
22 - session = composio.tool_router.create(user_id=user_id)
26 + # Create a tool router session. mcp=True surfaces session.mcp on the
27 + # returned type; without it the endpoint exists but is not typed.
28 + session = composio.tool_router.create(user_id=user_id, mcp=True)
29
30 print(f"Session ID: {session.session_id}")
31 print(f"MCP Server Type: {session.mcp.type}")
@@ -39,8 +45,6 @@ def session_with_connections_example():
45 """Create a session with connection management enabled."""
46 print("\n=== Session with Connection Management ===")
47
42 - user_id = "user_456"
43 -
48 # Create a tool router session with connection management
49 session = composio.tool_router.create(user_id=user_id, manage_connections=True)
50
@@ -61,8 +65,6 @@ def authorize_toolkit_example():
65 """Demonstrate toolkit authorization."""
66 print("\n=== Authorize Toolkit Example ===")
67
64 - user_id = "user_789"
65 -
68 # Create a session
69 session = composio.tool_router.create(user_id=user_id)
70
@@ -80,7 +82,7 @@ def authorize_toolkit_example():
82 return connection_request
83 except Exception as e:
84 print(f"Error authorizing toolkit: {e}")
83 - return None
85 + raise
86
87
88 # Example 4: Get toolkit connection states
@@ -88,8 +90,6 @@ def get_toolkits_example():
90 """Get toolkit connection states for a session."""
91 print("\n=== Get Toolkits Example ===")
92
91 - user_id = "user_101"
92 -
93 # Create a session
94 session = composio.tool_router.create(user_id=user_id)
95
@@ -106,14 +106,12 @@ def full_workflow_example():
106 """Complete workflow with session, tools, and authorization."""
107 print("\n=== Full Workflow Example ===")
108
109 - user_id = "user_full"
110 -
109 # 1. Create session with multiple configurations
110 session = composio.tool_router.create(
111 user_id=user_id,
112 toolkits=["github", "slack"],
113 manage_connections=True,
116 - auth_configs={"github": "ac_demo_123"},
114 + auth_configs={"github": github_auth_config_id},
115 )
116
117 print(f"✓ Created session: {session.session_id}")
@@ -135,6 +133,7 @@ def full_workflow_example():
133 print(f" → Redirect URL: {connection_request.redirect_url}")
134 except Exception as e:
135 print(f"✗ Authorization error: {e}")
136 + raise
137
138 return session
139
@@ -144,18 +143,14 @@ def session_with_modifiers_example():
143 """Create a session and use tools with custom modifiers."""
144 print("\n=== Session with Modifiers Example ===")
145
147 - user_id = "user_modifiers"
148 -
146 # Create session
147 session = composio.tool_router.create(user_id=user_id)
148
152 - # Get tools with custom modifiers
153 - modifiers = {
154 - # Add any custom modifiers here
155 - # Example: timeout, custom headers, etc.
156 - }
149 + # Modifiers are a list of before/after execute hooks; an empty list means
150 + # "no modifiers", which is what this example passes.
151 + modifiers: list = []
152
158 - tools = session.tools(modifiers=modifiers if modifiers else None)
153 + tools = session.tools(modifiers=modifiers or None)
154 print(
155 f"✓ Retrieved {len(tools) if isinstance(tools, list) else 'N/A'} tools with modifiers"
156 )
@@ -182,6 +177,4 @@ if __name__ == "__main__":
177
178 except Exception as e:
179 print(f"\n✗ Error running examples: {e}")
185 - import traceback
186 -
187 - traceback.print_exc()
180 + raise
python/examples/fastapi_app.py
+17 -2
@@ -1,3 +1,5 @@
1 +import os
2 +
3 from fastapi import FastAPI
4 from fastapi.responses import RedirectResponse
5
@@ -13,10 +15,10 @@ composio = Composio()
15 @app.get("/authorize/{toolkit}")
16 def authorize_app(toolkit: str):
17 # retrieve the user id from your app
16 - user_id = ""
18 + user_id = os.environ.get("COMPOSIO_EXAMPLES_USER_ID", "")
19
20 # retrieve the auth config id from your app
19 - auth_config_id = ""
21 + auth_config_id = os.environ.get("COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID", "")
22
23 # initiate the connection request
24 connection_request = composio.connected_accounts.initiate(
@@ -24,3 +26,16 @@ def authorize_app(toolkit: str):
26 auth_config_id=auth_config_id,
27 )
28 return RedirectResponse(url=connection_request.redirect_url) # type: ignore
29 +
30 +
31 +if __name__ == "__main__":
32 + import uvicorn
33 +
34 + for var in ("COMPOSIO_EXAMPLES_USER_ID", "COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"):
35 + if not os.environ.get(var):
36 + raise SystemExit(f"{var} is required")
37 +
38 + # Fail fast on bad credentials or a stale auth config before serving requests
39 + composio.auth_configs.get(os.environ["COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID"])
40 +
41 + uvicorn.run(app, host="127.0.0.1", port=8000)
python/examples/mcp.py deleted
-34
@@ -1,34 +0,0 @@
1 -import asyncio
2 -
3 -from langchain_mcp_adapters.client import MultiServerMCPClient
4 -from langgraph.prebuilt import create_react_agent
5 -
6 -from composio import Composio
7 -
8 -composio = Composio()
9 -
10 -mcp_config = composio.mcp.create(
11 - name="langchain-slack-mcp",
12 - toolkits=[{"toolkit": "slack", "auth_config_id": "<auth-config-id>"}],
13 -)
14 -
15 -mcp_server = mcp_config.generate(user_id="<user-id>")
16 -
17 -client = MultiServerMCPClient(
18 - {
19 - "composio": {
20 - "url": mcp_server["url"],
21 - "transport": "streamable_http",
22 - }
23 - }
24 -)
25 -
26 -
27 -async def langchain_mcp(message: str):
28 - tools = await client.get_tools()
29 - agent = create_react_agent("openai:gpt-4.1", tools)
30 - response = await agent.ainvoke({"messages": message})
31 - return response
32 -
33 -
34 -mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
python/examples/mcp_example.py new
+47
@@ -0,0 +1,47 @@
1 +import asyncio
2 +import os
3 +import time
4 +
5 +from langchain_mcp_adapters.client import MultiServerMCPClient
6 +from langgraph.prebuilt import create_react_agent
7 +
8 +from composio import Composio
9 +
10 +composio = Composio()
11 +
12 +# Slack auth config and user id (raise KeyError when unset)
13 +slack_auth_config_id = os.environ["COMPOSIO_EXAMPLES_SLACK_AUTH_CONFIG_ID"]
14 +user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
15 +
16 +mcp_config = composio.mcp.create(
17 + # Named `examples-<label>-<unix-seconds>` so the provisioning script's --gc
18 + # can tell this throwaway config from one created by hand. The API caps
19 + # this name at 30 characters, so the label stays short.
20 + name=f"examples-lc-slack-{int(time.time())}",
21 + toolkits=[{"toolkit": "slack", "auth_config_id": slack_auth_config_id}],
22 + # Keep the exposed tool list small; LLM providers cap tools per request
23 + allowed_tools=["SLACK_LIST_ALL_CHANNELS", "SLACK_SEARCH_MESSAGES"],
24 +)
25 +
26 +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
27 +
28 +client = MultiServerMCPClient(
29 + {
30 + "composio": {
31 + "url": mcp_server["url"],
32 + "transport": "streamable_http",
33 + # The MCP endpoint authenticates with your Composio API key
34 + "headers": {"x-api-key": os.environ["COMPOSIO_API_KEY"]},
35 + }
36 + }
37 +)
38 +
39 +
40 +async def langchain_mcp(message: str):
41 + tools = await client.get_tools()
42 + agent = create_react_agent("openai:gpt-4.1", tools)
43 + response = await agent.ainvoke({"messages": message})
44 + return response
45 +
46 +
47 +mcp_response = asyncio.run(langchain_mcp("Show me 20 most used slack channels"))
python/examples/tool_router/claude_agent.py
+5 -1
@@ -1,4 +1,5 @@
1 import asyncio
2 +import os
3
4 from claude_agent_sdk import ClaudeAgentOptions, query
5 from composio_claude_agent_sdk import ClaudeAgentSDKProvider
@@ -7,7 +8,10 @@ from composio import Composio
8
9 composio = Composio(provider=ClaudeAgentSDKProvider())
10 session = composio.create(
10 - user_id="user_123",
11 + # A user with a connected Gmail account (raises KeyError when unset)
12 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
13 + # mcp=True surfaces session.mcp on the returned type
14 + mcp=True,
15 )
16
17
python/examples/tool_router/crewai_agent.py
+7 -2
@@ -1,3 +1,5 @@
1 +import os
2 +
3 from crewai import Agent, Crew, Task
4 from crewai.mcp import MCPServerHTTP
5
@@ -5,7 +7,10 @@ from composio import Composio
7
8 composio = Composio()
9 session = composio.create(
8 - user_id="user_123",
10 + # A user with a connected Gmail account (raises KeyError when unset)
11 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
12 + # mcp=True surfaces session.mcp on the returned type
13 + mcp=True,
14 )
15
16 agent = Agent(
@@ -15,7 +20,7 @@ agent = Agent(
20 mcps=[
21 MCPServerHTTP(
22 url=session.mcp.url,
18 - headers=session.mcp.headers,
23 + headers=session.mcp.headers, # type: ignore[arg-type] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values
24 )
25 ],
26 )
python/examples/tool_router/direct_tools_preset.py
-1
@@ -27,7 +27,6 @@ def require_env(name: str) -> str:
27
28 composio = Composio(
29 api_key=require_env("COMPOSIO_API_KEY"),
30 - base_url=os.environ.get("COMPOSIO_BASE_URL"),
30 provider=OpenAIAgentsProvider(),
31 )
32 require_env("OPENAI_API_KEY")
python/examples/tool_router/langchain_agent.py
+26 -25
@@ -1,4 +1,5 @@
1 import asyncio
2 +import os
3
4 from langchain.agents import create_agent
5 from langchain_mcp_adapters.client import MultiServerMCPClient
@@ -8,40 +9,40 @@ from composio import Composio
9
10 composio = Composio()
11 session = composio.create(
11 - user_id="user_123",
12 + # A user with a connected Gmail account (raises KeyError when unset)
13 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
14 + # mcp=True surfaces session.mcp on the returned type
15 + mcp=True,
16 )
17
18
19 async def main():
16 - try:
17 - mcp_client = MultiServerMCPClient(
18 - {
19 - "composio": {
20 - "transport": "streamable_http",
21 - "url": session.mcp.url,
22 - "headers": session.mcp.headers,
23 - }
20 + mcp_client = MultiServerMCPClient(
21 + {
22 + "composio": {
23 + "transport": "streamable_http",
24 + "url": session.mcp.url,
25 + "headers": session.mcp.headers,
26 }
25 - )
27 + }
28 + )
29
27 - tools = await mcp_client.get_tools()
30 + tools = await mcp_client.get_tools()
31
29 - agent = create_agent(
30 - tools=tools,
31 - model=ChatOpenAI(model="gpt-4o"),
32 - )
32 + agent = create_agent(
33 + tools=tools,
34 + model=ChatOpenAI(model="gpt-4o"),
35 + )
36
34 - result = await agent.ainvoke(
35 - {
36 - "messages": [
37 - {"role": "user", "content": "Fetch my last email and summarize?"}
38 - ]
39 - }
40 - )
37 + result = await agent.ainvoke(
38 + {
39 + "messages": [
40 + {"role": "user", "content": "Fetch my last email and summarize?"}
41 + ]
42 + }
43 + )
44
42 - print(result)
43 - except Exception as e:
44 - print(e)
45 + print(result)
46
47
48 if __name__ == "__main__":
python/examples/tool_router/openai_agents.py
+7 -2
@@ -1,10 +1,15 @@
1 +import os
2 +
3 from agents import Agent, HostedMCPTool, Runner
4
5 from composio import Composio
6
7 composio = Composio()
8 session = composio.create(
7 - user_id="user_123",
9 + # A user with a connected Gmail account (raises KeyError when unset)
10 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
11 + # mcp=True surfaces session.mcp on the returned type
12 + mcp=True,
13 )
14
15 print(session.mcp)
@@ -15,7 +20,7 @@ composio_mcp = HostedMCPTool(
20 "server_label": "tool_router",
21 "server_url": session.mcp.url,
22 "require_approval": "never",
18 - "headers": session.mcp.headers,
23 + "headers": session.mcp.headers, # type: ignore[typeddict-item] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values
24 }
25 )
26
python/examples/tool_router/preload.py
-1
@@ -58,7 +58,6 @@ INTERNAL_USERS = {
58
59 composio = Composio(
60 api_key=require_env("COMPOSIO_API_KEY"),
61 - base_url=os.environ.get("COMPOSIO_BASE_URL"),
61 provider=OpenAIAgentsProvider(),
62 )
63 require_env("OPENAI_API_KEY")
python/examples/tool_router/session_update.py
+3 -2
@@ -10,11 +10,12 @@ import os
10
11 from composio import Composio
12
13 -composio = Composio(base_url=os.environ.get("COMPOSIO_BASE_URL"))
13 +composio = Composio()
14
15 # Create a session with gmail only
16 session = composio.create(
17 - user_id="session-update-demo",
17 + # The provisioned examples user (raises KeyError when unset)
18 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
19 toolkits=["gmail"],
20 manage_connections=False,
21 )
python/examples/tool_router/tool_router_mcp.py
+5 -2
@@ -28,8 +28,11 @@ async def main():
28
29 # Create a tool router session
30 session = composio.create(
31 - user_id="user_123",
31 + # A user with connected GitHub and Gmail accounts (raises KeyError when unset)
32 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
33 toolkits=["github", "gmail"],
34 + # mcp=True surfaces session.mcp on the returned type
35 + mcp=True,
36 )
37
38 mcpTool = HostedMCPTool(
@@ -38,7 +41,7 @@ async def main():
41 "server_label": "tool_router",
42 "server_url": session.mcp.url,
43 "require_approval": "never",
41 - "headers": session.mcp.headers,
44 + "headers": session.mcp.headers, # type: ignore[typeddict-item] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values
45 }
46 )
47
python/examples/tool_router/toolkits.py
+6 -1
@@ -5,6 +5,8 @@ This example demonstrates how to retrieve available toolkits
5 and their connection status in a Tool Router session.
6 """
7
8 +import os
9 +
10 from composio import Composio
11
12 composio = Composio()
@@ -12,8 +14,11 @@ composio = Composio()
14 # Create a tool router session
15 # When manage_connections is enabled, tools for managing connections are included
16 session = composio.create(
15 - user_id="pg-test-37ee710c-d5be-4775-91f2-a8e06b937d9b",
17 + # The provisioned examples user (raises KeyError when unset)
18 + user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
19 manage_connections=True,
20 + # mcp=True surfaces session.mcp on the returned type
21 + mcp=True,
22 )
23
24 print(f"Session created: {session.session_id}")
python/examples/tools.py
+8 -1
@@ -1,7 +1,14 @@
1 +import os
2 +
3 from composio import Composio
4
5 composio = Composio()
6
7 +# Connected account with GitHub access (raises KeyError when unset)
8 +github_connected_account_id = os.environ[
9 + "COMPOSIO_EXAMPLES_GITHUB_CONNECTED_ACCOUNT_ID"
10 +]
11 +
12 # Get all tools by toolkit
13 tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
14
@@ -24,7 +31,7 @@ print(response)
31 proxy_response = composio.tools.proxy(
32 endpoint="/repos/composiohq/composio/issues/1",
33 method="GET",
27 - connected_account_id="ac_1234", # use connected account for github
34 + connected_account_id=github_connected_account_id, # use connected account for github
35 parameters=[
36 {
37 "name": "Accept",
python/examples/triggers.py
+19 -18
@@ -1,7 +1,13 @@
1 +import os
2 +
3 from composio import Composio
4
5 composio = Composio()
6
7 +# Connected account with Gmail access and its owner (raise KeyError when unset)
8 +gmail_connected_account_id = os.environ["COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID"]
9 +user_id = os.environ["COMPOSIO_EXAMPLES_USER_ID"]
10 +
11
12 # List all triggers
13 triggers = composio.triggers.list()
@@ -16,41 +22,35 @@ trigger_enums = composio.triggers.list_enum()
22 print(trigger_enums)
23
24 # Get a trigger by id
19 -trigger = composio.triggers.get_type(slug="GITHUB_COMMIT_EVENT")
25 +trigger = composio.triggers.get_type(slug="GMAIL_NEW_GMAIL_MESSAGE")
26 print(trigger)
27
22 -# Create a trigger instance
28 +# Create a trigger instance pinned to a connected account
29 instance = composio.triggers.create(
24 - slug="GITHUB_COMMIT_EVENT",
25 - connected_account_id="123",
26 - trigger_config={
27 - "repo": "composio",
28 - "owner": "composiohq",
29 - },
30 + slug="GMAIL_NEW_GMAIL_MESSAGE",
31 + connected_account_id=gmail_connected_account_id,
32 + trigger_config={},
33 )
34 print(instance)
35
33 -# Or use user ID
36 +# Or use user ID and let the backend resolve the active connection
37 instance = composio.triggers.create(
35 - slug="GITHUB_COMMIT_EVENT",
36 - user_id="user@email.com",
37 - trigger_config={
38 - "repo": "composio",
39 - "owner": "composiohq",
40 - },
38 + slug="GMAIL_NEW_GMAIL_MESSAGE",
39 + user_id=user_id,
40 + trigger_config={},
41 )
42 print(instance)
43
44 # Disable a trigger instance
45 -disabled_instance = composio.triggers.disable(trigger_id="123")
45 +disabled_instance = composio.triggers.disable(trigger_id=instance.trigger_id)
46 print(disabled_instance)
47
48 # Enable a trigger instance
49 -enabled_instance = composio.triggers.enable(trigger_id="123")
49 +enabled_instance = composio.triggers.enable(trigger_id=instance.trigger_id)
50 print(enabled_instance)
51
52 # Delete a trigger instance
53 -deleted_instance = composio.triggers.delete(trigger_id="123")
53 +deleted_instance = composio.triggers.delete(trigger_id=instance.trigger_id)
54 print(deleted_instance)
55
56
@@ -92,4 +92,5 @@ def handle_slack_event(data):
92 print(data)
93
94
95 +print("Subscribed to triggers. Waiting for events...", flush=True)
96 subscription.wait_forever()
python/noxfile.py
+25
@@ -75,6 +75,31 @@ def fix(session: Session):
75 session.run(*ruff, "check", "--fix", *modules_for_ruff)
76
77
78 +@nox.session
79 +def chk_examples(session: Session):
80 + """Type-check example scripts against the SDK surface.
81 +
82 + Examples run one mypy invocation per file: duplicate basenames
83 + (examples/tools.py, examples/tool_router/tools.py) collide as module
84 + names inside a single run. Third-party agent frameworks stay
85 + unresolved on purpose; the check targets composio API usage.
86 + """
87 + from pathlib import Path
88 +
89 + session.install(".", "--group", "dev", mypy, *type_stubs)
90 + for path in sorted(Path("examples").rglob("*.py")):
91 + session.run(
92 + "mypy",
93 + "--config-file",
94 + "config/mypy.ini",
95 + "--ignore-missing-imports",
96 + # Examples wrap their bodies in unannotated main()s; without this
97 + # mypy skips those bodies entirely and the gate checks almost nothing.
98 + "--check-untyped-defs",
99 + str(path),
100 + )
101 +
102 +
103 @nox.session
104 def tst(session: Session):
105 """Run the Python unit test suite."""
scripts/examples-provision.mjs new
+314
@@ -0,0 +1,314 @@
1 +#!/usr/bin/env node
2 +// Idempotent provisioning check for the live example runs.
3 +//
4 +// Verifies that the dedicated (disposable) Composio project holds the auth
5 +// configs and connected accounts the tier-2/3 examples need, creates whatever
6 +// can be created without a human (API-key auth config), and
7 +// prints the remaining one-time OAuth authorizations.
8 +//
9 +// node scripts/examples-provision.mjs # report (stderr) + exports (stdout)
10 +// out=$(node scripts/examples-provision.mjs) && eval "$out"
11 +// load COMPOSIO_EXAMPLES_* into the shell. Do NOT collapse this into
12 +// eval "$(...)": eval reports the status of the text it evaluates, so a
13 +// failed provisioning run would look like success.
14 +// node scripts/examples-provision.mjs --initiate-missing
15 +// also starts an OAuth connection request for each missing account and
16 +// prints the redirect URL to authorize it (one browser visit per toolkit)
17 +// node scripts/examples-provision.mjs --gc [--dry-run]
18 +// DESTRUCTIVE. Deletes resources example runs leak into the project:
19 +// connected accounts that never became ACTIVE, surplus serpapi demo
20 +// accounts, and MCP configs named `examples-<label>-<unix-seconds>`,
21 +// which is the name every example gives the configs it creates.
22 +// Configs from runs predating that convention are not matched.
23 +// Connected accounts are only ever deleted when they are bound to an
24 +// `examples-<slug>` auth config, which only this script creates. An
25 +// account the examples did not create is never touched, whatever user
26 +// owns it. Only resources older than 24h are removed, so a concurrent run
27 +// is safe. Preview with --dry-run.
28 +//
29 +// Auth config ids and connected account ids are not secrets; no credential
30 +// values are ever printed. The API-key demo value stored for serpapi is a
31 +// deliberately fake placeholder, not a real key.
32 +
33 +const BASE_URL = process.env.COMPOSIO_BASE_URL ?? 'https://backend.composio.dev';
34 +const API_KEY = process.env.COMPOSIO_API_KEY;
35 +const USER_ID = process.env.COMPOSIO_EXAMPLES_USER_ID ?? 'examples';
36 +const INITIATE_MISSING = process.argv.includes('--initiate-missing');
37 +const GC = process.argv.includes('--gc');
38 +const DRY_RUN = process.argv.includes('--dry-run');
39 +
40 +// The examples only ever run against the production backend with the
41 +// disposable project key. Allowlist the Composio hosts rather than denylisting
42 +// loopback spellings: the API key travels in every request, so anything that is
43 +// not a Composio backend must be refused, not just localhost.
44 +const { baseHost, baseProtocol } = (() => {
45 + try {
46 + const url = new URL(BASE_URL);
47 + return { baseHost: url.hostname, baseProtocol: url.protocol };
48 + } catch {
49 + return { baseHost: null, baseProtocol: null };
50 + }
51 +})();
52 +if (!baseHost || !(baseHost === 'composio.dev' || baseHost.endsWith('.composio.dev'))) {
53 + console.error(`refusing non-Composio COMPOSIO_BASE_URL: ${BASE_URL}`);
54 + process.exit(1);
55 +}
56 +if (baseProtocol !== 'https:') {
57 + // The API key is sent on every request. Plain http would put it on the wire.
58 + console.error(`refusing non-https COMPOSIO_BASE_URL: ${BASE_URL}`);
59 + process.exit(1);
60 +}
61 +if (!API_KEY) {
62 + console.error('COMPOSIO_API_KEY is required (dedicated examples-project key)');
63 + process.exit(1);
64 +}
65 +
66 +// Toolkits the tier-2/3 entries depend on. OAuth toolkits need a one-time human
67 +// browser authorization. Only export ids that examples consume directly.
68 +const BROWSER_GRANT_TOOLKITS = [
69 + { exportPrefix: 'GMAIL', slug: 'gmail' },
70 + // googledrive exports nothing: examples reach Drive through the user's
71 + // standing connection (COMPOSIO_EXAMPLES_USER_ID), never through ids.
72 + { slug: 'googledrive' },
73 + { exportPrefix: 'GITHUB', slug: 'github' },
74 + { exportPrefix: 'SLACK', slug: 'slack' },
75 +];
76 +const DEMO_TOOLKIT = { exportPrefix: 'APIKEY', slug: 'serpapi', demoValue: 'examples-demo-key' };
77 +
78 +const report = line => console.error(line);
79 +
80 +async function api(method, path, body) {
81 + const res = await fetch(`${BASE_URL}${path}`, {
82 + method,
83 + headers: { 'x-api-key': API_KEY, 'content-type': 'application/json' },
84 + body: body === undefined ? undefined : JSON.stringify(body),
85 + // Without this a hung backend hangs the whole run instead of failing it.
86 + signal: AbortSignal.timeout(30_000),
87 + // The host allowlist above only checks BASE_URL. fetch follows redirects by
88 + // default and forwards x-api-key across origins (only Authorization is
89 + // stripped), so a 3xx would hand the key to whatever host it names.
90 + redirect: 'error',
91 + });
92 + const text = await res.text();
93 + if (!res.ok) {
94 + throw new Error(`${method} ${path} -> ${res.status}: ${text.slice(0, 300)}`);
95 + }
96 + return text ? JSON.parse(text) : undefined;
97 +}
98 +
99 +// Two pagination shapes are in play. Most v3.1 collections (auth_configs,
100 +// connected_accounts) return `next_cursor`; /mcp/servers never does and reports
101 +// current_page/total_pages instead. Follow whichever the response actually
102 +// offers, otherwise the MCP cleanup silently stops after one page.
103 +const MAX_PAGES = 50;
104 +
105 +async function listAll(path, key = 'items') {
106 + const out = [];
107 + let cursor;
108 + let pageNo = 1;
109 + for (let page = 0; page < MAX_PAGES; page++) {
110 + const sep = path.includes('?') ? '&' : '?';
111 + let query = 'limit=100';
112 + if (cursor) query += `&cursor=${encodeURIComponent(cursor)}`;
113 + else if (pageNo > 1) query += `&page_no=${pageNo}`;
114 +
115 + const data = await api('GET', `${path}${sep}${query}`);
116 + out.push(...(data?.[key] ?? []));
117 +
118 + if (data?.next_cursor) {
119 + if (data.next_cursor === cursor) {
120 + report(`warning: ${path} repeated cursor ${cursor}; stopping to avoid a loop`);
121 + return out;
122 + }
123 + cursor = data.next_cursor;
124 + continue;
125 + }
126 +
127 + const totalPages = Number(data?.total_pages);
128 + const currentPage = Number(data?.current_page ?? pageNo);
129 + if (Number.isFinite(totalPages) && Number.isFinite(currentPage) && currentPage < totalPages) {
130 + // Clear the cursor before falling back to page numbers. Leaving it set
131 + // would resend the same cursor every iteration and repeat one page until
132 + // the page cap.
133 + cursor = undefined;
134 + pageNo = currentPage + 1;
135 + continue;
136 + }
137 + return out;
138 + }
139 + report(`warning: stopped paginating ${path} after ${MAX_PAGES} pages; results may be incomplete`);
140 + return out;
141 +}
142 +
143 +const [authConfigs, accounts] = await Promise.all([
144 + listAll('/api/v3.1/auth_configs'),
145 + listAll(`/api/v3.1/connected_accounts?user_ids=${encodeURIComponent(USER_ID)}`),
146 +]);
147 +
148 +if (GC) {
149 + const cutoff = Date.now() - 24 * 60 * 60 * 1000;
150 + // Fail closed: a missing or unparseable created_at must not read as "old
151 + // enough to delete", which `new Date(0)` would.
152 + const stale = r => {
153 + const created = new Date(r.created_at ?? '').getTime();
154 + return Number.isFinite(created) && created < cutoff;
155 + };
156 + const gcDelete = async (kind, path, item) => {
157 + const label = `${kind} ${item.id} (${item.toolkit?.slug ?? item.name}, created ${item.created_at})`;
158 + if (DRY_RUN) {
159 + report(`gc: would delete ${label}`);
160 + return;
161 + }
162 + await api('DELETE', path);
163 + report(`gc: deleted ${label}`);
164 + };
165 +
166 + // Ownership marker: this script is the only thing that creates auth configs
167 + // named `examples-<slug>`, so an account bound to one of them was created by
168 + // an example run. Match the name exactly. findAuthConfig's fallback to any
169 + // config for the toolkit is fine for reading, but must never authorise a
170 + // delete, or a project's own gmail config would look example-owned.
171 + // Keying on the auth config rather than the user id matters: some examples
172 + // connect as 'default' rather than COMPOSIO_EXAMPLES_USER_ID.
173 + const ownedNames = new Set(
174 + [...BROWSER_GRANT_TOOLKITS, DEMO_TOOLKIT].map(({ slug }) => `examples-${slug}`)
175 + );
176 + const ownedAuthConfigIds = new Set(
177 + authConfigs.filter(c => ownedNames.has(c.name)).map(c => c.id)
178 + );
179 + const isExampleOwned = a => ownedAuthConfigIds.has(a.auth_config?.id);
180 +
181 + if (ownedAuthConfigIds.size === 0) {
182 + report('gc: no examples-* auth configs in this project; skipping account cleanup');
183 + }
184 +
185 + // Among example-created accounts only: ones that never became ACTIVE are dead
186 + // weight from OAuth-initiating runs, and surplus serpapi demo accounts pile up
187 + // from api-key runs. The newest standing account per toolkit is never touched.
188 + const allAccounts = (await listAll('/api/v3.1/connected_accounts')).filter(isExampleOwned);
189 + const serpapiActive = allAccounts
190 + .filter(a => a.toolkit?.slug === 'serpapi' && a.status === 'ACTIVE')
191 + .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
192 + const doomedAccounts = [
193 + ...allAccounts.filter(a => a.status !== 'ACTIVE' && stale(a)),
194 + ...serpapiActive.slice(1).filter(stale),
195 + ];
196 + for (const account of doomedAccounts) {
197 + await gcDelete('connected account', `/api/v3.1/connected_accounts/${account.id}`, account);
198 + }
199 +
200 + // Example runs name their MCP configs `examples-<label>-<unix-seconds>`.
201 + // Both halves are load-bearing. The reserved `examples-` prefix is what proves
202 + // an example created it, and the trailing timestamp keeps a hand-made
203 + // `examples-scratch` out of the delete set. Matching a bare trailing digit run
204 + // instead would also claim names like `release-1754923456`. Seconds, not
205 + // milliseconds: the API caps MCP names at 30 characters.
206 + const EXAMPLE_MCP_NAME = /^examples-[a-z0-9-]+-\d{10}$/;
207 + const mcpServers = await listAll('/api/v3.1/mcp/servers');
208 + for (const server of mcpServers.filter(s => EXAMPLE_MCP_NAME.test(s.name ?? '') && stale(s))) {
209 + await gcDelete('mcp config', `/api/v3.1/mcp/${server.id}`, server);
210 + }
211 +}
212 +
213 +const exports = { COMPOSIO_EXAMPLES_USER_ID: USER_ID };
214 +const pendingGrants = [];
215 +let ok = true;
216 +
217 +function findAuthConfig(slug) {
218 + // Only the exactly-named config counts. Adopting a project's own config for
219 + // the same toolkit would bind example-created accounts to a config --gc does
220 + // not recognise, so they could never be cleaned up, and it would point the
221 + // examples at credentials the examples do not own.
222 + return authConfigs.find(
223 + c => c.toolkit?.slug === slug && c.status !== 'DISABLED' && c.name === `examples-${slug}`
224 + );
225 +}
226 +function findActiveAccount(slug, authConfigId) {
227 + // Must agree with findAuthConfig. Accepting any ACTIVE account for the toolkit
228 + // would pair a freshly created examples-<slug> config with an account bound to
229 + // a different one, report the run complete, and leave the examples-owned
230 + // config with no connection --initiate-missing would ever create.
231 + return accounts.find(
232 + a => a.toolkit?.slug === slug && a.status === 'ACTIVE' && a.auth_config?.id === authConfigId
233 + );
234 +}
235 +
236 +for (const { exportPrefix, slug } of BROWSER_GRANT_TOOLKITS) {
237 + let config = findAuthConfig(slug);
238 + if (!config) {
239 + const created = await api('POST', '/api/v3.1/auth_configs', {
240 + toolkit: { slug },
241 + auth_config: { type: 'use_composio_managed_auth', name: `examples-${slug}` },
242 + });
243 + config = { id: created.auth_config?.id ?? created.id };
244 + report(`created auth config for ${slug}: ${config.id}`);
245 + }
246 + if (exportPrefix) {
247 + exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;
248 + }
249 +
250 + const account = findActiveAccount(slug, config.id);
251 + if (account) {
252 + if (exportPrefix) {
253 + exports[`COMPOSIO_EXAMPLES_${exportPrefix}_CONNECTED_ACCOUNT_ID`] = account.id;
254 + }
255 + report(`${slug}: ACTIVE connection ${account.id} (user ${USER_ID})`);
256 + } else {
257 + ok = false;
258 + if (INITIATE_MISSING) {
259 + const created = await api('POST', '/api/v3.1/connected_accounts', {
260 + auth_config: { id: config.id },
261 + connection: { user_id: USER_ID },
262 + });
263 + pendingGrants.push(
264 + `${slug}: authorize in a browser -> ${created.connectionData?.val?.redirectUrl ?? created.redirect_url ?? created.redirect_uri ?? '(no redirect url returned)'}`
265 + );
266 + } else {
267 + pendingGrants.push(
268 + `${slug}: no ACTIVE connection for user ${USER_ID} — rerun with --initiate-missing to get an authorization URL`
269 + );
270 + }
271 + }
272 +}
273 +
274 +// API-key toolkit: create the auth config automatically. The examples create
275 +// their own connected accounts to demonstrate that API. The stored value is a
276 +// placeholder; serpapi only validates it at tool-execution time and no example
277 +// executes a serpapi tool.
278 +{
279 + const { exportPrefix, slug, demoValue } = DEMO_TOOLKIT;
280 + let config = findAuthConfig(slug);
281 + if (!config) {
282 + const created = await api('POST', '/api/v3.1/auth_configs', {
283 + toolkit: { slug },
284 + auth_config: { type: 'use_custom_auth', authScheme: 'API_KEY', name: `examples-${slug}` },
285 + });
286 + config = { id: created.auth_config?.id ?? created.id };
287 + report(`created API-key auth config for ${slug}: ${config.id}`);
288 + }
289 + exports[`COMPOSIO_EXAMPLES_${exportPrefix}_AUTH_CONFIG_ID`] = config.id;
290 + exports[`COMPOSIO_EXAMPLES_${exportPrefix}_PLACEHOLDER`] = demoValue;
291 +}
292 +
293 +if (pendingGrants.length) {
294 + report('');
295 + report('OAuth connections still needing a one-time human authorization:');
296 + for (const line of pendingGrants) report(` - ${line}`);
297 +}
298 +report('');
299 +report(ok ? 'provisioned state: complete' : 'provisioned state: INCOMPLETE (see above)');
300 +
301 +// stdout is meant to be eval'd, so every value is single-quoted: an id the
302 +// backend returned with a space or a shell metacharacter must not become code.
303 +const shellQuote = value => `'${String(value).replace(/'/g, `'\\''`)}'`;
304 +
305 +for (const [name, value] of Object.entries(exports)) {
306 + if (value === undefined || value === null) {
307 + ok = false;
308 + report(`error: ${name} could not be resolved; not exporting it`);
309 + continue;
310 + }
311 + console.log(`export ${name}=${shellQuote(value)}`);
312 +}
313 +
314 +process.exitCode = ok ? 0 : 1;
ts/examples/README.md new
+34
@@ -0,0 +1,34 @@
1 +# Composio TypeScript examples
2 +
3 +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.
4 +
5 +## Run one example
6 +
7 +```bash
8 +cd ts
9 +pnpm install
10 +out=$(node ../scripts/examples-provision.mjs) && eval "$out"
11 +pnpm --filter openai-example start
12 +```
13 +
14 +`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.
15 +
16 +## Configuration
17 +
18 +Examples read configuration from environment variables and fail loudly, naming the missing variable, if one isn't set:
19 +
20 +- `COMPOSIO_API_KEY` — always required.
21 +- `COMPOSIO_EXAMPLES_USER_ID` — the user id examples act as.
22 +- `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.
23 +- `COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID` and `COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER` — the serpapi API-key auth config and its placeholder key value.
24 +- `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` — only needed by examples that call that LLM provider.
25 +
26 +`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.
27 +
28 +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.
29 +
30 +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.
31 +
32 +## A note on connection examples
33 +
34 +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.
ts/examples/anthropic/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "index.js",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "start:claude-agents-sdk": "bun src/claude-agents-sdk.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
@@ -29,5 +30,6 @@
30 "devDependencies": {
31 "@types/bun": "catalog:",
32 "typescript": "catalog:"
32 - }
33 + },
34 + "type": "module"
35 }
ts/examples/anthropic/src/experimental.mcp.ts
+14 -21
@@ -8,39 +8,32 @@ const composio = new Composio({
8 provider: new AnthropicProvider({ cacheTools: true }),
9 });
10
11 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
12 -const externalUserId = '<external_user_id>'; // Replace it with the your user id
13 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
11 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
12 +if (!externalUserId) {
13 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
14 +}
15
15 -// 2. Create an MCP config
16 -const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
17 - toolkits: [
18 - {
19 - toolkit: 'gmail',
20 - authConfigId,
21 - },
22 - ],
23 - allowedTools,
24 - manuallyManageConnections: true,
16 +// 2. Create a session scoped to the Gmail toolkit; it exposes a hosted MCP endpoint
17 +const session = await composio.sessions.create(externalUserId, {
18 + toolkits: ['gmail'],
19 + mcp: true,
20 });
21
27 -// 3. Retrieve the MCP server instance for the connected accounts
28 -const mcp = await composio.mcp.generate(externalUserId, mcpConfig.id);
29 -
30 -// 4. Initialize Anthropic client.
22 +// 3. Initialize Anthropic client.
23 const anthropic = new Anthropic({
24 apiKey: process.env.ANTHROPIC_API_KEY,
25 });
26
35 -// 5. Pass servers to Anthropic-specific Agent.
27 +// 4. Pass the session's MCP endpoint to Anthropic-specific Agent.
28 const stream = anthropic.beta.messages.stream({
37 - model: 'claude-4-sonnet-20250514',
29 + model: 'claude-sonnet-5',
30 max_tokens: 64_000,
31 mcp_servers: [
32 {
41 - name: mcp.name,
42 - url: mcp.url,
33 + name: 'composio-gmail',
34 + url: session.mcp.url,
35 type: 'url',
36 + authorization_token: process.env.COMPOSIO_API_KEY,
37 },
38 ],
39 messages: [
ts/examples/anthropic/src/index.ts
+3 -2
@@ -43,7 +43,7 @@ async function main() {
43 * Create a message with Anthropic that may use tools
44 */
45 const message = await anthropic.messages.create({
46 - model: 'claude-3-7-sonnet-latest',
46 + model: 'claude-sonnet-5',
47 max_tokens: 1024,
48 tools: tools,
49 messages,
@@ -75,7 +75,7 @@ async function main() {
75 * Send a follow-up message with the tool results
76 */
77 const followUpMessage = await anthropic.messages.create({
78 - model: 'claude-3-7-sonnet-latest',
78 + model: 'claude-sonnet-5',
79 max_tokens: 1024,
80 messages,
81 });
@@ -105,6 +105,7 @@ async function main() {
105 }
106 } catch (error) {
107 console.error('Error:', error);
108 + process.exitCode = 1;
109 }
110 }
111
ts/examples/anthropic/src/mcp.ts
+21 -23
@@ -2,8 +2,8 @@
2 * Anthropic MCP Gmail Example
3 *
4 * This example demonstrates how to use Composio SDK with Anthropic to:
5 - * 1. Create an MCP server for Gmail toolkit
6 - * 2. Connect to the server and use it with Anthropic's API
5 + * 1. Create a tool-router session scoped to the Gmail toolkit
6 + * 2. Connect Anthropic's MCP client to the session's hosted MCP endpoint
7 * 3. Fetch and summarize emails using the MCP tools
8 *
9 * Prerequisites:
@@ -30,35 +30,33 @@ const composio = new Composio({
30 provider,
31 });
32
33 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
34 -const externalUserId = '<external_user_id>'; // Replace it with your user ID
35 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
33 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user ID from your database
34 +if (!externalUserId) {
35 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
36 +}
37
37 -// Create an MCP server with Gmail toolkit
38 -const mcpConfig = await composio.mcp.create('gmail-anthropic-' + Date.now(), {
39 - toolkits: [
40 - {
41 - toolkit: 'gmail',
42 - authConfigId,
43 - },
44 - ],
45 - allowedTools,
38 +// Create a session scoped to the Gmail toolkit; every session exposes a hosted MCP endpoint
39 +const session = await composio.sessions.create(externalUserId, {
40 + toolkits: ['gmail'],
41 + mcp: true,
42 });
43
48 -console.log(`✅ MCP server created: ${mcpConfig.id}`);
49 -console.log(`🔧 Available toolkits: ${mcpConfig.allowedTools.join(', ')}`);
50 -
51 -// Generate a user-scoped MCP endpoint and adapt it for Anthropic's MCP beta.
52 -const mcp = await mcpConfig.generate(externalUserId);
53 -const servers = provider.wrapMcpServerResponse([{ name: mcp.name, url: mcp.url }]);
44 +console.log(`✅ MCP session created: ${session.sessionId}`);
45
46 console.log('\n=== Fetching and Summarizing Recent Emails ===');
47
57 -// Use Anthropic with the MCP servers
48 +// Use Anthropic with the session's MCP endpoint
49 const stream = anthropic.beta.messages.stream({
59 - model: 'claude-4-sonnet-20250514',
50 + model: 'claude-sonnet-5',
51 max_tokens: 64_000,
61 - mcp_servers: servers,
52 + mcp_servers: [
53 + {
54 + type: 'url',
55 + url: session.mcp.url,
56 + name: 'composio-gmail',
57 + authorization_token: process.env.COMPOSIO_API_KEY,
58 + },
59 + ],
60 messages: [
61 {
62 role: 'user',
ts/examples/anthropic/src/streaming.ts
+2 -2
@@ -31,7 +31,7 @@ async function main() {
31 console.log('🔄 Creating message with Anthropic...');
32 const stream = await anthropic.messages
33 .stream({
34 - model: 'claude-3-5-sonnet-latest',
34 + model: 'claude-sonnet-5',
35 max_tokens: 1024,
36 messages: [
37 {
@@ -70,7 +70,7 @@ async function main() {
70 */
71 const followUpStream = await anthropic.messages
72 .stream({
73 - model: 'claude-3-7-sonnet-latest',
73 + model: 'claude-sonnet-5',
74 max_tokens: 1024,
75 messages: [
76 {
ts/examples/anthropic/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/cloudflare-wrangler/package.json
+5 -2
@@ -7,10 +7,12 @@
7 "dev": "wrangler dev",
8 "start": "wrangler dev",
9 "test": "vitest",
10 - "cf-typegen": "wrangler types"
10 + "cf-typegen": "wrangler types",
11 + "typecheck": "tsc --noEmit -p ./tsconfig.json"
12 },
13 "devDependencies": {
14 "@cloudflare/vitest-pool-workers": "catalog:",
15 + "@types/node": "^26.1.2",
16 "typescript": "catalog:",
17 "vitest": "catalog:",
18 "wrangler": "catalog:"
@@ -19,5 +21,6 @@
21 "@composio/core": "workspace:^",
22 "hono": "catalog:",
23 "openai": "catalog:"
22 - }
24 + },
25 + "type": "module"
26 }
ts/examples/cloudflare-wrangler/tsconfig.json
+1 -3
@@ -36,9 +36,7 @@
36
37 /* Skip type checking all .d.ts files. */
38 "skipLibCheck": true,
39 - "types": [
40 - "./worker-configuration.d.ts"
41 - ]
39 + "types": ["node", "./worker-configuration.d.ts"]
40 },
41 "exclude": ["test"],
42 "include": ["worker-configuration.d.ts", "src/**/*.ts"]
ts/examples/connected-accounts/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "index.js",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
@@ -19,5 +20,6 @@
20 "devDependencies": {
21 "@types/bun": "catalog:",
22 "typescript": "catalog:"
22 - }
23 + },
24 + "type": "module"
25 }
ts/examples/connected-accounts/src/api-key.ts
+13 -2
@@ -4,9 +4,20 @@ const composio = new Composio({
4 apiKey: process.env.COMPOSIO_API_KEY,
5 });
6
7 -const connectionRequest = await composio.connectedAccounts.initiate('user_123', 'auth_config_123', {
7 +const authConfigId = process.env.COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID; // an API-key-scheme auth config ID
8 +const apiKey = process.env.COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER; // the service API key to store
9 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
10 +if (!authConfigId || !apiKey || !userId) {
11 + throw new Error(
12 + 'Set COMPOSIO_EXAMPLES_APIKEY_AUTH_CONFIG_ID, COMPOSIO_EXAMPLES_APIKEY_PLACEHOLDER and COMPOSIO_EXAMPLES_USER_ID'
13 + );
14 +}
15 +
16 +const connectionRequest = await composio.connectedAccounts.initiate(userId, authConfigId, {
17 + // Allow more than one connected account per user for this auth config
18 + allowMultiple: true,
19 config: AuthScheme.APIKey({
9 - api_key: 'your_api_key',
20 + generic_api_key: apiKey,
21 }),
22 });
23
ts/examples/connected-accounts/src/multiple-connected-accounts.ts
+6 -1
@@ -4,7 +4,12 @@ const composio = new Composio({
4 apiKey: process.env.COMPOSIO_API_KEY,
5 });
6
7 -const connectionRequest = await composio.connectedAccounts.initiate('default', 'ac_NSC2s9WqTE4n', {
7 +const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your auth config ID
8 +if (!authConfigId) {
9 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID');
10 +}
11 +
12 +const connectionRequest = await composio.connectedAccounts.initiate('default', authConfigId, {
13 allowMultiple: true,
14 });
15
ts/examples/connected-accounts/src/scopes.ts
+6 -1
@@ -2,6 +2,11 @@ import { Composio } from '@composio/core';
2
3 const composio = new Composio();
4
5 -const response = await composio.authConfigs.get('ac_3COrKCdQYLNu');
5 +const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your auth config ID
6 +if (!authConfigId) {
7 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID');
8 +}
9 +
10 +const response = await composio.authConfigs.get(authConfigId);
11
12 console.log(JSON.stringify(response, null, 2));
ts/examples/connected-accounts/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "types": ["bun"]
14 },
15 "include": ["src"]
16 }
ts/examples/error-handling-demo/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "index.js",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
@@ -19,5 +20,6 @@
20 "devDependencies": {
21 "@types/bun": "catalog:",
22 "typescript": "catalog:"
22 - }
23 + },
24 + "type": "module"
25 }
ts/examples/error-handling-demo/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "types": ["bun"]
14 },
15 "include": ["src"]
16 }
ts/examples/file-handling/package.json
+3 -1
@@ -5,6 +5,7 @@
5 "description": "Example project for File-handling",
6 "main": "src/index.ts",
7 "scripts": {
8 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
@@ -23,5 +24,6 @@
24 "devDependencies": {
25 "@types/bun": "catalog:",
26 "typescript": "catalog:"
26 - }
27 + },
28 + "type": "module"
29 }
ts/examples/file-handling/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/google/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "dev": "bun --watch src/index.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
@@ -29,5 +30,6 @@
30 "devDependencies": {
31 "@types/bun": "catalog:",
32 "typescript": "catalog:"
32 - }
33 + },
34 + "type": "module"
35 }
ts/examples/google/src/experimental.mcp.ts
+22 -24
@@ -2,7 +2,7 @@ import { Composio } from '@composio/core';
2 import { GoogleGenAI, mcpToTool } from '@google/genai';
3 import { GoogleProvider } from '@composio/google';
4 import { Client as MCPClient } from '@modelcontextprotocol/sdk/client/index.js';
5 -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
5 +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
6
7 function wrapTools(client: MCPClient) {
8 return [mcpToTool(client)];
@@ -14,44 +14,42 @@ const composio = new Composio({
14 provider: new GoogleProvider(),
15 });
16
17 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
18 -const externalUserId = '<externalUserId>'; // Replace it with the user id from your database
19 -const allowedTools = ['GMAIL_FETCH_EMAILS'];
17 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
18 +if (!externalUserId) {
19 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
20 +}
21
21 -// 2. Create an MCP config
22 -const mcpConfig = await composio.experimental.mcp.create(`${Date.now()}`, {
23 - toolkits: [
24 - {
25 - toolkit: 'gmail',
26 - authConfigId,
27 - allowedTools,
28 - },
29 - ],
30 - manuallyManageConnections: true,
22 +// 2. Create a session scoped to the Gmail toolkit; it exposes a hosted MCP endpoint.
23 +// manageConnections defaults to true, which would add connection-management tools
24 +// this example does not use. The config it replaced set manuallyManageConnections.
25 +const session = await composio.sessions.create(externalUserId, {
26 + toolkits: ['gmail'],
27 + manageConnections: false,
28 + mcp: true,
29 });
30
33 -// 3. Retrieve the MCP server instance for the user
34 -const server = await composio.experimental.mcp.generate(externalUserId, mcpConfig.id);
35 -
36 -// 4. Create a generic MCP client.
31 +// 3. Create a generic MCP client.
32 // This client needs to remain "alive" not be dropped by the GC until
33 // the tools are retrieved from it.
39 -const serverParams = new SSEClientTransport(new URL(server.url));
34 +// session.mcp.headers carries the credentials the endpoint requires.
35 +const serverParams = new StreamableHTTPClientTransport(new URL(session.mcp.url), {
36 + requestInit: { headers: session.mcp.headers },
37 +});
38 const mcpClient = new MCPClient({
39 name: 'composio-mcp-client',
40 version: '1.0.0',
41 });
42
45 -// 5. Retrieve tools.
43 +// 4. Retrieve tools.
44 await mcpClient.connect(serverParams);
45 const tools = wrapTools(mcpClient);
46
49 -// 6. Initialize Google Gemini client.
47 +// 5. Initialize Google Gemini client.
48 const gemini = new GoogleGenAI({
49 apiKey: process.env.GEMINI_API_KEY,
50 });
51
54 -// 7. Pass tools to Google Gemini-specific Agent.
52 +// 6. Pass tools to Google Gemini-specific Agent.
53 const stream = await gemini.models.generateContentStream({
54 model: 'gemini-2.5-flash',
55 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({
58 },
59 });
60
63 -// 8. Execute the Google Gemini-specific Agent.
61 +// 7. Execute the Google Gemini-specific Agent.
62 for await (const chunk of stream) {
63 console.log(chunk.text);
64 }
65
68 -// 9. Close the generic MCP client.
66 +// 8. Close the generic MCP client.
67 await mcpClient.close();
ts/examples/google/src/index.ts
+5 -1
@@ -62,8 +62,12 @@ async function main() {
62 }
63 } catch (error) {
64 console.error('❌ Error running example:', error);
65 + process.exitCode = 1;
66 }
67 }
68
69 // Run the example
69 -main().catch(console.error);
70 +main().catch(error => {
71 + console.error(error);
72 + process.exitCode = 1;
73 +});
ts/examples/google/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/json-schema-to-zod/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "dev": "bun --watch src/index.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
@@ -26,5 +27,6 @@
27 "devDependencies": {
28 "@types/bun": "catalog:",
29 "typescript": "catalog:"
29 - }
30 + },
31 + "type": "module"
32 }
ts/examples/json-schema-to-zod/src/index.ts
+5 -1
@@ -38,8 +38,12 @@ async function main() {
38 console.log('📝 Implement your json-schema-to-zod logic here!');
39 } catch (error) {
40 console.error('❌ Error running example:', error);
41 + process.exitCode = 1;
42 }
43 }
44
45 // Run the example
45 -main().catch(console.error);
46 +main().catch(error => {
47 + console.error(error);
48 + process.exitCode = 1;
49 +});
ts/examples/json-schema-to-zod/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/langchain/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "index.js",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
@@ -25,5 +26,6 @@
26 "devDependencies": {
27 "@types/bun": "catalog:",
28 "typescript": "catalog:"
28 - }
29 + },
30 + "type": "module"
31 }
ts/examples/langchain/src/openai.ts
+16 -11
@@ -1,6 +1,6 @@
1 import { Composio } from '@composio/core';
2 import { LangchainProvider } from '@composio/langchain';
3 -import { createAgent } from "langchain";
3 +import { createAgent } from 'langchain';
4 import { ChatOpenAI } from '@langchain/openai';
5
6 // initiate composio
@@ -8,15 +8,20 @@ const composio = new Composio({
8 provider: new LangchainProvider(),
9 });
10
11 -const githubTool = await composio.tools.get('jkomyno', 'GMAIL_FETCH_EMAILS');
11 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
12 +if (!userId) {
13 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
14 +}
15 +
16 +const gmailTool = await composio.tools.get(userId, 'GMAIL_FETCH_EMAILS');
17
18 const agent = createAgent({
14 - model: new ChatOpenAI({ model: "gpt-5" }),
15 - tools: githubTool,
16 - });
17 -
18 - console.log(
19 - await agent.invoke({
20 - messages: [{ role: "user", content: "Provide a summary of my last email received." }],
21 - })
22 - );
\ No newline at end of file
19 + model: new ChatOpenAI({ model: 'gpt-5' }),
20 + tools: gmailTool,
21 +});
22 +
23 +console.log(
24 + await agent.invoke({
25 + messages: [{ role: 'user', content: 'Provide a summary of my last email received.' }],
26 + })
27 +);
ts/examples/langchain/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "types": ["bun"]
14 },
15 "include": ["src"]
16 }
ts/examples/llamaindex/package.json
+3 -1
@@ -5,6 +5,7 @@
5 "description": "Example project for Llamaindex",
6 "main": "src/index.ts",
7 "scripts": {
8 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
@@ -27,5 +28,6 @@
28 "devDependencies": {
29 "@types/bun": "catalog:",
30 "typescript": "catalog:"
30 - }
31 + },
32 + "type": "module"
33 }
ts/examples/llamaindex/src/index.ts
+5 -1
@@ -71,8 +71,12 @@ async function main() {
71 }
72 } catch (error) {
73 console.error('❌ Error running example:', error);
74 + process.exitCode = 1;
75 }
76 }
77
78 // Run the example
78 -main().catch(console.error);
79 +main().catch(error => {
80 + console.error(error);
81 + process.exitCode = 1;
82 +});
ts/examples/llamaindex/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/mcp/package.json
+3 -1
@@ -5,6 +5,7 @@
5 "description": "Example project for Mcp",
6 "main": "src/index.ts",
7 "scripts": {
8 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
@@ -29,5 +30,6 @@
30 "@types/bun": "catalog:",
31 "@types/node": "^26.1.2",
32 "typescript": "catalog:"
32 - }
33 + },
34 + "type": "module"
35 }
ts/examples/mcp/src/index.ts
+14 -5
@@ -2,7 +2,7 @@ import { createMCPClient } from '@ai-sdk/mcp';
2 import { openai } from '@ai-sdk/openai';
3 import { Composio } from '@composio/core';
4 import { VercelProvider } from '@composio/vercel';
5 -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
5 +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
6 import { stepCountIs, streamText } from 'ai';
7 import 'dotenv/config';
8
@@ -12,12 +12,18 @@ const composio = new Composio({
12 provider: new VercelProvider(),
13 });
14
15 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
16 -const externalUserId = '<extern_user_id>'; // Replace it with the user id
15 +const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config ID
16 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
17 +if (!authConfigId || !externalUserId) {
18 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');
19 +}
20 const allowedTools = ['GMAIL_FETCH_EMAILS'];
21
22 // 2. Create an MCP config
20 -const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
23 +// Named `examples-<label>-<unix-seconds>` so the provisioning script's --gc can
24 +// tell an example's throwaway config from one someone created by hand. The API
25 +// caps this name at 30 characters, so keep the label short and use seconds.
26 +const mcpConfig = await composio.mcp.create(`examples-gmail-${Math.floor(Date.now() / 1000)}`, {
27 toolkits: [
28 {
29 toolkit: 'gmail',
@@ -31,7 +37,10 @@ const mcpConfig = await composio.mcp.create(`${Date.now()}`, {
37 // 3. Retrieve the MCP server instance for the user
38 const server = await composio.mcp.generate(externalUserId, mcpConfig.id);
39
34 -const serverParams = new SSEClientTransport(new URL(server.url));
40 +// The MCP endpoint authenticates with your Composio API key
41 +const serverParams = new StreamableHTTPClientTransport(new URL(server.url), {
42 + requestInit: { headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! } },
43 +});
44
45 const mcpClient = await createMCPClient({
46 name: 'composio-mcp-client',
ts/examples/modifiers/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
@@ -21,5 +22,6 @@
22 "devDependencies": {
23 "@types/bun": "catalog:",
24 "typescript": "catalog:"
24 - }
25 + },
26 + "type": "module"
27 }
ts/examples/modifiers/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "types": ["bun"]
14 },
15 "include": ["src"]
16 }
ts/examples/openai/src/agents-api/experiment.mcp.ts
+10 -5
@@ -11,13 +11,16 @@ const composio = new Composio({
11 allowTracking: false,
12 });
13
14 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
14 +const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config ID
15 const toolkit = 'gmail'; // slug of the toolkit
16 -const externalUserId = '<external_user_id>'; // Replace it with the userId from your database
16 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the userId from your database
17 +if (!authConfigId || !externalUserId) {
18 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');
19 +}
20 const allowedTools = ['GMAIL_FETCH_EMAILS'];
21
19 -// 2. Create an MCP config
20 -const mcpConfig = await composio.mcp.create(externalUserId, {
22 +// 2. Create an MCP config (names must be unique within a project)
23 +const mcpConfig = await composio.mcp.create(`examples-gm-agents-${Math.floor(Date.now() / 1000)}`, {
24 toolkits: [{ toolkit, authConfigId }],
25 allowedTools,
26 });
@@ -29,6 +32,8 @@ const tools: HostedMCPTool[] = [
32 hostedMcpTool({
33 serverLabel: server.name,
34 serverUrl: server.url,
35 + // The MCP endpoint authenticates with your Composio API key
36 + headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },
37 requireApproval: {
38 never: {
39 toolNames: ['GMAIL_FETCH_EMAILS'],
@@ -60,5 +65,5 @@ console.log('\n📬 Email Summary:');
65
66 const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
67
63 -// @ts-ignore
68 +// @ts-expect-error: the agents SDK types `output` as a union whose message variant is not narrowed by the `type` filter above
69 console.log(output?.content[0].text);
ts/examples/openai/src/agents-api/experiment.tool-router.ts
+4 -2
@@ -25,8 +25,10 @@ const session = await composio.sessions.create(externalUserId, {
25
26 const tools: HostedMCPTool[] = [
27 hostedMcpTool({
28 - serverLabel: 'composio tool router',
28 + serverLabel: 'composio-tool-router',
29 serverUrl: session.mcp.url,
30 + // The MCP endpoint authenticates with your Composio API key
31 + headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },
32 requireApproval: {
33 never: {
34 toolNames: ['HACKERNEWS_GET_USER_BY_USERNAME'],
@@ -57,5 +59,5 @@ console.log('\n📰 HackerNews Profile:');
59
60 const output = response.output.filter(({ type }) => type === 'message').at(0);
61
60 -// @ts-ignore
62 +// @ts-expect-error: the agents SDK types `output` as a union whose message variant is not narrowed by the `type` filter above
63 console.log(output?.content[0].text);
ts/examples/openai/src/chat-completions.ts
+1
@@ -86,6 +86,7 @@ async function main() {
86 }
87 } catch (error) {
88 console.error('❌ Error:', error);
89 + process.exitCode = 1;
90 }
91 }
92
ts/examples/openai/src/responses-api/experiment.mcp.ts
+8 -6
@@ -10,12 +10,15 @@ const composio = new Composio({
10 allowTracking: false,
11 });
12
13 -const authConfigId = '<auth_config_id>'; // Use your auth config ID
14 -const externalUserId = '<external_user_id>'; // Replace it with the user id from your database
13 +const authConfigId = process.env.COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID; // your Gmail auth config ID
14 +const externalUserId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
15 +if (!authConfigId || !externalUserId) {
16 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_AUTH_CONFIG_ID and COMPOSIO_EXAMPLES_USER_ID');
17 +}
18 const allowedTools = ['GMAIL_FETCH_EMAILS'];
19
20 // 2. Create an MCP config
18 -const mcpConfig = await composio.mcp.create(`gmail-mcp-${Date.now()}`, {
21 +const mcpConfig = await composio.mcp.create(`examples-gm-resp-${Math.floor(Date.now() / 1000)}`, {
22 toolkits: [
23 {
24 toolkit: 'gmail',
@@ -34,9 +37,10 @@ const tools = [
37 type: 'mcp' as const,
38 server_label: mcp.name,
39 server_url: mcp.url,
40 + // The MCP endpoint authenticates with your Composio API key
41 + headers: { 'x-api-key': process.env.COMPOSIO_API_KEY! },
42 },
43 ];
39 -console.log({ tools });
44
45 // 4. Pass tools to OpenAI-specific Agent.
46 const openai = new OpenAI();
@@ -51,8 +55,6 @@ const emailResponse = await openai.responses.create({
55 tools: tools,
56 });
57
54 -console.log(JSON.stringify(emailResponse, null, 2));
55 -
58 const result = await composio.provider.handleToolCalls('default', emailResponse.output);
59 console.log({ result });
60
ts/examples/session-management/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "dev": "bun --watch src/index.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
@@ -24,5 +25,6 @@
25 "devDependencies": {
26 "@types/bun": "catalog:",
27 "typescript": "catalog:"
27 - }
28 + },
29 + "type": "module"
30 }
ts/examples/session-management/src/index.ts
+5 -1
@@ -37,8 +37,12 @@ async function main() {
37 console.log(`✅ Found ${tools.length} tools`);
38 } catch (error) {
39 console.error('❌ Error running example:', error);
40 + process.exitCode = 1;
41 }
42 }
43
44 // Run the example
44 -main().catch(console.error);
45 +main().catch(error => {
46 + console.error(error);
47 + process.exitCode = 1;
48 +});
ts/examples/session-management/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/tool-router/package.json
+2 -1
@@ -44,5 +44,6 @@
44 "@types/bun": "catalog:",
45 "@types/node": "^26.1.2",
46 "typescript": "catalog:"
47 - }
47 + },
48 + "type": "module"
49 }
ts/examples/tool-router/src/authorize.ts
+12 -7
@@ -1,14 +1,19 @@
1 import { Composio } from '@composio/core';
2
3 const composio = new Composio();
4 -const session = await composio.create('user_123', { toolkits: ['gmail'] });
5 -const connectionRequest = await session.authorize("gmail", {
6 - callbackUrl: "https://google.com"
7 -});
4
9 -console.log(connectionRequest);
5 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
6 +if (!userId) {
7 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
8 +}
9
11 -const connectedAccount = await connectionRequest.waitForConnection();
12 -console.log(connectedAccount);
10 +const session = await composio.create(userId, { toolkits: ['gmail'] });
11 +const connectionRequest = await session.authorize('gmail', {
12 + callbackUrl: 'https://google.com',
13 +});
14
15 +console.log(`Visit this URL to authorize: ${connectionRequest.redirectUrl}`);
16
17 +const connectedAccount = await connectionRequest.waitForConnection();
18 +// Print identifying fields only: the full object carries live OAuth credentials.
19 +console.log(`Connected account ${connectedAccount.id} is ${connectedAccount.status}`);
ts/examples/tool-router/src/langchain.ts
+8 -3
@@ -12,10 +12,15 @@ const llm = new ChatOpenAI({
12 });
13
14 async function main() {
15 - const session = await composio.create('user_123', { toolkits: ['gmail'], mcp: true });
15 + const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a connected Gmail account
16 + if (!userId) {
17 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
18 + }
19 +
20 + const session = await composio.create(userId, { toolkits: ['gmail'], mcp: true });
21
22 const client = new MultiServerMCPClient({
18 - math: {
23 + composio: {
24 transport: 'http',
25 url: session.mcp.url,
26 headers: session.mcp.headers,
@@ -25,7 +30,7 @@ async function main() {
30 const tools = await client.getTools();
31
32 const agent = createAgent({
28 - name: 'Gmail Assistant',
33 + name: 'gmail-assistant',
34 systemPrompt: 'You are a helpful gmail assistant.',
35 model: llm,
36 tools,
ts/examples/tool-router/src/multi-account.ts
+14 -3
@@ -7,9 +7,14 @@ const composio = new Composio({
7 provider: new VercelProvider(),
8 });
9
10 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user id from your database
11 +if (!userId) {
12 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
13 +}
14 +
15 // Enable multi-account mode so the user can connect multiple accounts
16 // per toolkit (e.g. two Gmail accounts).
12 -const session = await composio.create('user_123', {
17 +const session = await composio.create(userId, {
18 toolkits: ['gmail'],
19 multiAccount: {
20 enable: true,
@@ -19,10 +24,16 @@ const session = await composio.create('user_123', {
24 });
25
26 // Set an alias while authorizing a connected account for easier identification.
22 -await session.authorize('gmail', {
23 - alias: 'work-gmail',
27 +// Aliases are unique per entity and toolkit, so suffix to keep reruns working.
28 +const connectionRequest = await session.authorize('gmail', {
29 + alias: `work-gmail-${Date.now()}`,
30 });
31
32 +console.log(`Visit this URL to authorize: ${connectionRequest.redirectUrl}`);
33 +
34 +// requireExplicitSelection means the new alias is only usable once it is ACTIVE.
35 +await connectionRequest.waitForConnection();
36 +
37 const tools = await session.tools();
38
39 const stream = await streamText({
ts/examples/toolkits/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
12 },
@@ -21,5 +22,6 @@
22 "devDependencies": {
23 "@types/bun": "catalog:",
24 "typescript": "catalog:"
24 - }
25 + },
26 + "type": "module"
27 }
ts/examples/toolkits/tsconfig.json
+2 -1
@@ -9,7 +9,8 @@
9 "strict": true,
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 - "skipLibCheck": true
12 + "skipLibCheck": true,
13 + "types": ["bun"]
14 },
15 "include": ["src"]
16 }
ts/examples/tools/package.json
+3 -1
@@ -5,6 +5,7 @@
5 "description": "Example project for Tools",
6 "main": "src/index.ts",
7 "scripts": {
8 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
@@ -29,5 +30,6 @@
30 "devDependencies": {
31 "@types/bun": "catalog:",
32 "typescript": "catalog:"
32 - }
33 + },
34 + "type": "module"
35 }
ts/examples/tools/src/ai.ts
+15 -4
@@ -12,20 +12,28 @@ const openai = new OpenAI({
12 */
13 const composio = new Composio({
14 apiKey: process.env.COMPOSIO_API_KEY,
15 + // Local file paths under fileUploadDirs are uploaded automatically when the tool expects a file
16 + dangerouslyAllowAutoUploadDownloadFiles: true,
17 + fileUploadDirs: [import.meta.dirname],
18 });
19
20 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a Google Drive connection
21 +if (!userId) {
22 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
23 +}
24 +
25 /**
26 * Get the tools
27 * This tool is automatically typed and wrapped with the OpenAI Provider
28 */
29 console.log('🔄 Getting tools...');
22 -const tools = await composio.tools.get('default', 'GOOGLEDRIVE_UPLOAD_FILE');
30 +const tools = await composio.tools.get(userId, 'GOOGLEDRIVE_UPLOAD_FILE');
31 console.log('✅ Tools fetched successfully...');
32 console.log(JSON.stringify(tools, null, 2));
33 /**
34 * Define a task for the assistant based on the tools in hand
35 */
28 -const fileToUpload = path.join(__dirname, 'image.png');
36 +const fileToUpload = path.join(import.meta.dirname, 'image.png');
37 const task = `Upload the file ${fileToUpload} to Google Drive`;
38
39 /**
@@ -51,9 +59,12 @@ console.log('✅ Chat completion created successfully...');
59 * If the assistant has tool calls, execute them and log the result
60 */
61 console.log('🔄 Calling tool...');
54 -if (response.choices[0].message.tool_calls && response.choices[0].message.tool_calls[0].type === 'function') {
62 +if (
63 + response.choices[0].message.tool_calls &&
64 + response.choices[0].message.tool_calls[0].type === 'function'
65 +) {
66 console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
56 - const result = await composio.provider.handleToolCalls('default', response);
67 + const result = await composio.provider.handleToolCalls(userId, response);
68 console.log(result);
69 }
70 console.log('✅ Tool called successfully...');
ts/examples/tools/src/index.ts
+17 -5
@@ -18,8 +18,16 @@ import path from 'path';
18 const composio = new Composio({
19 apiKey: process.env.COMPOSIO_API_KEY,
20 allowTracking: false,
21 + // Local file paths under fileUploadDirs are uploaded automatically when the tool expects a file
22 + dangerouslyAllowAutoUploadDownloadFiles: true,
23 + fileUploadDirs: [import.meta.dirname],
24 });
25
26 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // a user with a Google Drive connection
27 +if (!userId) {
28 + throw new Error('Set COMPOSIO_EXAMPLES_USER_ID');
29 +}
30 +
31 /**
32 * Main function to run the example
33 */
@@ -31,9 +39,9 @@ async function main() {
39 const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
40 dangerouslySkipVersionCheck: true,
41 arguments: {
34 - file_to_upload: path.join(__dirname, 'image.png'),
42 + file_to_upload: path.join(import.meta.dirname, 'image.png'),
43 },
36 - userId: 'default',
44 + userId,
45 });
46 console.log('✅ File uploaded successfully...');
47 console.log(JSON.stringify(result, null, 2));
@@ -42,16 +50,20 @@ async function main() {
50 const result2 = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {
51 dangerouslySkipVersionCheck: true,
52 arguments: {
45 - file_id: (result.data.response_data as unknown as { id: string }).id,
53 + file_id: (result.data as unknown as { id: string }).id,
54 },
47 - userId: 'default',
55 + userId,
56 });
57 console.log('✅ File downloaded successfully...');
58 console.log(JSON.stringify(result2, null, 2));
59 } catch (error) {
60 console.error('❌ Error running example:', error);
61 + process.exitCode = 1;
62 }
63 }
64
65 // Run the example
57 -main().catch(console.error);
66 +main().catch(error => {
67 + console.error(error);
68 + process.exitCode = 1;
69 +});
ts/examples/tools/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/triggers/package.json
+3 -1
@@ -6,6 +6,7 @@
6 "main": "src/index.ts",
7 "scripts": {
8 "clean": "git clean -xdf node_modules",
9 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
10 "start": "bun src/index.ts",
11 "dev": "bun --watch src/index.ts",
12 "webhook:server": "bun src/webhook-server.ts",
@@ -25,5 +26,6 @@
26 "devDependencies": {
27 "@types/bun": "catalog:",
28 "typescript": "catalog:"
28 - }
29 + },
30 + "type": "module"
31 }
ts/examples/triggers/src/create.ts
+8 -2
@@ -9,9 +9,15 @@ const triggerType = await composio.triggers.getType('GMAIL_NEW_GMAIL_MESSAGE');
9
10 console.log(JSON.stringify(triggerType, null, 2));
11
12 +const connectedAccountId = process.env.COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID; // your Gmail connected account ID
13 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user that owns the connected account
14 +if (!connectedAccountId || !userId) {
15 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID and COMPOSIO_EXAMPLES_USER_ID');
16 +}
17 +
18 // create a trigger
13 -const trigger = await composio.triggers.create('default', triggerType.slug, {
14 - connectedAccountId: 'ca_uQvmu9uZOhQo',
19 +const trigger = await composio.triggers.create(userId, triggerType.slug, {
20 + connectedAccountId,
21 triggerConfig: {},
22 });
23
ts/examples/triggers/src/index.ts
+7 -2
@@ -41,13 +41,18 @@ async function main() {
41 '📝 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'
42 );
43
44 - composio.triggers.subscribe(data => {
44 + await composio.triggers.subscribe(data => {
45 console.log('🔔 Trigger received:', JSON.stringify(data, null, 2));
46 });
47 + console.log('Subscribed to trigger events');
48 } catch (error) {
49 console.error('❌ Error running example:', error);
50 + process.exitCode = 1;
51 }
52 }
53
54 // Run the example
53 -main().catch(console.error);
55 +main().catch(error => {
56 + console.error(error);
57 + process.exitCode = 1;
58 +});
ts/examples/triggers/src/subscribe.ts
+8 -2
@@ -5,9 +5,15 @@ const composio = new Composio({
5 apiKey: process.env.COMPOSIO_API_KEY,
6 });
7
8 +const connectedAccountId = process.env.COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID; // your Gmail connected account ID
9 +const userId = process.env.COMPOSIO_EXAMPLES_USER_ID; // the user that owns the connected account
10 +if (!connectedAccountId || !userId) {
11 + throw new Error('Set COMPOSIO_EXAMPLES_GMAIL_CONNECTED_ACCOUNT_ID and COMPOSIO_EXAMPLES_USER_ID');
12 +}
13 +
14 // create a trigger
9 -const { triggerId } = await composio.triggers.create('default','GMAIL_NEW_GMAIL_MESSAGE', {
10 - connectedAccountId: 'ca_uQvmu9uZOhQo',
15 +const { triggerId } = await composio.triggers.create(userId, 'GMAIL_NEW_GMAIL_MESSAGE', {
16 + connectedAccountId,
17 triggerConfig: {},
18 });
19
ts/examples/triggers/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }
ts/examples/vercel/package.json
+2 -1
@@ -29,5 +29,6 @@
29 "@types/bun": "catalog:",
30 "@types/node": "^26.1.2",
31 "typescript": "catalog:"
32 - }
32 + },
33 + "type": "module"
34 }
ts/examples/vercel/src/stream.ts
+1 -1
@@ -11,7 +11,7 @@ const composio = new Composio({
11 provider: new VercelProvider(),
12 });
13
14 -const tools = await composio.tools.get('test-user-id', 'HACKERNEWS_GET_FRONTPAGE');
14 +const tools = await composio.tools.get('test-user-id', 'HACKERNEWS_GET_TOP_STORIES');
15 const stream = await streamText({
16 model: openai('gpt-4o-mini'),
17 tools,
ts/examples/versioning/package.json
+3 -1
@@ -5,6 +5,7 @@
5 "description": "Example project for Versioning",
6 "main": "src/index.ts",
7 "scripts": {
8 + "typecheck": "tsc --noEmit -p ./tsconfig.json",
9 "start": "bun src/index.ts",
10 "dev": "bun --watch src/index.ts",
11 "test": "echo \"Error: no test specified\" && exit 1"
@@ -23,5 +24,6 @@
24 "devDependencies": {
25 "@types/bun": "catalog:",
26 "typescript": "catalog:"
26 - }
27 + },
28 + "type": "module"
29 }
ts/examples/versioning/src/index.ts
+5 -1
@@ -42,8 +42,12 @@ async function main() {
42
43 } catch (error) {
44 console.error('❌ Error running example:', error);
45 + process.exitCode = 1;
46 }
47 }
48
49 // Run the example
49 -main().catch(console.error);
50 +main().catch(error => {
51 + console.error(error);
52 + process.exitCode = 1;
53 +});
ts/examples/versioning/tsconfig.json
+2 -1
@@ -10,7 +10,8 @@
10 "esModuleInterop": true,
11 "moduleResolution": "bundler",
12 "skipLibCheck": true,
13 - "resolveJsonModule": true
13 + "resolveJsonModule": true,
14 + "types": ["bun"]
15 },
16 "include": ["src"]
17 }