Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(sdk): auto-detect OAuth tokens in AuthScheme helpers to prevent stuck INITIATED state
jkomynob4d82be00c2d
diff --git a/python/composio/core/models/connected_accounts.py b/python/composio/core/models/connected_accounts.pyindex 1d5ff80a8..bca54d0f6 100644--- a/python/composio/core/models/connected_accounts.py+++ b/python/composio/core/models/connected_accounts.py@@ -94,13 +94,22 @@ class AuthScheme:"""Create a new connected account using OAuth 1.0."""+ oauth_token = options.get("oauth_token") # type: ignore[union-attr]+ oauth_token_secret = options.get("oauth_token_secret") # type: ignore[union-attr]+ has_tokens = (+ isinstance(oauth_token, str)+ and len(oauth_token) > 0+ and isinstance(oauth_token_secret, str)+ and len(oauth_token_secret) > 0+ )+ status = "ACTIVE" if has_tokens else "INITIALIZING"return {"auth_scheme": "OAUTH1","val": t.cast(connected_account_create_params.ConnectionStateUnionMember0Val,{+ "status": status,**options,- "status": "INITIALIZING",},),}@@ -109,15 +118,18 @@ class AuthScheme:self, options: connected_account_create_params.ConnectionStateUnionMember1Val) -> connected_account_create_params.ConnectionState:"""- Create a new connected account using OAuth 1.0.+ Create a new connected account using OAuth 2.0."""+ access_token = options.get("access_token") # type: ignore[union-attr]+ has_token = isinstance(access_token, str) and len(access_token) > 0+ status = "ACTIVE" if has_token else "INITIALIZING"return {"auth_scheme": "OAUTH2","val": t.cast(connected_account_create_params.ConnectionStateUnionMember1Val,{+ "status": status,**options,- "status": "INITIALIZING",},),}diff --git a/python/tests/test_connected_accounts.py b/python/tests/test_connected_accounts.pyindex e55e8d84d..445f33f36 100644--- a/python/tests/test_connected_accounts.py+++ b/python/tests/test_connected_accounts.py@@ -13,7 +13,18 @@ from composio.core.models.connected_accounts import (class TestAuthScheme:- def test_oauth2_sets_initializing_status(self):+ def test_oauth2_with_access_token_sets_active_status(self):+ scheme = AuthScheme()+ options = {"access_token": "test_token", "refresh_token": "test_refresh"}++ state = scheme.oauth2(options)++ assert state["auth_scheme"] == "OAUTH2"+ assert state["val"]["access_token"] == "test_token"+ assert state["val"]["refresh_token"] == "test_refresh"+ assert state["val"]["status"] == "ACTIVE"++ def test_oauth2_without_access_token_sets_initializing_status(self):scheme = AuthScheme()options = {"client_id": "id", "client_secret": "secret"}@@ -24,6 +35,40 @@ class TestAuthScheme:assert state["val"]["client_secret"] == "secret"assert state["val"]["status"] == "INITIALIZING"+ def test_oauth2_with_empty_access_token_sets_initializing_status(self):+ scheme = AuthScheme()+ state = scheme.oauth2({"access_token": ""})++ assert state["val"]["status"] == "INITIALIZING"++ def test_oauth2_honors_explicit_status_override(self):+ scheme = AuthScheme()+ state = scheme.oauth2({"access_token": "test_token", "status": "INITIALIZING"})++ assert state["val"]["status"] == "INITIALIZING"++ def test_oauth1_with_both_tokens_sets_active_status(self):+ scheme = AuthScheme()+ state = scheme.oauth1({"oauth_token": "tok", "oauth_token_secret": "secret"})++ assert state["auth_scheme"] == "OAUTH1"+ assert state["val"]["oauth_token"] == "tok"+ assert state["val"]["oauth_token_secret"] == "secret"+ assert state["val"]["status"] == "ACTIVE"++ def test_oauth1_without_secret_sets_initializing_status(self):+ scheme = AuthScheme()+ state = scheme.oauth1({"oauth_token": "tok"})++ assert state["auth_scheme"] == "OAUTH1"+ assert state["val"]["status"] == "INITIALIZING"++ def test_oauth1_with_empty_token_sets_initializing_status(self):+ scheme = AuthScheme()+ state = scheme.oauth1({"oauth_token": "", "oauth_token_secret": "secret"})++ assert state["val"]["status"] == "INITIALIZING"+@pytest.mark.parametrize("method_name, expected_auth_scheme, expected_status",[@@ -288,6 +333,33 @@ class TestConnectedAccounts:assert call_kwargs["user_id"] == "user-1"assert "callback_url" not in call_kwargs+ def test_initiate_with_oauth2_tokens_returns_active_connection_request(+ self, connected_accounts, mock_client+ ):+ mock_accounts = Mock()+ mock_accounts.items = []+ mock_client.connected_accounts.list.return_value = mock_accounts++ mock_response = Mock()+ mock_response.id = "conn-active"+ mock_response.connection_data.val.status = "ACTIVE"+ mock_response.connection_data.val.redirect_url = None+ mock_client.connected_accounts.create.return_value = mock_response++ scheme = AuthScheme()+ config = scheme.oauth2(+ {"access_token": "tok", "refresh_token": "ref", "expires_in": 3600}+ )++ result = connected_accounts.initiate(+ user_id="user-1", auth_config_id="auth-1", config=config+ )++ assert isinstance(result, ConnectionRequest)+ assert result.id == "conn-active"+ assert result.status == "ACTIVE"+ assert result.redirect_url is None+def test_wait_for_connection_delegates_to_connection_request(self, mock_client):connected_accounts = ConnectedAccounts(client=mock_client)diff --git a/ts/packages/core/src/models/AuthScheme.ts b/ts/packages/core/src/models/AuthScheme.tsindex ae3564fcc..cf6ff8ce2 100644--- a/ts/packages/core/src/models/AuthScheme.ts+++ b/ts/packages/core/src/models/AuthScheme.ts@@ -33,10 +33,11 @@ export class AuthScheme {expired_at?: string;}): ConnectionData {+ const hasToken = typeof params.access_token === 'string' && params.access_token.length > 0;return {authScheme: AuthSchemeTypes.OAUTH2,val: {- status: ConnectionStatuses.INITIALIZING,+ status: hasToken ? ConnectionStatuses.ACTIVE : ConnectionStatuses.INITIALIZING,...params,},};@@ -50,6 +51,7 @@ export class AuthScheme {static OAuth1(params: BaseConnectionFields & {oauth_token?: string;+ oauth_token_secret?: string;consumer_key?: string;redirectUrl?: string;callback_url?: string;@@ -58,10 +60,15 @@ export class AuthScheme {expired_at?: string;}): ConnectionData {+ const hasTokens =+ typeof params.oauth_token === 'string' &&+ params.oauth_token.length > 0 &&+ typeof params.oauth_token_secret === 'string' &&+ params.oauth_token_secret.length > 0;return {authScheme: AuthSchemeTypes.OAUTH1,val: {- status: ConnectionStatuses.INITIALIZING,+ status: hasTokens ? ConnectionStatuses.ACTIVE : ConnectionStatuses.INITIALIZING,...params,},};diff --git a/ts/packages/core/test/AuthConfigs/AuthScheme.test.ts b/ts/packages/core/test/AuthConfigs/AuthScheme.test.tsindex b75e5ae75..573f090d7 100644--- a/ts/packages/core/test/AuthConfigs/AuthScheme.test.ts+++ b/ts/packages/core/test/AuthConfigs/AuthScheme.test.ts@@ -8,7 +8,7 @@ import {describe('AuthScheme', () => {describe('OAuth2', () => {- it('should create OAuth2 connection data with required fields', () => {+ it('should set ACTIVE status when access_token is provided', () => {const params = {access_token: 'test_token',token_type: 'Bearer',@@ -19,7 +19,7 @@ describe('AuthScheme', () => {expect(result).toEqual({authScheme: AuthSchemeTypes.OAUTH2,val: {- status: ConnectionStatuses.INITIALIZING,+ status: ConnectionStatuses.ACTIVE,access_token: 'test_token',token_type: 'Bearer',},@@ -29,7 +29,7 @@ describe('AuthScheme', () => {expect(() => ConnectionDataSchema.parse(result)).not.toThrow();});- it('should create OAuth2 connection data with all optional fields', () => {+ it('should set ACTIVE status with all optional fields when access_token is provided', () => {const params = {access_token: 'test_token',token_type: 'Bearer',@@ -49,7 +49,7 @@ describe('AuthScheme', () => {expect(result).toEqual({authScheme: AuthSchemeTypes.OAUTH2,val: {- status: ConnectionStatuses.INITIALIZING,+ status: ConnectionStatuses.ACTIVE,...params,},});@@ -57,10 +57,46 @@ describe('AuthScheme', () => {// Verify Zod schema validationexpect(() => ConnectionDataSchema.parse(result)).not.toThrow();});++ it('should set INITIALIZING status when no access_token is provided', () => {+ const result = AuthScheme.OAuth2({});++ expect(result).toEqual({+ authScheme: AuthSchemeTypes.OAUTH2,+ val: {+ status: ConnectionStatuses.INITIALIZING,+ },+ });++ expect(() => ConnectionDataSchema.parse(result)).not.toThrow();+ });++ it('should set INITIALIZING status when access_token is empty string', () => {+ const result = AuthScheme.OAuth2({ access_token: '' });++ expect(result).toEqual({+ authScheme: AuthSchemeTypes.OAUTH2,+ val: {+ status: ConnectionStatuses.INITIALIZING,+ access_token: '',+ },+ });++ expect(() => ConnectionDataSchema.parse(result)).not.toThrow();+ });++ it('should honor explicit status override from user', () => {+ const result = AuthScheme.OAuth2({+ access_token: 'test_token',+ status: ConnectionStatuses.INITIALIZING,+ });++ expect(result.val.status).toBe(ConnectionStatuses.INITIALIZING);+ });});describe('OAuth1', () => {- it('should create OAuth1 connection data with required fields', () => {+ it('should set INITIALIZING status when only oauth_token is provided (no secret)', () => {const params = {oauth_token: 'test_token',};@@ -79,7 +115,7 @@ describe('AuthScheme', () => {expect(() => ConnectionDataSchema.parse(result)).not.toThrow();});- it('should create OAuth1 connection data with all optional fields', () => {+ it('should set INITIALIZING status with optional fields but no oauth_token_secret', () => {const params = {oauth_token: 'test_token',consumer_key: 'consumer_key',@@ -100,6 +136,35 @@ describe('AuthScheme', () => {// Verify Zod schema validationexpect(() => ConnectionDataSchema.parse(result)).not.toThrow();});++ it('should set ACTIVE status when both oauth_token and oauth_token_secret are provided', () => {+ const params = {+ oauth_token: 'test_token',+ oauth_token_secret: 'test_secret',+ };++ const result = AuthScheme.OAuth1(params);++ expect(result).toEqual({+ authScheme: AuthSchemeTypes.OAUTH1,+ val: {+ status: ConnectionStatuses.ACTIVE,+ oauth_token: 'test_token',+ oauth_token_secret: 'test_secret',+ },+ });++ expect(() => ConnectionDataSchema.parse(result)).not.toThrow();+ });++ it('should set INITIALIZING status when oauth_token is empty', () => {+ const result = AuthScheme.OAuth1({+ oauth_token: '',+ oauth_token_secret: 'test_secret',+ });++ expect(result.val.status).toBe(ConnectionStatuses.INITIALIZING);+ });});describe('APIKey', () => {diff --git a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.tsindex d05e30f4c..c7f5110e2 100644--- a/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts+++ b/ts/packages/core/test/connectedAccounts/connectedAccounts.test.ts@@ -355,13 +355,12 @@ describe('ConnectedAccounts', () => {expect(typeof connectionRequest.waitForConnection).toBe('function');});- it('should create a new connected account with config and return a ConnectionRequest', async () => {+ it('should create a connected account with OAuth2 token import and return ACTIVE ConnectionRequest', async () => {const userId = 'user_123';const authConfigId = 'auth_config_123';const options = {callbackUrl: 'https://example.com/callback',config: AuthScheme.OAuth2({- status: ConnectionStatuses.ACTIVE,access_token: 'test_token',token_type: 'Bearer',}),@@ -374,12 +373,12 @@ describe('ConnectedAccounts', () => {total_pages: 1,});+ // When tokens are imported, the API should return ACTIVE with no redirectUrlconst mockResponse = {id: 'conn_123',connectionData: {val: {- status: ConnectionStatuses.INITIALIZING,- redirectUrl: 'https://auth.example.com/connect',+ status: ConnectionStatuses.ACTIVE,},},};@@ -400,9 +399,39 @@ describe('ConnectedAccounts', () => {});expect(connectionRequest).toHaveProperty('id', 'conn_123');- expect(connectionRequest).toHaveProperty('waitForConnection');+ expect(connectionRequest).toHaveProperty('status', ConnectionStatuses.ACTIVE);+ expect(connectionRequest).toHaveProperty('redirectUrl', null);expect(typeof connectionRequest.waitForConnection).toBe('function');});++ it('should return INITIATED status with redirectUrl when no tokens are provided', async () => {+ const userId = 'user_123';+ const authConfigId = 'auth_config_123';++ extendedMockClient.connectedAccounts.list.mockResolvedValueOnce({+ items: [],+ next_cursor: null,+ total_pages: 1,+ });++ const mockResponse = {+ id: 'conn_456',+ connectionData: {+ val: {+ status: ConnectionStatuses.INITIATED,+ redirectUrl: 'https://auth.example.com/connect',+ },+ },+ };++ extendedMockClient.connectedAccounts.create.mockResolvedValueOnce(mockResponse);++ const connectionRequest = await connectedAccounts.initiate(userId, authConfigId);++ expect(connectionRequest).toHaveProperty('id', 'conn_456');+ expect(connectionRequest).toHaveProperty('status', ConnectionStatuses.INITIATED);+ expect(connectionRequest).toHaveProperty('redirectUrl', 'https://auth.example.com/connect');+ });});describe('get', () => {