# Search Connector Flow

```mermaid
flowchart TD
    Start([Client Request]) --> Auth{Authenticate}
    Auth -->|Unauthorized| Error[Return 401]
    Auth -->|Authorized| Service[ConnectorService.execute]

    Service --> PrepareCredentials[Prepare GL Connectors Credentials]
    PrepareCredentials --> CredentialType{Custom gl_token?}
    CredentialType -->|Yes| UseCustom[Use gl_token + GLCHAT_GL_CONNECTORS_API_KEY]
    CredentialType -->|No| GetInternal[Get Internal GL Connectors Token]

    GetInternal --> EnsureCredentials[Ensure GL Connectors Credentials]
    EnsureCredentials --> CheckUser{GL Connectors User exists?}
    CheckUser -->|No| CreateUser[Create GL Connectors User]
    CreateUser --> StoreSecret[Store User Secret]
    CheckUser -->|Yes| CheckToken{Token valid?}
    StoreSecret --> CheckToken
    CheckToken -->|No| RefreshToken[Refresh GL Connectors Token]
    RefreshToken --> StoreToken[Store Updated Token]
    CheckToken -->|Yes| UseInternal[Use Internal Token + GL_CONNECTORS_API_KEY]
    StoreToken --> UseInternal
    UseCustom --> CheckIntegration
    UseInternal --> CheckIntegration

    CheckIntegration[Check Connector Integration] --> HasIntegration{Has Integration?}
    HasIntegration -->|No| ReturnOAuth[Return OAuth URL]
    ReturnOAuth --> IntegrationError[Set integration error]
    IntegrationError --> BuildResponse[Build ConnectorResponse]
    HasIntegration -->|Yes| ExecuteQuery[Execute AIP Agent Query]
    ExecuteQuery --> AIPAgent[AIPAgentService.run_aip_agent_query_mcp]
    AIPAgent --> GL ConnectorsQuery[Execute Query via GL Connectors]
    GL ConnectorsQuery --> ProcessResults[Process Results]
    ProcessResults --> CreateChunks[Create Chunks]
    CreateChunks --> BuildResponse
    BuildResponse --> Emit[Emit WebSocket Events<br/>if stream=true]
    Emit --> Response[Return ConnectorResponse]
    Response --> End([End])

    style Start fill:#e1f5ff
    style Service fill:#fff4e1
    style PrepareCredentials fill:#fff2cc
    style CheckIntegration fill:#fff2cc
    style AIPAgent fill:#f3e5f5
    style GL ConnectorsQuery fill:#fce4ec
    style ReturnOAuth fill:#fce4ec
    style IntegrationError fill:#fce4ec
    style BuildResponse fill:#ede7f6
    style Response fill:#e1f5ff
```
