---
canonical_url: "https://docs.composio.dev/docs/sessions/updating-sessions"
markdown_url: "https://docs.composio.dev/docs/sessions/updating-sessions.md"
product: "platform"
version: null
last_updated: null
---

# Update a session (/docs/sessions/updating-sessions)

## Reading and updating session configuration [#reading-and-updating-session-configuration]

In TypeScript, `session.config` exposes the configuration returned by the server. Call `session.update()` to change selected fields. It preserves omitted fields, updates `session.config` in place, and returns the updated configuration. See [Updating a session](/docs/sessions/create-and-reuse#how-sessions-behave) for an example.

`ToolRouterSessionConfig` and `ToolRouterSessionConfigHistoryConfig` use the API client's types. The SDK returns the config as sent by the API, without validating `instant` at runtime or removing `premium_usage`. `instant` is always present as `false` or a policy object. Use `ToolRouterSessionConfig['instant']` when you need its TypeScript type.

When inspecting a returned config, handle `toolkits` and individual `tools` entries that contain only `require_approval`, without `enabled` or `disabled`. `tags` can also carry `require_approval`, and the config can include `proxy_execute`. These fields also appear in configurations returned by `session.listConfigHistory()`.

In Python, `session.config.instant` is a model when it contains a policy. Read its fields with attribute access rather than dictionary indexing, just as you do for [Instant charges](/docs/instant-tools#return-the-charge-with-a-call).

> If you implement the TypeScript `Session` interface yourself, include the required `config` member. Sessions created by the SDK provide it automatically.

## Updating a session [#updating-a-session]

`session.update()` patches the stored configuration in place. Fields you omit are preserved, so you can widen or narrow one part of a session without restating the rest. The SDK refreshes `session.config` and the session's config version only after the API accepts the change.

**Python:**
```python
session = composio.sessions.use("session_id")

session.update(toolkits={"enable": ["gmail", "github"]})
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");

await session.update({ toolkits: { enable: ["gmail", "github"] } });
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkits": {"enable": ["gmail", "github"]}}'
```

> The update behavior below requires `@composio/core` ≥ `0.19.1` (TypeScript) or `composio` ≥ `0.22.1` (Python).

### Maps replace, they don't merge [#maps-replace-they-dont-merge]

A `tools`, `authConfigs`, or `connectedAccounts` map you send replaces the stored map entirely. The API does not merge entries, so a Slack-only `tools` map removes a Gmail entry that was stored before it.

Stored before the update:

```json
{
  "tools": {
    "gmail": { "enable": ["GMAIL_FETCH_EMAILS"] },
    "slack": { "enable": ["SLACK_SEND_MESSAGE"] }
  }
}
```

The update:

**Python:**
```python
session.update(
    tools={"slack": {"enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]}},
)
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({
  tools: { slack: { enable: ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] } },
});
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tools": {"slack": {"enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"]}}}'
```

Stored after the update. The `gmail` entry is gone:

```json
{
  "tools": {
    "slack": { "enable": ["SLACK_SEND_MESSAGE", "SLACK_LIST_CHANNELS"] }
  }
}
```

To change one entry, send the whole map with every entry you want to keep. An empty map (`{}`) is stored as an explicit empty map.

The same rule applies to `toolkits`, `tags`, and `preload`: a value replaces the stored policy. `manageConnections`, `sandbox`, and `multiAccount` merge the subfields you send, and an empty object changes nothing.

### Narrowing an existing session to no app toolkits [#narrowing-an-existing-session-to-no-app-toolkits]

An empty allowlist on update denies every app toolkit, exactly as it does on create. The SDK sends `{ "enable": [] }` as-is instead of dropping it from the request.

**Python:**
```python
session.update(toolkits={"enable": []})
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({ toolkits: { enable: [] } });
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkits": {"enable": []}}'
```

### Removing a callback URL [#removing-a-callback-url]

`manageConnections.callbackUrl: null` removes only the stored callback URL. `enable` and the other connection settings stay as they are. An empty string is rejected.

**Python:**
```python
session.update(manage_connections={"callback_url": None})
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({ manageConnections: { callbackUrl: null } });
```

**API:**
{/* code-example: unchecked-api rule="api-body-schema" operation="PATCH /api/v3.1/tool_router/session/{session_id}" field="manage_connections.callback_url" reason="openapi.json types callback_url as a string; the API accepts null to remove it" */}

```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"manage_connections": {"callback_url": null}}'
```

### Clearing a block with null [#clearing-a-block-with-null]

Passing `null` (`None` in Python) for a whole block removes the stored override and the session falls back to the default for that block. Every policy block accepts it: `toolkits`, `tools`, `tags`, `authConfigs`, `connectedAccounts`, `preload`, `manageConnections`, `sandbox`, `proxyExecute`, `multiAccount`, `search`, `execute`, and `experimental`.

**Python:**
```python
session.update(manage_connections=None, multi_account=None)
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({ manageConnections: null, multiAccount: null });
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"manage_connections": null, "multi_account": null}'
```

Clearing a policy can widen access. `toolkits: null` removes the toolkit policy and restores the unrestricted default, which is the opposite of `{ "enable": [] }`; clearing `preload` does the same for preloaded tools, so the agent can reach more than before the update. Send `toolkits: []` when you want to deny every app toolkit. Clearing `multiAccount` resolves to disabled, while omitting it preserves the stored setting.

### Blocks you can set only on update [#blocks-you-can-set-only-on-update]

`search`, `execute`, and `experimental` are not part of `create()`. Reach them with `session.update()` on an existing session.

**Python:**
```python
session.update(
    search={"enable": False},
    execute={"enable_multi_execute": False},
)
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({
  search: { enable: false },
  execute: { enableMultiExecute: false },
});
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"search": {"enable": false}, "execute": {"enable_multi_execute": false}}'
```

Both blocks are on by default. `search` controls the session's search helper, so disabling it leaves the agent with the tools you preloaded. `execute.enableMultiExecute` controls whether the agent can run several tool calls in one request. `manageConnections.enableConnectionRemoval` is update-only as well, and controls whether the session exposes the connection-removal tool.

The `experimental` block on update holds server-side session settings: `permissions`, `linkUrlOverwrite`, `fastMode`, `submitFeedback`, and `sessionConfigId`. `sessionConfigId` applies a [saved Session config](/docs/sessions/saved-session-policies#applying-a-config-to-an-existing-session) and can't be combined with `toolkits`, `tools`, or `tags`. The `experimental` block on update is a different field from the `experimental` option on `create()`, which holds [local tools and toolkits](/docs/extending-sessions/local-tools-and-toolkits) that run in your process, so `experimental: null` on an update leaves those alone.

### Multi-account mode after an update [#multi-account-mode-after-an-update]

The canonical disabled state is `{ "enable": false, "require_explicit_selection": false }` with no maximum. Sending `enable: false` resets a stale maximum or selection setting, and reapplying that disabled configuration is accepted. Combining `enable: false` with `maxAccountsPerToolkit` or `requireExplicitSelection: true` is rejected with a `400`.

### Preload must stay inside the policy [#preload-must-stay-inside-the-policy]

An update that narrows `toolkits`, `tools`, or `tags` while leaving an explicitly preloaded tool outside the new policy is rejected with a `400`, and nothing changes. Fix `preload` in the same update:

**Python:**
```python
session.update(
    toolkits={"enable": ["slack"]},
    preload={"tools": ["SLACK_SEND_MESSAGE"]},
)
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.sessions.use("session_id");
await session.update({
  toolkits: { enable: ["slack"] },
  preload: { tools: ["SLACK_SEND_MESSAGE"] },
});
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkits": {"enable": ["slack"]}, "preload": {"tools": ["SLACK_SEND_MESSAGE"]}}'
```

### Concurrent updates [#concurrent-updates]

Every session response carries a config version (`session.configVersion` in TypeScript, `session.config_version` in Python, `config_version` on the wire). By default, `session.update()` sends no precondition, so the last writer wins. To make an update conditional, pass the version you read as `expectedConfigVersion` (`expected_config_version` in Python). The API then applies the update only when the stored version still matches. Otherwise it answers `409` and writes nothing: no config change, no history entry, no cache update. The SDK never retries that request, so a conflict is reported exactly once.

> The API must support `expected_config_version`. If it doesn't, it rejects a conditional update with a `400`.

On a conflict, the SDK raises `ComposioSessionConfigConflictError` (TypeScript) or `SessionConfigConflictError` (Python) and leaves the session object as it was. Re-read the session with `sessions.use()`, reapply your change on top of the fresh config, and retry:

**Python:**
```python
from composio.exceptions import SessionConfigConflictError

session = composio.sessions.use("session_id")

try:
    session.update(
        toolkits={"enable": ["gmail", "github"]},
        expected_config_version=session.config_version,
    )
except SessionConfigConflictError:
    # Another client changed the session first. Nothing was written.
    session = composio.sessions.use("session_id")
    session.update(
        toolkits={"enable": ["gmail", "github"]},
        expected_config_version=session.config_version,
    )
```

**TypeScript:**
```typescript
import { Composio, ComposioSessionConfigConflictError } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
let session = await composio.sessions.use("session_id");

try {
  await session.update({
    toolkits: { enable: ["gmail", "github"] },
    expectedConfigVersion: session.configVersion,
  });
} catch (error) {
  if (!(error instanceof ComposioSessionConfigConflictError)) throw error;
  // Another client changed the session first. Nothing was written.
  session = await composio.sessions.use("session_id");
  await session.update({
    toolkits: { enable: ["gmail", "github"] },
    expectedConfigVersion: session.configVersion,
  });
}
```

**API:**
{/* code-example: unchecked-api rule="api-body-schema" operation="PATCH /api/v3.1/tool_router/session/{session_id}" field="expected_config_version" reason="the PATCH endpoint accepts expected_config_version but its OpenAPI schema omits the field" */}

```bash
CONFIG_VERSION=$(curl -s -X GET https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" | jq -r '.config_version')

# Returns 409 and writes nothing if another client changed the session first.
# Re-read config_version and retry.
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkits": {"enable": ["gmail", "github"]}, "expected_config_version": '"$CONFIG_VERSION"'}'
```

You can also pass a version you read elsewhere, for example one stored with a queued job. `expectedConfigVersion: false` (`expected_config_version=False`) is the same as omitting it. The API still commits only a fully validated configuration, so a losing update never leaves a half-applied session behind.

Raw HTTP callers set `expected_config_version` in the `PATCH` body themselves; without it the last writer wins.

To roll a session back, read a previous configuration from its config history (`GET /api/v3.1/tool_router/session/{session_id}/config_history`) and convert it into an update request. A history entry is not a request body: it carries metadata and version fields, and it names toolkits and tools as `enabled` and `disabled`, which map to `enable` and `disable` in the update.

## update() [#update]

Patch the session configuration in place. See [Updating a session](/docs/sessions/updating-sessions#updating-a-session) for what omitted fields, replaced maps, `null`, and `expectedConfigVersion` do.

**Python:**
```python
config = session.update(toolkits={"enable": ["gmail", "github"]})
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.create("user_123");
const config = await session.update({ toolkits: { enable: ["gmail", "github"] } });
```

**API:**
```bash
curl -X PATCH https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID \
  -H "x-api-key: $COMPOSIO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"toolkits": {"enable": ["gmail", "github"]}}'
```

## Configuration history [#configuration-history]

Inspect the configurations a session has used with `session.list_config_history(limit=10)` in Python or `await session.listConfigHistory({ limit: 10 })` in TypeScript. Results are newest first, with the live configuration first. Each `session.update()` archives the previous configuration.

The response contains `items` with each version's `config` and an `is_current` (Python) or `isCurrent` (TypeScript) flag. Pass the response's `next_cursor` (Python) or `nextCursor` (TypeScript) as `cursor` to fetch another page; `limit` supports up to 100 items per page.

## Related guides [#related-guides]

For framework examples, see [OpenAI](/docs/providers/openai) or [Vercel AI SDK](/docs/providers/vercel). To connect over MCP, see [Using sessions via MCP](/docs/sessions-via-mcp).

---

📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Changelog](https://docs.composio.dev/docs/changelog.md) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)

---

# Composio SDK — Notes for AI Code Generators

**Purpose:** Reference for generating current (v3) [Composio](https://composio.dev/) integration code.
**Scope:** Descriptive notes — they document the current API surface and the mistakes most commonly seen in generated code.

---

## 1. Recommended Integration: Sessions

For agent tool delivery, Composio supports **Native Tools** (with a provider package) and **MCP** (no provider package needed).

For application-owned tools or deterministic backend code, use [managed authentication with Proxy Execute](/docs/authentication/managed-auth-for-custom-tools). A session can provide a user-scoped runtime context without an LLM or MCP. Composio authenticates provider requests server-side; connected-account reads redact credentials and aren't a supported token-export workflow.

### Native Tools

#### Python

```python
# ✅ CORRECT — Python (defaults to OpenAI)
from composio import Composio

composio = Composio()
session = composio.create(user_id="user_123")
tools = session.tools()
# Pass tools to your agent/LLM framework
```

#### TypeScript

```typescript
// ✅ CORRECT — TypeScript (defaults to OpenAI)
import { Composio } from "@composio/core";

const composio = new Composio();
const session = await composio.create("user_123");
const tools = await session.tools();
// Pass tools to your agent/LLM framework
```

#### API

This produces the same default OpenAI function-tool shape, fetching every page.

```bash
set -euo pipefail
SESSION=$(curl --fail-with-body -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
  -H "x-api-key: $COMPOSIO_API_KEY" -H "Content-Type: application/json" \
  -d '{"user_id":"user_123"}')
SESSION_ID=$(echo "$SESSION" | jq -r '.session_id')
TOOLS='[]'
CURSOR=''
while true; do
  PAGE=$(curl --fail-with-body -s --get "https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/tools" \
    -H "x-api-key: $COMPOSIO_API_KEY" --data-urlencode 'limit=500' --data-urlencode "cursor=$CURSOR")
  TOOLS=$(jq -cn --argjson existing "$TOOLS" --argjson page "$PAGE" \
    '$existing + [$page.items[] | {type:"function",function:{name:.slug,description:.description,parameters:.input_parameters}}]')
  CURSOR=$(echo "$PAGE" | jq -r '.next_cursor // empty')
  [ -n "$CURSOR" ] || break
done
printf '%s\n' "$TOOLS"
```

For other providers, pass the provider explicitly. Provider packages follow the naming convention: `composio_<provider>` for Python, `@composio/<provider>` for TypeScript.

### MCP

Use `session.mcp.url` and `session.mcp.headers` with any MCP-compatible client (Claude Desktop, Cursor, OpenAI Agents, etc.). No provider package needed.

---

## 2. Integration Notes

- `composio.create(user_id)` is the standard entry point for agent integrations. Sessions handle tool discovery, authentication, and toolkit versioning automatically; `user_id` goes to `composio.create()` — individual tool calls in session mode don't take one.
- Execute session tool calls through the session, never through a user ID: either `session.execute(tool_slug, arguments=...)` / `session.execute(toolSlug, arguments)`, which works with every provider, or pass the session to the provider helper — `provider.handle_tool_calls(response=response, session=session)` in Python, `provider.handleToolCalls(session, response)` in TypeScript. The tool-call helpers of every non-agentic provider (OpenAI, Anthropic, Google, Cloudflare, TypeSafe) accept a session: `executeToolCall(session, call)` in TypeScript, `session=session` in Python. Agentic providers execute session tools on their own. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with `"can only be called inside a tool-router session"`.
- Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
- Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is `composio_openai_agents` / `@composio/openai-agents` (importing `composio_openai` / `@composio/openai` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
- **Direct execution** (`composio.tools.get()`, `composio.tools.execute()`, `provider.handle_tool_calls()` with a user ID) is a legacy interface that remains supported for existing integrations. Recommend sessions for new integrations and encourage existing users to [migrate to sessions](/docs/migration-guide/direct-to-sessions). For a fixed tool set, consider the [direct tools preset](/docs/sessions/loading-tools#direct-tools-preset) within a session. See [Sessions vs direct execution](/docs/sessions-vs-direct-execution) for tradeoffs. Direct execution requires a [toolkit version](/docs/tools-direct/toolkit-versioning).

---

# 3. Calling the REST API directly

## REST API version

The current REST API version is **v3.1**, served at `https://backend.composio.dev/api/v3.1`. Prefer it for new code and new examples.

`https://backend.composio.dev/api/v3` is the previous version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.

## Tool-endpoint version defaults on v3.1

On v3.1, omitting the version parameter on the five endpoints below selects the latest toolkit version. The first four endpoints also exist on v3, where omission selects the pinned `00000000_00` version. `POST /tools/scopes/required` is v3.1-only.

| Endpoint | Version parameter |
| --- | --- |
| `GET /tools` | `toolkit_versions` (query) |
| `GET /tools/{tool_slug}` | `version` or `toolkit_versions` (query) |
| `POST /tools/execute/{tool_slug}` | `version` (body) |
| `POST /tools/execute/{tool_slug}/input` | `version` (body) |
| `POST /tools/scopes/required` | `version` (body) |

A v3.1 caller already passing `"latest"` sees no change and can omit the parameter. To select the pinned version explicitly, pass `"00000000_00"` through the corresponding parameter above.

This version-default change is limited to the five endpoints above.


---

## Terminology Migration (old → current)

If you encounter these terms in error messages, old documentation, or user prompts, translate them to the current equivalents. **Do not use the old terms in generated code or explanations.**

| Old term (v1/v2) | Current term (v3) | In code |
|---|---|---|
| entity ID | user ID | `user_id` parameter |
| actions | tools | e.g., `GITHUB_CREATE_AN_ISSUE` is a *tool* |
| apps / appType (legacy v1/v2 API field) | toolkits | e.g., `github` is a *toolkit*. The current word **App** is *not* legacy: it names a catalog grouping of sibling toolkits (the Notion app groups `notion` and `notion_mcp`); do not translate it |
| integration / integration ID | auth config / auth config ID | `auth_config_id` parameter |
| connection | connected account | `connected_accounts` namespace |
| ComposioToolSet / OpenAIToolSet | `Composio` class with a provider | `Composio(provider=...)` |
| toolset | provider | e.g., `OpenAIProvider` |

If a user says "entity ID", they mean `user_id`. If they say "integration", they mean "auth config". Always respond using the current terminology.

