Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/server/mcp/__tests__/toolHandlers.operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
28 changes: 28 additions & 0 deletions src/server/mcp/tools/operations/__tests__/shared.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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'), {
Expand Down
2 changes: 1 addition & 1 deletion src/server/mcp/tools/operations/configureEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export function createConfigureEnvironmentToolDefinition(
},
};
} catch (error) {
throw mapEnvironmentOperationError(error, { validServices });
throw mapEnvironmentOperationError(error, { validServices, requestId: context.requestId });
}
},
};
Expand Down
1 change: 1 addition & 0 deletions src/server/mcp/tools/operations/createEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export function createCreateEnvironmentToolDefinition(
? await dependencies.listEnvironmentChoices(repository).catch(() => [])
: undefined;
throw mapEnvironmentOperationError(error, {
requestId: context.requestId,
...(ambiguousEnvironments ? { ambiguousEnvironments } : {}),
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/server/mcp/tools/operations/deployEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
},
};
Expand Down
2 changes: 1 addition & 1 deletion src/server/mcp/tools/operations/destroyEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export function createDestroyEnvironmentToolDefinition(
},
};
} catch (error) {
throw mapEnvironmentOperationError(error);
throw mapEnvironmentOperationError(error, { requestId: context.requestId });
}
},
};
Expand Down
2 changes: 1 addition & 1 deletion src/server/mcp/tools/operations/extendEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function createExtendEnvironmentToolDefinition(
...(extension.maxReached ? { next: EXTEND_MAX_NEXT } : {}),
};
} catch (error) {
throw mapEnvironmentOperationError(error);
throw mapEnvironmentOperationError(error, { requestId: context.requestId });
}
},
};
Expand Down
3 changes: 3 additions & 0 deletions src/server/mcp/tools/operations/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -298,6 +299,7 @@ export function mapEnvironmentOperationError(
options: {
validServices?: string[];
ambiguousEnvironments?: EnvironmentChoice[];
requestId?: string;
} = {}
): McpExecutionError {
if (error instanceof McpExecutionError) return error;
Expand All @@ -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.'
Expand Down
39 changes: 39 additions & 0 deletions src/server/models/__tests__/serverCompilation.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
1 change: 1 addition & 0 deletions tsconfig.server.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"isolatedModules": false,
"jsx": "preserve",
"lib": ["es2022", "dom"],
"useDefineForClassFields": false,
"strictNullChecks": false,
"baseUrl": "."
},
Expand Down
Loading