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

next
mdx 276 lines 14.2 KB
Raw
1 ---
2 title: What is a session?
3 description: What Composio sessions do, and how they scope users, tools, toolkits, auth, MCP, and workbench state
4 keywords: [session, userID, tools, toolkits, meta tools, mcp, workbench]
5 ---
6
7 A **session** is the runtime context for an agentic run: the scoped environment an AI agent works in while it acts for one of your users. You create it with `composio.create(userId)`, and it ties together the user, the toolkits available, authentication, and connected accounts. By default it gives the agent meta tools to discover, authenticate, and execute app tools at runtime, instead of loading hundreds of tool definitions into context.
8
9 If you only need authentication for tools you already own, follow [managed authentication for your own tools](/docs/authentication/managed-auth-for-custom-tools). Use a session to create a Connect Link, then call provider APIs through Proxy Execute from your own code. You don't need to fetch tool schemas or replace your tools with catalog actions.
10
11 ## The basics
12
13 Create a session for a user, then read its tools formatted for your framework. To connect over MCP instead, see [Using sessions via MCP](/docs/sessions-via-mcp).
14
15 <Tabs groupId="language" items={['Python', 'TypeScript', 'API']} persist>
16 <Tab value="Python">
17 ```python
18 session = composio.sessions.create(user_id="user_123")
19
20 tools = session.tools()
21 ```
22 </Tab>
23 <Tab value="TypeScript">
24 ```typescript
25 import { Composio } from '@composio/core';
26 const composio = new Composio({ apiKey: 'your_api_key' });
27 // ---cut---
28 const session = await composio.create("user_123");
29
30 const tools = await session.tools();
31 ```
32 </Tab>
33 <Tab value="API">
34 ```bash
35 SESSION_ID=$(curl -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
36 -H "x-api-key: $COMPOSIO_API_KEY" \
37 -H "Content-Type: application/json" \
38 -d '{"user_id": "user_123"}' | jq -r '.session_id')
39
40 curl -X GET https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/tools \
41 -H "x-api-key: $COMPOSIO_API_KEY"
42 ```
43 </Tab>
44 </Tabs>
45
46 A session scopes four things:
47
48 - **userID**: whose connected accounts and tool executions are in scope.
49 - **Tool access**: all toolkits by default, or a filtered set of toolkits, tools, or tags.
50 - **Authentication**: managed auth, custom auth configs, and connected-account selection.
51 - **Execution state**: logs, tool memory, MCP state, and workbench files for the task.
52
53
54 ## What comes in a session
55 By default, a session gives your agent meta tools to discover and execute app tools and manage connections for your user. All toolkits are discoverable, and search includes skill guidance when a matching skill exists. Standard sessions also include a [sandbox](#sandbox) for processing files and large responses outside the model's context window. You can restrict tool access or disable the sandbox through [session configuration](/docs/configuring-sessions).
56
57 Later we'll discuss [configuring sessions](/docs/configuring-sessions) for specialized use cases. But for now you can think of the Composio session as the basic building block for your agent.
58
59 ```mermaid
60 architecture-beta
61 group session(lucide:box)[Composio Session]
62
63 service toolsearch(lucide:book-search)[Tool Search] in session
64 service toolkits(lucide:toolbox)[Toolkits] in session
65 service tools(lucide:wrench)[Tools] in session
66 service sandbox(lucide:scan-box)[Sandbox] in session
67
68 service user(lucide:user)[User Context] in session
69 service auth(lucide:lock)[Authentication] in session
70
71 user:R -- L:auth
72 toolsearch:R -- L:toolkits
73 toolkits:B -- T:tools
74 ```
75
76 Below we're going to explain each of the concepts that come with a session.
77
78 ## Users
79
80 A user is an identifier from your app. Composio stores connections under that ID, so tools run with the right account and stay isolated from other users. Use a stable identifier like your database ID, never one that can change.
81
82 <Accordions>
83 <Accordion title="userID best practices">
84 - **Recommended:** database UUID or primary key (`user.id`)
85 - **Acceptable:** unique username (`user.username`)
86 - **Avoid:** email addresses (they can change)
87 - **Never:** `default` in production (it exposes other users' data)
88 </Accordion>
89 </Accordions>
90
91 A user can connect multiple accounts for the same toolkit, like work and personal Gmail. Use the same userID, then select the connected account when a session needs a specific one. See [Managing multiple connected accounts](/docs/authentication/managing-multiple-connected-accounts).
92
93 ## Authentication
94
95 When a tool needs a connection, the session generates a Connect Link with `session.authorize()`, or the agent handles the flow through `COMPOSIO_MANAGE_CONNECTIONS`.
96
97 In chat, the agent can pause, ask the user to connect an app, then retry the tool once auth completes. Composio manages the OAuth redirects, token exchange, and refresh. Once a user connects a toolkit, the connected account persists and future sessions reuse it without re-authentication.
98
99 For OAuth toolkits, Composio uses [managed apps](/docs/authentication/custom-app-vs-managed-app) by default. Bring your own app when you need your own branding, scopes, or consent screen.
100
101 ## Tools and Toolkits
102
103 A **toolkit** is a collection of related tools for a service. The `github` toolkit, for example, contains tools for creating issues, managing pull requests, and starring repositories.
104
105 A **tool** is an individual action your agent can execute. Each tool has an input schema (its parameters) and an output schema (what it returns), and follows a `{TOOLKIT}_{ACTION}` naming pattern, like `GITHUB_CREATE_AN_ISSUE`.
106
107 See [Toolkits](/docs/toolkits) for how tools are grouped, discovered, and used with connected accounts.
108
109 Every toolkit in the catalog is discoverable by default. Create a session without a `toolkits` parameter and the agent can find any of them at runtime. To restrict the set, pass `toolkits` when you create the session. See [Enable and disable toolkits](/docs/configuring-sessions). You can also bind local, in-process tools to a session with the experimental [local tools and toolkits](/docs/extending-sessions/local-tools-and-toolkits) API.
110
111 ### Meta tools
112
113 A session gives your agent meta tools, a small fixed set that discover, authenticate, and execute tools at runtime, so you never load hundreds of tool definitions into context:
114
115 <SessionFlow />
116
117 The agent searches for relevant tools, authenticates if needed, and executes them through the same session. Meta-tool calls share context, so the agent searches in one call and executes in the next without losing state. See the [Meta Tools reference](/toolkits/meta-tools) for each tool's input and output schema.
118
119 Know the exact tools upfront? The [direct tools preset](/docs/configuring-sessions#direct-tools-preset) returns them directly from `session.tools()` with no search step, while keeping session auth, connected accounts, and the workbench.
120
121 ### Executing session tools
122
123 When your model asks to call a session tool, execute it with `session.execute()`. It routes the call through the session's tool router, which is the only place session meta-tools run:
124
125 <Tabs groupId="language" items={['Python', 'TypeScript', 'API']} persist>
126 <Tab value="Python">
127 ```python
128 result = session.execute("COMPOSIO_SEARCH_TOOLS", arguments={"queries": [{"use_case": "send an email"}]})
129
130 if result.result_type == "failed":
131 raise RuntimeError(result.error or f"Tool execution failed (log ID: {result.log_id})")
132
133 print(result.data)
134 ```
135 </Tab>
136 <Tab value="TypeScript">
137 ```typescript
138 import { Composio } from '@composio/core';
139 const composio = new Composio({ apiKey: 'your_api_key' });
140 const session = await composio.create("user_123");
141 // ---cut---
142 const result = await session.execute("COMPOSIO_SEARCH_TOOLS", { queries: [{ use_case: "send an email" }] });
143
144 if (result.resultType === 'failed') {
145 throw new Error(result.error || `Tool execution failed (log ID: ${result.logId})`);
146 }
147
148 console.log(result.data);
149 ```
150 </Tab>
151 <Tab value="API">
152 ```bash
153 curl -X POST https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/execute \
154 -H "x-api-key: $COMPOSIO_API_KEY" \
155 -H "Content-Type: application/json" \
156 -d '{"tool_slug": "COMPOSIO_SEARCH_TOOLS", "arguments": {"queries": [{"use_case": "send an email"}]}}'
157 ```
158 </Tab>
159 </Tabs>
160
161 Do not execute session tools with `tools.execute()`, or by passing a user ID to a provider's `handle_tool_calls` helper — both take the direct execution path, which does not carry your session, and meta-tools fail there with `"can only be called inside a tool-router session"`. The [OpenAI](/docs/providers/openai) and [Anthropic](/docs/providers/anthropic) helpers also accept the session itself (`handle_tool_calls(response=response, session=session)` in Python, `handleToolCalls(session, response)` in TypeScript), which routes through the session while keeping provider argument normalization.
162
163 #### Reading execution results
164
165 `session.execute()` returns a result envelope, not the tool payload directly:
166
167 | TypeScript | Python | Meaning |
168 | --- | --- | --- |
169 | `data` | `data` | The tool-specific output. |
170 | `error` | `error` | Error text, or `null` (`None` in Python). A failed execution can have no error text. |
171 | `logId` | `log_id` | The execution log ID. Local tools return an empty string. |
172 | `resultType` | `result_type` | `completed` if execution succeeded, or `failed` if it failed. |
173
174 The result can also include `instantCharge` (`instant_charge` in Python) when you enable [Instant usage charge reporting](/docs/instant-tools#report-charges-and-use-instant-tools).
175
176 Use `resultType` (`result_type` in Python) to check success, as shown above. Checking `error` alone can mistake a failed execution with an empty error for a success.
177
178 Unlike direct `composio.tools.execute()` results, session results have no top-level `successful` field. A `successful` field inside `data` belongs to the tool-specific payload and is not guaranteed. Don't use `result.data.successful` as a general session success check.
179
180 If you pass a custom TypeScript `ToolCallSession` to a provider, its `execute()` method must return `resultType`; providers use it to determine `successful`.
181
182 #### Handling requests for user input
183
184 A session tool can request user input, such as an approval, before it runs. In Python, catch `ToolInputRequiredError` from `composio.exceptions`. In TypeScript, catch `ComposioToolInputRequiredError` from `@composio/core`. The error carries the questions on `input_requests` / `inputRequests` and opaque continuation state on `request_state` / `requestState`.
185
186 This also applies to provider-wrapped session tools, `session.proxy_execute()` / `session.proxyExecute()`, and the session execution helpers passed to local tools. Present the questions to your user rather than treating the error as an empty tool result.
187
188 <Callout type="warn">
189 An input-required call has not executed and is not retried. To resume `session.execute()` or `session.executeMeta()` in TypeScript, repeat the call with `inputResponses` and `requestState`. In Python, repeat `session.execute()` or `session.execute_meta()` with `input_responses` and `request_state`. Wait for the person's answers and forward decline and cancel responses unchanged. Keep the continuation state unchanged; it is excluded from logs and serialized error output, so read it directly from the error object.
190 </Callout>
191
192 The TypeScript Google and Cloudflare providers also accept `executeToolCall(session, toolCall)`. Pass the Session that produced the tools to preserve its execution settings. Passing a user ID uses direct execution.
193
194 ## Sandbox
195
196 Handle large responses and bulk operations in the remote sandbox. Instead of stuffing long tool responses into the model context, the agent reads files, searches outputs, writes Python, transforms data, and calls Composio tools in bulk.
197
198 The sandbox is scoped to the session, so files, variables, helper functions, and intermediate results stay available while the agent works through a task. Learn more about [sandboxes here](/docs/sandbox/remote).
199
200 ## How sessions behave
201
202 Every `create()` call returns a new session ID. Use it for a fresh task context.
203
204 Sessions persist on the server and don't expire. For multi-turn conversations, store the session ID and reuse it with `composio.use()` instead of calling `create()` again.
205
206 <Tabs groupId="language" items={['Python', 'TypeScript', 'API']} persist>
207 <Tab value="Python">
208 ```python
209 session = composio.use("session_id")
210 tools = session.tools()
211 ```
212 </Tab>
213 <Tab value="TypeScript">
214 ```typescript
215 import { Composio } from '@composio/core';
216 const composio = new Composio({ apiKey: 'your_api_key' });
217 // ---cut---
218 const session = await composio.use("session_id");
219 const tools = await session.tools();
220 ```
221 </Tab>
222 <Tab value="API">
223 ```bash
224 curl -X GET https://backend.composio.dev/api/v3.1/tool_router/session/session_id \
225 -H "x-api-key: $COMPOSIO_API_KEY"
226
227 curl -X GET https://backend.composio.dev/api/v3.1/tool_router/session/session_id/tools \
228 -H "x-api-key: $COMPOSIO_API_KEY"
229 ```
230 </Tab>
231 </Tabs>
232
233 You can also update a session in place instead of creating a new one:
234
235 <Tabs groupId="language" items={['Python', 'TypeScript', 'API']} persist>
236 <Tab value="Python">
237 ```python
238 session.update(
239 toolkits={"enable": ["gmail", "slack"]},
240 auth_configs={"gmail": "ac_new_config"},
241 connected_accounts={"slack": ["ca_work_slack"]},
242 )
243 ```
244 </Tab>
245 <Tab value="TypeScript">
246 ```typescript
247 import { Composio } from '@composio/core';
248 const composio = new Composio({ apiKey: 'your_api_key' });
249 const session = await composio.use("session_id");
250 // ---cut---
251 await session.update({
252 toolkits: ["gmail", "slack"],
253 authConfigs: { gmail: "ac_new_config" },
254 connectedAccounts: { slack: ["ca_work_slack"] },
255 });
256 ```
257 </Tab>
258 <Tab value="API">
259 ```bash
260 curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/session_id \
261 -H "x-api-key: $COMPOSIO_API_KEY" \
262 -H "Content-Type: application/json" \
263 -d '{
264 "toolkits": {"enable": ["gmail", "slack"]},
265 "auth_configs": {"gmail": "ac_new_config"},
266 "connected_accounts": {"slack": ["ca_work_slack"]}
267 }'
268 ```
269 </Tab>
270 </Tabs>
271
272 Create a new session for a different user or a fundamentally different task setup. Reuse or update a session when the same conversation should keep its tool, auth, and workbench context.
273
274 ## Next
275
276 <Card icon={<Wrench />} title="Configuring Sessions" href="/docs/configuring-sessions" description="Enable toolkits, set auth configs, and select connected accounts" />