@devries-cameron20 / composio-1 / commits / c7843d8a3
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.

feat(core): return session config from session.update() (#4533)

This PR: - makes `session.update()` resolve to the updated server-side session configuration instead of `void` - exposes that configuration as `session.config` (new `ToolRouterSessionConfig` type) on sessions from `create()`, `use()` and attach, so the toolkit/tool allowlist is readable without dropping to the raw client - renames the private SDK-config member on `ToolRouterSession` to `sdkConfig`, ending the runtime name clash that made `session.config` look like the SDK's `ComposioConfig` - applies the same change to the Python `ToolRouterSession` (`config` attribute, `update()` returns it) - adds a minor changeset for `@composio/core` ## Context After `sessions.use(id)` there was no way to know the session's allowlist, and `update()` threw the response away except for `configVersion` / `preload` / `sandbox` / `warnings`. Hackathon feedback (area 8).

Alberto Schiabel committed Sep 18, 2026 at 18:29 UTC c7843d8a3a1404da6049df63997fde06ac063f1c
8 files changed +184 -15
.changeset/session-update-returns-config.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Expose the server-side session configuration on sessions and return it from `update()`. `session.config` now carries the toolkit/tool allowlists, tags, auth configs, connected accounts, `manage_connections`, preload and sandbox settings the API returned for the session (from `create()`, `use()` and after every `update()`), and `session.update()` resolves to that updated config instead of `void`. Previously the only `config` reachable on a session object at runtime was the SDK's own `ComposioConfig`, and reading the live allowlist after `sessions.use(id)` required dropping to the raw client.
6 +
7 +`config` is a required member of the `Session` interface, so objects you construct yourself to satisfy `Session` (test doubles, wrappers) now need a `config` value. Callers of SDK-created sessions are unaffected. The read side is the raw API shape (`toolkits.enabled`, `manage_connections`), while `update()` keeps taking the SDK's camelCase input.
python/composio/core/models/tool_router.py
+2
@@ -1118,6 +1118,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1118 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
1119 file_upload_dirs=self._file_upload_dirs,
1120 session_id=session.session_id,
1121 + config=session.config,
1122 mcp=self._create_mcp_server_config(
1123 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
1124 url=session.mcp.url,
@@ -1266,6 +1267,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1267 file_upload_path_deny_segments=self._file_upload_path_deny_segments,
1268 file_upload_dirs=self._file_upload_dirs,
1269 session_id=session.session_id,
1270 + config=session.config,
1271 mcp=self._create_mcp_server_config(
1272 mcp_type=ToolRouterMCPServerType(session.mcp.type.lower()),
1273 url=session.mcp.url,
python/composio/core/models/tool_router_session.py
+41 -4
@@ -19,7 +19,14 @@ from composio_client.types.tool_list_response import (
19 ItemDeprecatedToolkit,
20 ItemToolkit,
21 )
22 -from composio_client.types.tool_router import session_link_params, session_patch_params
22 +from composio_client.types.tool_router import (
23 + session_attach_response,
24 + session_create_response,
25 + session_link_params,
26 + session_patch_params,
27 + session_patch_response,
28 + session_retrieve_response,
29 +)
30 from composio_client.types.tool_router.session_execute_response import (
31 SessionExecuteResponse,
32 )
@@ -87,6 +94,18 @@ class ToolRouterSessionPreloadConfig:
94 tools: t.Union[t.List[str], t.Literal["all"]]
95
96
97 +#: Server-side session configuration as returned by the API: toolkit and tool
98 +#: allowlists, tags, auth configs, connected accounts, ``manage_connections``,
99 +#: preload, sandbox (``workbench``), search and execute settings. The four
100 +#: Stainless response models carry the same fields.
101 +ToolRouterSessionConfig = t.Union[
102 + session_create_response.Config,
103 + session_retrieve_response.Config,
104 + session_attach_response.Config,
105 + session_patch_response.Config,
106 +]
107 +
108 +
109 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
110 """
111 A Composio session — the object returned by ``composio.create(...)`` /
@@ -105,11 +124,17 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
124
125 Attributes:
126 session_id: Unique session identifier
127 + config: Server-side session configuration as returned by the API,
128 + refreshed in place by :meth:`update`
129 experimental: Experimental features (files, assistive prompt, etc.)
130 """
131
132 #: Unique session identifier.
133 session_id: str
134 + #: Server-side session configuration (toolkit/tool allowlists, tags,
135 + #: preload, sandbox, manage_connections) as returned by the API. Refreshed
136 + #: in place by :meth:`update`.
137 + config: ToolRouterSessionConfig
138 #: Experimental capabilities available on this session.
139 experimental: "ToolRouterSessionExperimental"
140
@@ -125,6 +150,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
150 session_id: str,
151 mcp: t.Any,
152 experimental: "ToolRouterSessionExperimental",
153 + config: t.Optional[ToolRouterSessionConfig] = None,
154 custom_tools_map: t.Optional[CustomToolsMap] = None,
155 user_id: t.Optional[str] = None,
156 preload: t.Optional[ToolRouterSessionPreloadConfig] = None,
@@ -138,13 +164,21 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
164 self._file_upload_path_deny_segments = file_upload_path_deny_segments
165 self._file_upload_dirs = file_upload_dirs
166 self.session_id = session_id
167 + self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
168 + # Sessions built from an API response always carry their config; the
169 + # fallback only covers direct construction without one (tests).
170 + self.config = config or session_create_response.Config(
171 + user_id=user_id or "",
172 + execute=session_create_response.ConfigExecute(),
173 + search=session_create_response.ConfigSearch(),
174 + preload=session_create_response.ConfigPreload(tools=self.preload.tools),
175 + )
176 # The MCP endpoint exists on every session at runtime (kept for
177 # backwards compatibility), but is only typed via
178 # ToolRouterSessionWithMcp. Assign through setattr so type checkers do
179 # not surface `mcp` on the base class — MCP is an explicit opt-in.
180 setattr(self, "mcp", mcp)
181 self.experimental = experimental
147 - self.preload = preload or ToolRouterSessionPreloadConfig(tools=[])
182 self._custom_tools_map = custom_tools_map
183 self._user_id = user_id
184 self._preloaded_custom_tool_slugs = preloaded_custom_tool_slugs or []
@@ -909,11 +943,12 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
943 t.Optional[session_patch_params.MultiAccount], "Omit"
944 ] = omit,
945 preload: t.Union[session_patch_params.Preload, "Omit"] = omit,
912 - ) -> None:
946 + ) -> ToolRouterSessionConfig:
947 """Partially update the session configuration.
948
949 Only the fields provided will be changed; omitted fields are preserved.
916 - Mutates this session's ``preload`` in-place.
950 + Mutates this session's ``config`` and ``preload`` in-place and returns
951 + the updated session configuration.
952
953 Pass ``None`` for ``manage_connections``, ``sandbox``/``workbench``, or
954 ``multi_account`` to clear the stored value.
@@ -946,7 +981,9 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
981 multi_account=multi_account,
982 preload=preload,
983 )
984 + self.config = response.config
985 self.preload = _session_preload_config(response.config.preload)
986 + return self.config
987
988 def delete(self) -> ToolRouterSessionDeleteResponse:
989 """
python/tests/test_tool_router.py
+33
@@ -1101,11 +1101,44 @@ class TestToolRouter:
1101 assert callable(session.toolkits)
1102 assert callable(session.delete)
1103 assert session.preload.tools == ["GMAIL_FETCH_EMAILS"]
1104 + assert (
1105 + session.config
1106 + is mock_client.tool_router.session.retrieve.return_value.config
1107 + )
1108
1109 mock_client.tool_router.session.retrieve.assert_called_once_with("session_123")
1110 mock_client.tool_router.session.attach.assert_not_called()
1111 mock_client.post.assert_not_called()
1112
1113 + def test_create_session_exposes_config(self, tool_router, mock_client):
1114 + """create() exposes the server-side session config on the session."""
1115 + create_config = mock_client.tool_router.session.create.return_value.config
1116 + create_config.toolkits = {"enabled": ["gmail"]}
1117 +
1118 + session = tool_router.create(user_id="user_123", toolkits=["gmail"])
1119 +
1120 + assert session.config is create_config
1121 + assert session.config.toolkits == {"enabled": ["gmail"]}
1122 +
1123 + def test_update_session_returns_config(self, tool_router, mock_client):
1124 + """update() returns the patched config and refreshes it on the session."""
1125 + patched = MagicMock()
1126 + patched.toolkits = {"enabled": ["gmail"]}
1127 + patched.preload = MagicMock()
1128 + patched.preload.tools = ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
1129 + mock_client.tool_router.session.patch.return_value.config = patched
1130 +
1131 + session = tool_router.use(session_id="session_123")
1132 + before = session.config
1133 +
1134 + config = session.update(toolkits={"enable": ["gmail"]})
1135 +
1136 + mock_client.tool_router.session.patch.assert_called_once()
1137 + assert config is patched
1138 + assert session.config is patched
1139 + assert session.config is not before
1140 + assert session.preload.tools == ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"]
1141 +
1142 def test_session_delete(self, tool_router, mock_client):
1143 """Session delete removes the current session."""
1144 mock_client.delete.return_value = {
ts/packages/core/src/models/ToolRouter.ts
+1
@@ -71,6 +71,7 @@ function getSessionMetadata(
71 session: SessionCreateResponse | SessionRetrieveResponse | SessionAttachResponse
72 ) {
73 const metadata: ToolRouterSessionMetadata = {
74 + config: session.config,
75 preload: session.config.preload,
76 workbench: session.config.workbench,
77 configVersion: session.config_version,
ts/packages/core/src/models/ToolRouterSession.ts
+25 -8
@@ -16,6 +16,7 @@ import {
16 ToolRouterSessionExecuteResponseSchema,
17 ToolRouterSessionProxyExecuteResponse,
18 ToolRouterSessionExecuteOptions,
19 + ToolRouterSessionConfig,
20 ToolRouterSessionMetadata,
21 ToolRouterSessionPreloadConfig,
22 ToolRouterSessionWorkbenchConfig,
@@ -118,6 +119,12 @@ export class ToolRouterSession<
119 /** Hosted MCP endpoint (`session.mcp.url` / `session.mcp.headers`). Exists on every session at runtime, but only surfaced in the type when the session is created with `{ mcp: true }` (which returns `Session`); the default `SessionWithoutMcp` omits `mcp`, so MCP is an explicit opt-in. See https://docs.composio.dev/docs/sessions-via-mcp */
120 public readonly mcp: ToolRouterMCPServerConfig;
121 public readonly experimental: SessionExperimental;
122 + /**
123 + * Server-side session configuration (toolkit/tool allowlists, tags, preload,
124 + * sandbox, manage_connections) as returned by the API. Refreshed in place by
125 + * `update()`.
126 + */
127 + public config: ToolRouterSessionConfig;
128 public preload: ToolRouterSessionPreloadConfig;
129 /** Resolved sandbox (code-execution) config returned by the API. `enable` defaults to `true` server-side. */
130 public sandbox?: ToolRouterSessionWorkbenchConfig;
@@ -131,7 +138,7 @@ export class ToolRouterSession<
138
139 constructor(
140 private readonly client: ComposioClient,
134 - private readonly config: ComposioConfig<TProvider> | undefined,
141 + private readonly sdkConfig: ComposioConfig<TProvider> | undefined,
142 sessionId: string,
143 mcp: ToolRouterMCPServerConfig,
144 experimentalOverrides?: Pick<SessionExperimental, 'assistivePrompt'>,
@@ -139,6 +146,12 @@ export class ToolRouterSession<
146 private readonly userId?: string,
147 metadata?: ToolRouterSessionMetadata
148 ) {
149 + const config: ToolRouterSessionConfig = metadata?.config ?? {
150 + user_id: userId ?? '',
151 + execute: {},
152 + search: {},
153 + preload: { tools: [] },
154 + };
155 if (customToolsMap && !userId) {
156 throw new Error('userId is required when custom tools are bound to a session.');
157 }
@@ -148,8 +161,9 @@ export class ToolRouterSession<
161 assistivePrompt: experimentalOverrides?.assistivePrompt,
162 files: new ToolRouterSessionFilesMount(client, sessionId),
163 };
151 - this.preload = metadata?.preload ?? { tools: [] };
152 - this.sandbox = metadata?.workbench;
164 + this.config = config;
165 + this.preload = metadata?.preload ?? config.preload;
166 + this.sandbox = metadata?.workbench ?? config.workbench;
167 this.configVersion = metadata?.configVersion;
168 this.warnings = metadata?.warnings ?? [];
169 this.preloadedCustomToolSlugs = metadata?.preloadedCustomToolSlugs ?? [];
@@ -193,7 +207,7 @@ export class ToolRouterSession<
207 modifiers?: SessionMetaToolOptions,
208 requestOptions?: ComposioRequestOptions
209 ): Promise<ReturnType<TProvider['wrapTools']>> {
196 - const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
210 + const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.sdkConfig);
211 const rawTools = await ToolsModel.getRawToolRouterSessionTools(
212 this.sessionId,
213 undefined,
@@ -226,13 +240,13 @@ export class ToolRouterSession<
240 );
241 };
242
229 - if (!this.config?.provider) {
243 + if (!this.sdkConfig?.provider) {
244 throw new Error(
245 'A provider is required when using custom tools with session.tools(). ' +
246 'Pass a provider in the Composio constructor.'
247 );
248 }
235 - return this.config.provider.wrapTools(sessionTools, routingExecuteFn) as ReturnType<
249 + return this.sdkConfig.provider.wrapTools(sessionTools, routingExecuteFn) as ReturnType<
250 TProvider['wrapTools']
251 >;
252 }
@@ -664,12 +678,13 @@ export class ToolRouterSession<
678 /**
679 * Partially update the session configuration.
680 * Only the fields provided will be changed; omitted fields are preserved.
667 - * Mutates this session's `configVersion`, `preload`, and `warnings` in-place.
681 + * Mutates this session's `config`, `configVersion`, `preload`, `sandbox`,
682 + * and `warnings` in-place, and resolves to the updated session `config`.
683 */
684 async update(
685 config: ToolRouterUpdateSessionConfig,
686 requestOptions?: ComposioRequestOptions
672 - ): Promise<void> {
687 + ): Promise<ToolRouterSessionConfig> {
688 const parsed = ToolRouterUpdateSessionConfigSchema.parse(config);
689 const params = transformToolRouterUpdateParams(parsed);
690 const response = await withCancellation(
@@ -677,9 +692,11 @@ export class ToolRouterSession<
692 requestOptions?.signal
693 );
694 this.configVersion = response.config_version;
695 + this.config = response.config;
696 this.preload = response.config.preload;
697 this.sandbox = response.config.workbench;
698 this.warnings = response.warnings ?? [];
699 + return this.config;
700 }
701
702 /**
ts/packages/core/src/types/toolRouter.types.ts
+19 -2
@@ -605,7 +605,16 @@ export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Work
605
606 export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
607
608 +/**
609 + * Server-side session configuration as returned by the API: toolkit and tool
610 + * allowlists, tags, auth configs, connected accounts, manage_connections,
611 + * preload, sandbox (`workbench`), search and execute settings.
612 + */
613 +export type ToolRouterSessionConfig = SessionCreateResponse.Config;
614 +
615 export interface ToolRouterSessionMetadata {
616 + /** Present on every session built from an API response; the constructor synthesises a minimal config when absent. */
617 + config?: ToolRouterSessionConfig;
618 preload?: ToolRouterSessionPreloadConfig;
619 workbench?: ToolRouterSessionWorkbenchConfig;
620 configVersion?: number;
@@ -699,7 +708,9 @@ export const ToolRouterUpdateSessionConfigSchema = z
708
709 export type ToolRouterUpdateSessionConfig = z.infer<typeof ToolRouterUpdateSessionConfigSchema>;
710
702 -export type ToolRouterSessionUpdateFn = (config: ToolRouterUpdateSessionConfig) => Promise<void>;
711 +export type ToolRouterSessionUpdateFn = (
712 + config: ToolRouterUpdateSessionConfig
713 +) => Promise<ToolRouterSessionConfig>;
714
715 export const ToolRouterSessionDeleteResponseSchema = z.object({
716 sessionId: z.string(),
@@ -719,6 +730,12 @@ export interface Session<
730 > {
731 sessionId: string;
732 mcp: ToolRouterMCPServerConfig;
733 + /**
734 + * Server-side session configuration (toolkit/tool allowlists, tags, preload,
735 + * sandbox, manage_connections) as returned by the API. Refreshed in place by
736 + * `update()`.
737 + */
738 + config: ToolRouterSessionConfig;
739 /** Stored preload configuration for this session. */
740 preload: ToolRouterSessionPreloadConfig;
741 /**
@@ -744,7 +761,7 @@ export interface Session<
761 search: ToolRouterSessionSearchFn;
762 /** Execute a tool within the session */
763 execute: ToolRouterSessionExecuteFn;
747 - /** Update the session configuration. Mutates this session in-place. */
764 + /** Update the session configuration. Mutates this session in-place and resolves to the updated `config`. */
765 update: ToolRouterSessionUpdateFn;
766 /** Delete the session. Deleted sessions are no longer retrievable or executable. */
767 delete: ToolRouterSessionDeleteFn;
ts/packages/core/test/models/toolRouter.test.ts
+56 -1
@@ -10,6 +10,7 @@ import {
10 ToolRouterCreateSessionConfig,
11 Session,
12 SessionPreset,
13 + type ToolRouterSessionConfig,
14 } from '../../src/types/toolRouter.types';
15 import { createCustomTool } from '../../src/models/CustomTool';
16 import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';
@@ -46,6 +47,7 @@ const createMockClient = () => ({
47 create: vi.fn(),
48 retrieve: vi.fn(),
49 attach: vi.fn(),
50 + patch: vi.fn(),
51 link: vi.fn(),
52 toolkits: vi.fn(),
53 search: vi.fn(),
@@ -87,7 +89,7 @@ const mockSessionRetrieveResponse = {
89 tool_router_tools: ['GMAIL_FETCH_EMAILS', 'SLACK_SEND_MESSAGE', 'GITHUB_CREATE_ISSUE'],
90 config: {
91 user_id: 'user_123',
90 - toolkits: { enable: ['gmail', 'slack', 'github'] },
92 + toolkits: { enabled: ['gmail', 'slack', 'github'] },
93 auth_configs: {},
94 connected_accounts: {},
95 manage_connections: {
@@ -250,6 +252,7 @@ describe('ToolRouter', () => {
252 expect(session.sessionId).toBe('session_123');
253 expect(session.preload.tools).toEqual([]);
254 expect(session.configVersion).toBe(1);
255 + expect(session.config).toEqual(mockSessionCreateResponse.config);
256 });
257
258 it('should create a session with preloaded tools', async () => {
@@ -3323,6 +3326,8 @@ describe('ToolRouter', () => {
3326 expect(session).toHaveProperty('delete');
3327 expect(session.preload.tools).toEqual(['GMAIL_FETCH_EMAILS']);
3328 expect(session.configVersion).toBe(7);
3329 + expect(session.config).toEqual(mockSessionRetrieveResponse.config);
3330 + expect(session.config.toolkits).toEqual({ enabled: ['gmail', 'slack', 'github'] });
3331 });
3332
3333 it('should attach custom tools when provided', async () => {
@@ -3658,4 +3663,54 @@ describe('ToolRouter', () => {
3663 expect(mockClient.post).not.toHaveBeenCalled();
3664 });
3665 });
3666 +
3667 + describe('update method', () => {
3668 + const sessionId = 'session_123';
3669 + const patchedConfig: ToolRouterSessionConfig = {
3670 + ...mockSessionRetrieveResponse.config,
3671 + toolkits: { enabled: ['gmail'] },
3672 + tags: { enabled: ['readOnlyHint'] },
3673 + preload: { tools: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'] },
3674 + workbench: { enable: false },
3675 + };
3676 +
3677 + beforeEach(() => {
3678 + mockClient.toolRouter.session.patch.mockResolvedValue({
3679 + session_id: sessionId,
3680 + config: patchedConfig,
3681 + config_version: 8,
3682 + warnings: [{ code: 'TOOLKIT_NOT_CONNECTED', message: 'gmail is not connected' }],
3683 + });
3684 + });
3685 +
3686 + it('should resolve to the updated session config', async () => {
3687 + const session = await toolRouter.use(sessionId);
3688 +
3689 + const config = await session.update({ toolkits: ['gmail'], tags: ['readOnlyHint'] });
3690 +
3691 + expect(mockClient.toolRouter.session.patch).toHaveBeenCalledWith(
3692 + sessionId,
3693 + expect.objectContaining({ toolkits: { enable: ['gmail'] } }),
3694 + undefined
3695 + );
3696 + expect(config).toEqual(patchedConfig);
3697 + expect(config.toolkits).toEqual({ enabled: ['gmail'] });
3698 + });
3699 +
3700 + it('should refresh config, preload, sandbox, configVersion and warnings in place', async () => {
3701 + const session = await toolRouter.use(sessionId);
3702 + expect(session.config).toEqual(mockSessionRetrieveResponse.config);
3703 + expect(session.configVersion).toBe(7);
3704 +
3705 + const config = await session.update({ toolkits: ['gmail'] });
3706 +
3707 + expect(session.config).toBe(config);
3708 + expect(session.preload.tools).toEqual(['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL']);
3709 + expect(session.sandbox).toEqual({ enable: false });
3710 + expect(session.configVersion).toBe(8);
3711 + expect(session.warnings).toEqual([
3712 + { code: 'TOOLKIT_NOT_CONNECTED', message: 'gmail is not connected' },
3713 + ]);
3714 + });
3715 + });
3716 });