| 22 | } |
| 23 | |
| 24 | export async function getGatewaySessionToken( |
| 25 | runId: string, |
| 26 | organizationId: string | null, |
| 27 | connectedToolNodeIds?: string[], |
| 28 | ): Promise<string> { |
| 29 | const internalToken = process.env.INTERNAL_SERVICE_TOKEN; |
| 30 | |
| 31 | if (!internalToken) { |
| 32 | throw new ConfigurationError( |
| 33 | 'INTERNAL_SERVICE_TOKEN env var must be set for agent tool discovery', |
| 34 | { configKey: 'INTERNAL_SERVICE_TOKEN' }, |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | const url = `${DEFAULT_API_BASE_URL}/internal/mcp/generate-token`; |
| 39 | // If connectedToolNodeIds is empty or undefined, we might still want to generate a token |
| 40 | // without specific allowedNodeIds if the API supports it, or handle it otherwise. |
| 41 | // The original code passed `allowedNodeIds: connectedToolNodeIds`. |
| 42 | const body = { runId, organizationId, allowedNodeIds: connectedToolNodeIds }; |
| 43 | |
| 44 | const response = await fetch(url, { |
| 45 | method: 'POST', |
| 46 | headers: { |
| 47 | 'Content-Type': 'application/json', |
| 48 | 'X-Internal-Token': internalToken, |
| 49 | }, |
| 50 | body: JSON.stringify(body), |
| 51 | }); |
| 52 | |
| 53 | if (!response.ok) { |
| 54 | const errorText = await response.text(); |
| 55 | throw new Error(`Failed to generate gateway session token: ${errorText}`); |
| 56 | } |
| 57 | |
| 58 | const payload = await response.json(); |
| 59 | const token = isRecord(payload) && typeof payload.token === 'string' ? payload.token : null; |
| 60 | if (!token) { |
| 61 | throw new Error('Failed to generate gateway session token: invalid response shape'); |
| 62 | } |
| 63 | return token; |
| 64 | } |