From cc8542892aa7e07a8312e99c267dc7254855179c Mon Sep 17 00:00:00 2001 From: Vigneshraj Sekar Babu Date: Wed, 4 Nov 2026 09:14:19 -0800 Subject: [PATCH] fix(mcp): stop tsc class fields from wiping model instances in configure_environment The server build emits declared model properties as class fields, so an Objection instance patched via $query().patch() was overwritten with undefined values. Disable useDefineForClassFields for the server build and log unexpected errors in the environment operation error mapper. --- .../__tests__/toolHandlers.operations.test.ts | 17 ++++++++ .../tools/operations/__tests__/shared.test.ts | 28 +++++++++++++ .../tools/operations/configureEnvironment.ts | 2 +- .../mcp/tools/operations/createEnvironment.ts | 1 + .../mcp/tools/operations/deployEnvironment.ts | 2 +- .../tools/operations/destroyEnvironment.ts | 2 +- .../mcp/tools/operations/extendEnvironment.ts | 2 +- src/server/mcp/tools/operations/shared.ts | 3 ++ .../__tests__/serverCompilation.test.ts | 39 +++++++++++++++++++ tsconfig.server.json | 1 + 10 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 src/server/models/__tests__/serverCompilation.test.ts diff --git a/src/server/mcp/__tests__/toolHandlers.operations.test.ts b/src/server/mcp/__tests__/toolHandlers.operations.test.ts index 3fba91f1..da3ea3fa 100644 --- a/src/server/mcp/__tests__/toolHandlers.operations.test.ts +++ b/src/server/mcp/__tests__/toolHandlers.operations.test.ts @@ -327,6 +327,23 @@ describe('configure_environment', () => { expect((service.applyApiEnvironmentPatch as jest.Mock).mock.calls[0][3]).toEqual({ envMode: 'merge' }); }); + it('passes service active and branch changes through to the patch', async () => { + const build = environmentBuild(); + const service = operationService({ + applyApiEnvironmentPatch: jest.fn().mockResolvedValue({ mode: 'applied', changed: true, build }), + }); + const { call } = harness({ service, loadNamedEnvironment: async () => loadedEnvironment(build) }); + const patch: McpJsonObject = { + services: [ + { name: 'web', active: false }, + { name: 'api', branchOrExternalUrl: 'feature/x' }, + ], + }; + const { output } = await call('configure_environment', { uuid: UUID, environmentId: ENVIRONMENT_ID, patch }); + expect(output).toMatchObject({ applied: true, result: { mode: 'applied' } }); + expect((service.applyApiEnvironmentPatch as jest.Mock).mock.calls[0][2]).toEqual(patch); + }); + it('returns the queued deploy without prompting automatic monitoring', async () => { const build = environmentBuild(); const service = operationService({ diff --git a/src/server/mcp/tools/operations/__tests__/shared.test.ts b/src/server/mcp/tools/operations/__tests__/shared.test.ts index 50d770ae..4bae3454 100644 --- a/src/server/mcp/tools/operations/__tests__/shared.test.ts +++ b/src/server/mcp/tools/operations/__tests__/shared.test.ts @@ -15,6 +15,7 @@ */ import { AppError } from 'server/lib/appError'; +import { getLogger } from 'server/lib/logger'; import Build from 'server/models/Build'; import Deploy from 'server/models/Deploy'; import Environment from 'server/models/Environment'; @@ -42,6 +43,11 @@ import { validEnvironmentServiceNames, } from '../shared'; +jest.mock('server/lib/logger', () => ({ + ...jest.requireActual('server/lib/logger'), + getLogger: jest.fn(() => ({ error: jest.fn() })), +})); + describe('environment operation shared helpers', () => { afterEach(() => { jest.restoreAllMocks(); @@ -361,6 +367,28 @@ describe('mapEnvironmentOperationError', () => { expect(mapEnvironmentOperationError(appError('env_ambiguous'))).toMatchObject({ code: 'internal_error' }); }); + it('logs the original error with the request id before mapping it to internal_error', () => { + const errorLog = jest.fn(); + (getLogger as jest.Mock).mockReturnValue({ error: errorLog }); + const cause = new TypeError("Cannot read properties of undefined (reading 'x')"); + + const mapped = mapEnvironmentOperationError(cause, { requestId: 'req-1' }); + + expect(mapped).toMatchObject({ code: 'internal_error' }); + expect(JSON.stringify(mapped)).not.toContain('Cannot read properties'); + expect(errorLog).toHaveBeenCalledWith( + expect.objectContaining({ error: cause, requestId: 'req-1' }), + expect.stringContaining('unexpectedly') + ); + }); + + it('does not log expected operation errors', () => { + const errorLog = jest.fn(); + (getLogger as jest.Mock).mockReturnValue({ error: errorLog }); + mapEnvironmentOperationError(new ServiceOverrideNotFoundError('web'), { requestId: 'req-1' }); + expect(errorLog).not.toHaveBeenCalled(); + }); + it('maps service-not-found AppErrors with safe unique services', () => { expect( mapEnvironmentOperationError(appError('service_not_found'), { diff --git a/src/server/mcp/tools/operations/configureEnvironment.ts b/src/server/mcp/tools/operations/configureEnvironment.ts index 50a2fba8..018b8dc1 100644 --- a/src/server/mcp/tools/operations/configureEnvironment.ts +++ b/src/server/mcp/tools/operations/configureEnvironment.ts @@ -118,7 +118,7 @@ export function createConfigureEnvironmentToolDefinition( }, }; } catch (error) { - throw mapEnvironmentOperationError(error, { validServices }); + throw mapEnvironmentOperationError(error, { validServices, requestId: context.requestId }); } }, }; diff --git a/src/server/mcp/tools/operations/createEnvironment.ts b/src/server/mcp/tools/operations/createEnvironment.ts index 4eeeb149..1490cd4e 100644 --- a/src/server/mcp/tools/operations/createEnvironment.ts +++ b/src/server/mcp/tools/operations/createEnvironment.ts @@ -134,6 +134,7 @@ export function createCreateEnvironmentToolDefinition( ? await dependencies.listEnvironmentChoices(repository).catch(() => []) : undefined; throw mapEnvironmentOperationError(error, { + requestId: context.requestId, ...(ambiguousEnvironments ? { ambiguousEnvironments } : {}), }); } diff --git a/src/server/mcp/tools/operations/deployEnvironment.ts b/src/server/mcp/tools/operations/deployEnvironment.ts index 6368aff2..81c2a5a5 100644 --- a/src/server/mcp/tools/operations/deployEnvironment.ts +++ b/src/server/mcp/tools/operations/deployEnvironment.ts @@ -86,7 +86,7 @@ export function createDeployEnvironmentToolDefinition( next: `Deploy ${result.deployId} was queued and continues in the background. Report this receipt now. Use get_environment with uuid ${uuid} later when the user asks for current state. Do not call deploy_environment again for this run.${lifecycleUiNext}`, }; } catch (error) { - throw mapEnvironmentOperationError(error); + throw mapEnvironmentOperationError(error, { requestId: context.requestId }); } }, }; diff --git a/src/server/mcp/tools/operations/destroyEnvironment.ts b/src/server/mcp/tools/operations/destroyEnvironment.ts index 27fb7769..32418470 100644 --- a/src/server/mcp/tools/operations/destroyEnvironment.ts +++ b/src/server/mcp/tools/operations/destroyEnvironment.ts @@ -181,7 +181,7 @@ export function createDestroyEnvironmentToolDefinition( }, }; } catch (error) { - throw mapEnvironmentOperationError(error); + throw mapEnvironmentOperationError(error, { requestId: context.requestId }); } }, }; diff --git a/src/server/mcp/tools/operations/extendEnvironment.ts b/src/server/mcp/tools/operations/extendEnvironment.ts index 0f982d85..9bb9d3fb 100644 --- a/src/server/mcp/tools/operations/extendEnvironment.ts +++ b/src/server/mcp/tools/operations/extendEnvironment.ts @@ -70,7 +70,7 @@ export function createExtendEnvironmentToolDefinition( ...(extension.maxReached ? { next: EXTEND_MAX_NEXT } : {}), }; } catch (error) { - throw mapEnvironmentOperationError(error); + throw mapEnvironmentOperationError(error, { requestId: context.requestId }); } }, }; diff --git a/src/server/mcp/tools/operations/shared.ts b/src/server/mcp/tools/operations/shared.ts index e8f623ba..f0ff1640 100644 --- a/src/server/mcp/tools/operations/shared.ts +++ b/src/server/mcp/tools/operations/shared.ts @@ -16,6 +16,7 @@ import type { Transaction } from 'objection'; import { isAppError } from 'server/lib/appError'; +import { getLogger } from 'server/lib/logger'; import type { Principal } from 'server/lib/principal'; import Build from 'server/models/Build'; import Deploy from 'server/models/Deploy'; @@ -298,6 +299,7 @@ export function mapEnvironmentOperationError( options: { validServices?: string[]; ambiguousEnvironments?: EnvironmentChoice[]; + requestId?: string; } = {} ): McpExecutionError { if (error instanceof McpExecutionError) return error; @@ -320,6 +322,7 @@ export function mapEnvironmentOperationError( return invalidBodyFromError(error); } if (!isAppError(error)) { + getLogger().error({ error, requestId: options.requestId }, 'MCP: environment operation failed unexpectedly'); return new McpExecutionError( 'internal_error', 'Lifecycle could not complete this environment request. Ask an administrator for help.' diff --git a/src/server/models/__tests__/serverCompilation.test.ts b/src/server/models/__tests__/serverCompilation.test.ts new file mode 100644 index 00000000..fa8cd005 --- /dev/null +++ b/src/server/models/__tests__/serverCompilation.test.ts @@ -0,0 +1,39 @@ +/** + * Copyright 2026 GoodRx, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs'; +import path from 'path'; +import ts from 'typescript'; + +const ROOT = path.resolve(__dirname, '../../../..'); + +function serverCompilerOptions(): ts.CompilerOptions { + const configPath = path.join(ROOT, 'tsconfig.server.json'); + const raw = ts.readConfigFile(configPath, ts.sys.readFile); + return ts.parseJsonConfigFileContent(raw.config, ts.sys, ROOT, undefined, configPath).options; +} + +// ws-server (and the MCP tools it serves) runs from tsc output. Emitted class fields would +// overwrite every property of an Objection model instance that `$query().patch()` touches. +describe('server TypeScript compilation', () => { + it('does not emit declared model properties as class fields', () => { + const source = fs.readFileSync(path.join(ROOT, 'src/server/models/Deploy.ts'), 'utf8'); + const { outputText } = ts.transpileModule(source, { compilerOptions: serverCompilerOptions() }); + + expect(outputText).not.toMatch(/^\s*deployableId;$/m); + expect(outputText).not.toMatch(/^\s*status;$/m); + }); +}); diff --git a/tsconfig.server.json b/tsconfig.server.json index 136026b4..8b0eb809 100644 --- a/tsconfig.server.json +++ b/tsconfig.server.json @@ -7,6 +7,7 @@ "isolatedModules": false, "jsx": "preserve", "lib": ["es2022", "dom"], + "useDefineForClassFields": false, "strictNullChecks": false, "baseUrl": "." },