@heroku/mcp-server 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE.txt +206 -0
  2. package/README.md +279 -0
  3. package/dist/index.js +86 -0
  4. package/dist/repl/heroku-cli-repl.js +210 -0
  5. package/dist/repl/heroku-cli-repl.spec.js +106 -0
  6. package/dist/services/app-service.js +42 -0
  7. package/dist/services/app-setup-service.js +72 -0
  8. package/dist/services/build-service.js +149 -0
  9. package/dist/services/source-service.js +42 -0
  10. package/dist/tools/addons.js +241 -0
  11. package/dist/tools/addons.spec.js +335 -0
  12. package/dist/tools/apps.js +222 -0
  13. package/dist/tools/apps.spec.js +332 -0
  14. package/dist/tools/data.js +345 -0
  15. package/dist/tools/data.spec.js +300 -0
  16. package/dist/tools/deploy-to-heroku.js +449 -0
  17. package/dist/tools/deploy-to-heroku.spec.js +166 -0
  18. package/dist/tools/logs.js +61 -0
  19. package/dist/tools/logs.spec.js +112 -0
  20. package/dist/tools/maintenance.js +55 -0
  21. package/dist/tools/maintenance.spec.js +115 -0
  22. package/dist/tools/pipelines.js +146 -0
  23. package/dist/tools/pipelines.spec.js +183 -0
  24. package/dist/tools/ps.js +99 -0
  25. package/dist/tools/ps.spec.js +127 -0
  26. package/dist/tools/spaces.js +34 -0
  27. package/dist/tools/spaces.spec.js +71 -0
  28. package/dist/tools/teams.js +37 -0
  29. package/dist/tools/teams.spec.js +69 -0
  30. package/dist/utils/app-json.schema.json +232 -0
  31. package/dist/utils/command-builder.js +61 -0
  32. package/dist/utils/command-builder.spec.js +95 -0
  33. package/dist/utils/generate-request-init.js +18 -0
  34. package/dist/utils/handle-cli-output.js +26 -0
  35. package/dist/utils/handle-cli-output.spec.js +54 -0
  36. package/dist/utils/mcp-tool-response.js +1 -0
  37. package/dist/utils/read-app-json.js +39 -0
  38. package/dist/utils/read-app-json.spec.js +106 -0
  39. package/dist/utils/tarball.js +114 -0
  40. package/dist/utils/tarball.spec.js +98 -0
  41. package/dist/utils/tool-commands.js +47 -0
  42. package/package.json +85 -0
@@ -0,0 +1,449 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { ValidatorResult } from 'jsonschema';
3
+ import { z } from 'zod';
4
+ import { readAppJson } from '../utils/read-app-json.js';
5
+ import AppService from '../services/app-service.js';
6
+ import SourceService from '../services/source-service.js';
7
+ import AppSetupService from '../services/app-setup-service.js';
8
+ import BuildService from '../services/build-service.js';
9
+ import { generateRequestInit } from '../utils/generate-request-init.js';
10
+ import { packSources } from '../utils/tarball.js';
11
+ const appJsonSchema = await import('../utils/app-json.schema.json', { with: { type: 'json' } });
12
+ /**
13
+ * Schema for validating Heroku deployment parameters.
14
+ * This schema enforces the structure and types of deployment options
15
+ * including required fields and optional configurations.
16
+ */
17
+ export const deployToHerokuSchema = z
18
+ .object({
19
+ name: z
20
+ .string()
21
+ .min(5)
22
+ .max(30)
23
+ .describe('Heroku application name for deployment target. If omitted, a new app will be created with a random name. If supplied and the app does not exist, the tool will create a new app with the given name.'),
24
+ rootUri: z
25
+ .string()
26
+ .min(1)
27
+ .describe("The absolute path of the user's workspace unless otherwise specified by the user. Must be a string that can be resolved to a valid directory using node's path module."),
28
+ tarballUri: z
29
+ .string()
30
+ .optional()
31
+ .describe('The URL of the tarball to deploy. If not provided, the rootUri must be provided and the tool will create a new tarball from the contents of the rootUri.'),
32
+ teamId: z
33
+ .string()
34
+ .optional()
35
+ .describe('Heroku team identifier for team-scoped deployments. Use teams_list tool to get a list of teams if needed.'),
36
+ spaceId: z
37
+ .string()
38
+ .optional()
39
+ .describe('Heroku private space identifier for space-scoped deployments. Use spaces_list tool to get a list of spaces if needed.'),
40
+ internalRouting: z
41
+ .boolean()
42
+ .optional()
43
+ .describe('Enables internal routing within private spaces. Use this flag when you need to configure private spaces for internal routing.'),
44
+ env: z
45
+ .record(z.string(), z.any())
46
+ .optional()
47
+ .describe('Key-value pairs of environment variables for the deployment that override the ones in app.json'),
48
+ appJson: z.string().optional()
49
+ .describe(`Stringified app.json configuration for deployment. Used for dynamic configurations or converted projects.
50
+ The app.json string must be valid and conform to the following schema: ${JSON.stringify(appJsonSchema, null, 0)}`)
51
+ })
52
+ .strict();
53
+ /**
54
+ * Registers the deploy_to_heroku tool with the MCP server.
55
+ * This tool handles deployment of applications to Heroku using app.json configuration.
56
+ * It supports team and private space deployments, environment variable configuration,
57
+ * and custom app.json specifications.
58
+ *
59
+ * @param server - The MCP server instance to register the tool with
60
+ */
61
+ export const registerDeployToHerokuTool = (server) => {
62
+ server.tool('deploy_to_heroku', 'Deploy projects to Heroku, replaces manual git push workflows. Use this tool when you need to: ' +
63
+ '1) Deploy a new application with specific app.json configuration, 2) Update an existing application with new code, ' +
64
+ '3) Configure team or private space deployments, or 4) Set up environment-specific configurations. ' +
65
+ 'The tool handles app creation, source code deployment, and environment setup. ' +
66
+ 'Requires valid app.json in workspace or provided via configuration. ' +
67
+ 'Supports team deployments, private spaces, and custom environment variables.' +
68
+ 'Use apps_list tool with the "all" param to get a list of apps for the user to choose from when deploying to an existing app and the app name was not provided.', deployToHerokuSchema.shape, async (options) => {
69
+ const deployToHeroku = new DeployToHeroku();
70
+ const result = await deployToHeroku.run({
71
+ rootUri: options.rootUri,
72
+ tarballUri: options.tarballUri,
73
+ name: options.name,
74
+ teamId: options.teamId,
75
+ spaceId: options.spaceId,
76
+ internalRouting: options.internalRouting,
77
+ env: options.env,
78
+ appJson: options.appJson ? new TextEncoder().encode(options.appJson) : undefined
79
+ });
80
+ if (result?.errorMessage) {
81
+ return {
82
+ success: false,
83
+ message: result.errorMessage,
84
+ content: [{ type: 'text', text: result.errorMessage }]
85
+ };
86
+ }
87
+ const successMessage = `Successfully deployed to ${result?.name ?? 'Heroku'}`;
88
+ return {
89
+ success: true,
90
+ message: successMessage,
91
+ content: [{ type: 'text', text: successMessage }],
92
+ data: result
93
+ };
94
+ });
95
+ };
96
+ /**
97
+ * The DeploymentError class is used when
98
+ * an error occurs during the deployment of
99
+ * an app.
100
+ */
101
+ class DeploymentError extends Error {
102
+ appId;
103
+ /**
104
+ * Constructs a new DeploymentError
105
+ *
106
+ * @param message The message related to the error
107
+ * @param appId The app ID if available
108
+ */
109
+ constructor(message, appId) {
110
+ super(message);
111
+ this.appId = appId;
112
+ }
113
+ }
114
+ /**
115
+ * Handles deployment of VSCode workspace projects to Heroku.
116
+ *
117
+ * This command-based class manages the entire deployment workflow including:
118
+ * - Authentication with Heroku
119
+ * - Validation of project configuration (app.json)
120
+ * - Application creation and deployment via Heroku's AppSetup API
121
+ * - Git remote configuration for the new Heroku app
122
+ *
123
+ * The deployment process uses Heroku's source blob URL approach, which requires
124
+ * a publicly accessible tarball of the repository. Local uncommitted changes
125
+ * will be included in the deployment unless a blobUri is specified.
126
+ *
127
+ * Usage:
128
+ * ```typescript
129
+ * await vscode.commands.executeCommand(DeployToHeroku.COMMAND_ID);
130
+ * ```
131
+ *
132
+ * appSetupService - Service for Heroku app setup operations
133
+ * appService - Service for Heroku app management
134
+ *
135
+ * @see {@link HerokuCommand}
136
+ * @see {@link AppSetupService}
137
+ * @see {@link AppService}
138
+ */
139
+ export class DeployToHeroku extends AbortController {
140
+ appService = new AppService('https://api.heroku.com');
141
+ sourcesService = new SourceService('https://api.heroku.com');
142
+ appSetupService = new AppSetupService('https://api.heroku.com');
143
+ buildService = new BuildService('https://api.heroku.com');
144
+ requestInit;
145
+ isExistingDeployment = false;
146
+ deploymentOptions;
147
+ /**
148
+ * Deploys the current workspace to Heroku by means
149
+ * of the AppSetup apis.
150
+ *
151
+ * This function orchestrates the following steps:
152
+ * 1. Determines if the app.json configuration file exists and is valid
153
+ * 2. Determines if the the Procfile exists
154
+ * 2. Creates and deploys a new Heroku application
155
+ *
156
+ * The deployment process is displayed in a progress notification that can be cancelled
157
+ * by the user. Upon successful deployment, the new app is added to the git
158
+ * remote and the user is notified with options to view the app in the explorer
159
+ *
160
+ * Note that the AppSetupService requires a URL to download a tarball. If
161
+ * the blobUri argument is provided (such as the git repo's archive link) and the
162
+ * local branch has uncommitted changes, those changes will not be reflected
163
+ * in the deployment (obviously).
164
+ *
165
+ * Requirements:
166
+ * - Valid app.json file in the workspace root
167
+ * - Profile must exist in the workspace root
168
+ * - Valid Heroku authentication token
169
+ *
170
+ * @param deploymentOptions details used for the deployment
171
+ *
172
+ * @throws {Error} If authentication fails or required files are missing
173
+ * @throws {Error} If the app.json validation fails
174
+ * @throws {Error} If the deployment to Heroku fails
175
+ * @see runOperation
176
+ * @see deployToHeroku
177
+ *
178
+ * @returns A promise that resolves when the deployment is complete or rejects if an error occurs during deployment
179
+ */
180
+ async run(deploymentOptions = {}) {
181
+ this.deploymentOptions = deploymentOptions;
182
+ this.requestInit = await generateRequestInit(this.signal);
183
+ try {
184
+ const app = deploymentOptions.name
185
+ ? await this.appService.info(deploymentOptions.name, this.requestInit)
186
+ : undefined;
187
+ this.isExistingDeployment = Boolean(app);
188
+ }
189
+ catch {
190
+ // no-op
191
+ }
192
+ // rejecting means something went wrong.
193
+ let result = null;
194
+ try {
195
+ result = await this.runOperation();
196
+ if (!result) {
197
+ this.abort();
198
+ const abortMessage = 'Deployment cancelled';
199
+ throw new DeploymentError(abortMessage);
200
+ }
201
+ }
202
+ catch (error) {
203
+ const message = error.message;
204
+ return { errorMessage: message };
205
+ }
206
+ return result;
207
+ }
208
+ /**
209
+ * Orchestrates the deployment tasks and handles cancellations.
210
+ * This function wraps the deployment process into a Promise
211
+ * and returns it. The Promise returned from this function
212
+ * is expected to be awaited on in a try...catch.
213
+ *
214
+ * It performs the following tasks:
215
+ * 1. Validates the app.json configuration file
216
+ * 2. Validates the Procfile
217
+ * 3. Creates and deploys a new Heroku application
218
+ * 4. Adds the new Heroku app to the git remote
219
+ * 5. Displays a notification with options to view the app in the explorer
220
+ *
221
+ * @returns The deployment process wrapped in a promise
222
+ */
223
+ runOperation = async () => {
224
+ const { tarballUri } = this.deploymentOptions;
225
+ // app.json is required on an initial deployment using this flow
226
+ if (!tarballUri && !this.isExistingDeployment) {
227
+ await this.validateAppJson();
228
+ }
229
+ // We're good to deploy
230
+ return this.deployToHeroku();
231
+ };
232
+ /**
233
+ * Builds and sends the payload to Heroku for setting
234
+ * up a new app. If a tarballUri is provided, it will be used
235
+ * as the source_blob url. Otherwise, the AppSetup service will
236
+ * create a new tarball and upload it to the source_blob url created
237
+ * by the SourceService.
238
+ *
239
+ * - If the target argument is provided and this is an App object,
240
+ * a new build is created and deployed to the app.
241
+ * - If the target argument is not an App object and existing apps are found
242
+ * in the workspace, a dialog is presented to ask the user
243
+ * where to deploy.
244
+ * - If the target argument is not an App object and no existing
245
+ * apps are found in the workspace, a new app is created and deployed.
246
+ *
247
+ * @returns an AppSetup object with the details of the newly setup app
248
+ * @throws {DeploymentError} If the deployment fails
249
+ */
250
+ async deployToHeroku() {
251
+ const { tarballUri, rootUri, appJson } = this.deploymentOptions;
252
+ let blobUrl = tarballUri?.toString();
253
+ // Create and use an amazon s3 bucket and
254
+ // then upload the newly created tarball
255
+ // from the local sources if no tarballUri was provided.
256
+ if (!blobUrl) {
257
+ const generatedAppJson = appJson ? [{ relativePath: './app.json', contents: appJson }] : [];
258
+ const tarball = await packSources(rootUri, generatedAppJson);
259
+ const { source_blob: sourceBlob } = await this.sourcesService.create(this.requestInit);
260
+ blobUrl = sourceBlob.get_url;
261
+ const response = await fetch(sourceBlob.put_url, {
262
+ method: 'PUT',
263
+ body: tarball
264
+ });
265
+ if (!response.ok) {
266
+ const uploadErrorMessage = `Error uploading tarball to S3 bucket. The server responded with: ${response.status} - ${response.statusText}`;
267
+ throw new Error(uploadErrorMessage);
268
+ }
269
+ }
270
+ // The user has right-clicked on a
271
+ // Procfile or app.json or has used
272
+ // the deploy to heroku decorator button
273
+ // and we have apps in the remote. Ask
274
+ // the user where to deploy.
275
+ const result = this.isExistingDeployment
276
+ ? await this.createNewBuildForExistingApp(blobUrl, this.deploymentOptions.name ?? '')
277
+ : await this.setupNewApp(blobUrl);
278
+ // This is a new app setup and needs a git remote
279
+ // added to the workspace.
280
+ if (!this.isExistingDeployment && result) {
281
+ // Add the new remote to the workspace
282
+ const app = await this.appService.info(result.name, this.requestInit);
283
+ try {
284
+ execSync(`git remote add heroku-${result.name} ${app.git_url}`, { cwd: rootUri });
285
+ }
286
+ catch {
287
+ // Ignore
288
+ }
289
+ }
290
+ return result;
291
+ }
292
+ /**
293
+ * Reads and validates the app.json. If it is invalid,
294
+ * the errors are logged and the user is informed that
295
+ * the app will not be deployed and the action is aborted.
296
+ *
297
+ * @returns The app.json as an object or undefined if it is invalid
298
+ * @throws {Error} If the app.json is invalid or cannot be read
299
+ */
300
+ async validateAppJson() {
301
+ const { appJson, rootUri } = this.deploymentOptions;
302
+ const readAppJsonResult = await readAppJson(rootUri, appJson ? Buffer.from(appJson) : undefined);
303
+ if (readAppJsonResult instanceof ValidatorResult) {
304
+ let message = 'invalid app.json\nThe following errors were found in app.json:\n--------------------------------\n';
305
+ readAppJsonResult.errors.forEach((error) => {
306
+ message += error.stack + '\n';
307
+ });
308
+ message += '--------------------------------';
309
+ throw new Error(message);
310
+ }
311
+ return readAppJsonResult;
312
+ }
313
+ /**
314
+ * Creates a new build for the given appIdentity.
315
+ * This function is used when creating a new build
316
+ * for an existing app.
317
+ *
318
+ * @param blobUrl The url of the blob to sent to the app setup service
319
+ * @param appName The name of the app to create the build for
320
+ * @returns Build object with the details of the newly created build
321
+ * @throws {DeploymentError} If the deployment fails
322
+ */
323
+ async createNewBuildForExistingApp(blobUrl, appName) {
324
+ const payload = {
325
+ // eslint-disable-next-line camelcase
326
+ source_blob: {
327
+ url: blobUrl,
328
+ checksum: null,
329
+ version: null,
330
+ // eslint-disable-next-line camelcase
331
+ version_description: null
332
+ }
333
+ };
334
+ try {
335
+ const result = await this.buildService.create(appName, payload, this.requestInit);
336
+ let buildOutput = '';
337
+ if (result.output_stream_url) {
338
+ buildOutput = await this.captureBuildOutput(result.output_stream_url);
339
+ }
340
+ const info = await this.buildService.info(appName, result.id, this.requestInit);
341
+ if (info.status === 'failed') {
342
+ throw new DeploymentError(`The request was sent to Heroku successfully but there was a problem with deployment: ${info.status} - ${buildOutput}`, appName);
343
+ }
344
+ return { ...info, name: appName };
345
+ }
346
+ catch (error) {
347
+ throw new DeploymentError(error.message);
348
+ }
349
+ }
350
+ /**
351
+ * Sets up a new app using the AppSetup service and the
352
+ * supplied blobUrl.
353
+ *
354
+ * @param blobUrl The url of the blob to sent to the app setup service
355
+ * @returns Build object with the details of the newly setup app
356
+ * @throws {DeploymentError} If the deployment fails
357
+ */
358
+ async setupNewApp(blobUrl) {
359
+ const { name, spaceId, teamId, env, internalRouting } = this.deploymentOptions;
360
+ const payload = {
361
+ // eslint-disable-next-line camelcase
362
+ source_blob: { url: blobUrl },
363
+ overrides: { env },
364
+ app: {
365
+ name: name ?? undefined,
366
+ organization: teamId ?? undefined,
367
+ space: spaceId ?? undefined
368
+ }
369
+ };
370
+ Reflect.set(payload.app, 'internal_routing', !!internalRouting);
371
+ try {
372
+ const result = await this.appSetupService.create(payload, this.requestInit);
373
+ const info = await this.waitForAppSetup(result);
374
+ return {
375
+ ...info.build,
376
+ name: result.app.name,
377
+ postDeployOutput: info.postdeploy?.output,
378
+ buildOutput: info.build?.output
379
+ };
380
+ }
381
+ catch (error) {
382
+ throw new DeploymentError(error.message);
383
+ }
384
+ }
385
+ /**
386
+ * Waits for the app setup to complete.
387
+ *
388
+ * @param result The app setup result
389
+ * @returns The app setup result
390
+ * @throws {DeploymentError} If the deployment fails
391
+ */
392
+ async waitForAppSetup(result) {
393
+ let info;
394
+ let retriesOnError = 3;
395
+ while (retriesOnError > 0) {
396
+ try {
397
+ info = await this.appSetupService.info(result.id, this.requestInit);
398
+ if (info?.build?.output_stream_url ?? info?.status === 'failed') {
399
+ break;
400
+ }
401
+ }
402
+ catch {
403
+ retriesOnError--;
404
+ }
405
+ await new Promise((resolve) => setTimeout(resolve, 2000));
406
+ }
407
+ if (!info) {
408
+ throw new DeploymentError('The request was sent to Heroku successfully but there was a problem with deployment');
409
+ }
410
+ if (info?.build?.output_stream_url) {
411
+ const buildOutput = await this.captureBuildOutput(info.build.output_stream_url);
412
+ info.build.output = buildOutput;
413
+ }
414
+ while (info.status === 'pending') {
415
+ await new Promise((resolve) => setTimeout(resolve, 2000));
416
+ info = await this.appSetupService.info(result.id, this.requestInit);
417
+ }
418
+ if (info.failure_message) {
419
+ let errorMessage = `Error: deployment failed with "${info.failure_message}"\n`;
420
+ if (info.manifest_errors?.length) {
421
+ errorMessage += '-----------------------\n';
422
+ info.manifest_errors.forEach((error) => (errorMessage += error + '\n'));
423
+ errorMessage += '-----------------------\n';
424
+ }
425
+ throw new DeploymentError(`The request was sent to Heroku successfully but there was a problem with deployment:\n${errorMessage}`, result.app?.id);
426
+ }
427
+ return info;
428
+ }
429
+ /**
430
+ * Streams the build output to the console.
431
+ *
432
+ * @param streamUrl the URL of the stream
433
+ * @returns The build output
434
+ */
435
+ async captureBuildOutput(streamUrl) {
436
+ let output = '';
437
+ const stream = await fetch(streamUrl);
438
+ const reader = stream.body?.getReader();
439
+ while (!this.signal.aborted) {
440
+ const { done, value } = await reader.read();
441
+ if (done)
442
+ break;
443
+ if (value.length > 1) {
444
+ output += Buffer.from(value).toString();
445
+ }
446
+ }
447
+ return output;
448
+ }
449
+ }
@@ -0,0 +1,166 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { expect } from 'chai';
5
+ import { Readable } from 'node:stream';
6
+ import { DeployToHeroku } from './deploy-to-heroku.js';
7
+ import AppService from '../services/app-service.js';
8
+ import SourceService from '../services/source-service.js';
9
+ import AppSetupService from '../services/app-setup-service.js';
10
+ import BuildService from '../services/build-service.js';
11
+ import sinon from 'sinon';
12
+ describe('DeployToHeroku', () => {
13
+ // Increase timeout for async tests
14
+ const TEST_TIMEOUT = 30000;
15
+ before(function () {
16
+ this.timeout(TEST_TIMEOUT);
17
+ });
18
+ let tempDir;
19
+ let deployToHeroku;
20
+ let appServiceStub;
21
+ let sourceServiceStub;
22
+ let appSetupServiceStub;
23
+ let buildServiceStub;
24
+ let fetchStub;
25
+ beforeEach(async () => {
26
+ // Create a temporary directory for each test
27
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'deploy-test-'));
28
+ // Create stubs for services
29
+ appServiceStub = sinon.createStubInstance(AppService);
30
+ sourceServiceStub = sinon.createStubInstance(SourceService);
31
+ appSetupServiceStub = sinon.createStubInstance(AppSetupService);
32
+ buildServiceStub = sinon.createStubInstance(BuildService);
33
+ const readable = Readable.from((async function* () {
34
+ yield 'test log output';
35
+ })());
36
+ fetchStub = sinon.stub(globalThis, 'fetch');
37
+ fetchStub
38
+ .withArgs('https://test.com/put', {
39
+ method: 'PUT',
40
+ body: sinon.match.any
41
+ })
42
+ .resolves({ ok: true });
43
+ fetchStub.withArgs('https://test.com/stream').resolves(new Response(readable));
44
+ deployToHeroku = new DeployToHeroku();
45
+ // Replace service instances with stubs
46
+ Object.assign(deployToHeroku, {
47
+ appService: appServiceStub,
48
+ sourcesService: sourceServiceStub,
49
+ appSetupService: appSetupServiceStub,
50
+ buildService: buildServiceStub
51
+ });
52
+ });
53
+ afterEach(async () => {
54
+ // Clean up temporary directory after each test
55
+ await fs.rm(tempDir, { recursive: true, force: true });
56
+ sinon.restore();
57
+ });
58
+ async function createTempFile(relativePath, content) {
59
+ const filePath = path.join(tempDir, relativePath);
60
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
61
+ await fs.writeFile(filePath, content);
62
+ return filePath;
63
+ }
64
+ describe('run', () => {
65
+ it('should deploy to existing app when app exists', async function () {
66
+ this.timeout(TEST_TIMEOUT);
67
+ // Create test app.json
68
+ await createTempFile('app.json', JSON.stringify({
69
+ name: 'test-app',
70
+ description: 'Test app',
71
+ stack: 'heroku-22'
72
+ }));
73
+ const mockApp = { id: 'test-id', name: 'test-app', git_url: 'https://git.heroku.com/test-app.git' };
74
+ const mockBuild = {
75
+ id: 'build-id',
76
+ status: 'succeeded',
77
+ output_stream_url: 'https://test.com/stream',
78
+ name: 'test-app'
79
+ };
80
+ appServiceStub.info.resolves(mockApp);
81
+ sourceServiceStub.create.resolves({
82
+ source_blob: {
83
+ get_url: 'https://test.com/get',
84
+ put_url: 'https://test.com/put'
85
+ }
86
+ });
87
+ buildServiceStub.create.resolves(mockBuild);
88
+ buildServiceStub.info.resolves({ ...mockBuild, status: 'succeeded' });
89
+ const options = {
90
+ name: 'test-app',
91
+ rootUri: tempDir
92
+ };
93
+ const result = await deployToHeroku.run(options);
94
+ expect(result).to.not.be.null;
95
+ expect(result).to.have.property('name', 'test-app');
96
+ expect(result).to.have.property('status', 'succeeded');
97
+ expect(appServiceStub.info.calledOnce).to.be.true;
98
+ expect(buildServiceStub.create.calledOnce).to.be.true;
99
+ });
100
+ it('should handle invalid app.json', async function () {
101
+ this.timeout(TEST_TIMEOUT);
102
+ // Create invalid app.json
103
+ await createTempFile('app.json', 'invalid json');
104
+ const options = {
105
+ name: 'test-app',
106
+ rootUri: tempDir
107
+ };
108
+ const result = await deployToHeroku.run(options);
109
+ expect(result).to.not.be.null;
110
+ expect(result).to.have.property('errorMessage');
111
+ expect(result.errorMessage).to.include('Cannot parse');
112
+ });
113
+ it('should handle deployment errors', async function () {
114
+ this.timeout(TEST_TIMEOUT);
115
+ await createTempFile('app.json', JSON.stringify({
116
+ name: 'test-app',
117
+ description: 'Test app',
118
+ stack: 'heroku-22'
119
+ }));
120
+ appServiceStub.info.rejects(new Error('App not found'));
121
+ sourceServiceStub.create.rejects(new Error('Source creation failed'));
122
+ const options = {
123
+ name: 'test-app',
124
+ rootUri: tempDir
125
+ };
126
+ const result = await deployToHeroku.run(options);
127
+ expect(result).to.not.be.null;
128
+ expect(result).to.have.property('errorMessage').that.includes('Source creation failed');
129
+ });
130
+ it('should handle app setup failure', async function () {
131
+ this.timeout(TEST_TIMEOUT);
132
+ await createTempFile('app.json', JSON.stringify({
133
+ name: 'test-app',
134
+ description: 'Test app',
135
+ stack: 'heroku-22'
136
+ }));
137
+ const mockAppSetup = {
138
+ id: 'setup-id',
139
+ status: 'failed',
140
+ failure_message: 'Setup failed',
141
+ manifest_errors: ['Error 1', 'Error 2'],
142
+ app: { name: 'test-app', id: 'app-id' }
143
+ };
144
+ appServiceStub.info.rejects(new Error('App not found'));
145
+ sourceServiceStub.create.resolves({
146
+ source_blob: {
147
+ get_url: 'https://test.com/get',
148
+ put_url: 'https://test.com/put'
149
+ }
150
+ });
151
+ appSetupServiceStub.create.resolves(mockAppSetup);
152
+ appSetupServiceStub.info.resolves(mockAppSetup);
153
+ const options = {
154
+ name: 'test-app',
155
+ rootUri: tempDir
156
+ };
157
+ const result = await deployToHeroku.run(options);
158
+ expect(result).to.not.be.null;
159
+ if (result) {
160
+ expect(result.errorMessage).to.include('Setup failed');
161
+ expect(result.errorMessage).to.include('Error 1');
162
+ expect(result.errorMessage).to.include('Error 2');
163
+ }
164
+ });
165
+ });
166
+ });
@@ -0,0 +1,61 @@
1
+ import { z } from 'zod';
2
+ import { handleCliOutput } from '../utils/handle-cli-output.js';
3
+ import { CommandBuilder } from '../utils/command-builder.js';
4
+ import { TOOL_COMMAND_MAP } from '../utils/tool-commands.js';
5
+ /**
6
+ * Schema for retrieving application logs with various filtering and output options.
7
+ * This schema defines the structure and validation rules for the logs operation.
8
+ */
9
+ export const getAppGetAppLogsOptionsSchema = z.object({
10
+ app: z
11
+ .string()
12
+ .describe('Specifies the target Heroku app whose logs to retrieve. Requirements and behaviors: ' +
13
+ '1) App must exist and be accessible to you with appropriate permissions, ' +
14
+ '2) The response includes both system events and application output, ' +
15
+ "3) Currently it's only available to Cedar generation apps."),
16
+ dynoName: z
17
+ .string()
18
+ .optional()
19
+ .describe('Filter logs by specific dyno instance. Important behaviors: ' +
20
+ '1) Format is "process_type.instance_number" (e.g., "web.1", "worker.2"). ' +
21
+ '2) You cannot specify both dynoName and processType parameters together. ' +
22
+ 'Best practice: Use when debugging specific dyno behavior or performance issues.'),
23
+ source: z
24
+ .string()
25
+ .optional()
26
+ .describe('Filter logs by their origin. Key characteristics: ' +
27
+ '1) Common values: "app" (application logs), "heroku" (platform events), ' +
28
+ '2) When omitted, shows logs from all sources. ' +
29
+ 'Best practice: Use "app" for application debugging, "heroku" for platform troubleshooting.'),
30
+ processType: z
31
+ .string()
32
+ .optional()
33
+ .describe('Filter logs by process type. Key characteristics: ' +
34
+ '1) Common values: "web" (web dynos), "worker" (background workers), ' +
35
+ '2) Shows logs from all instances of the specified process type, ' +
36
+ '3) You cannot specify both dynoName and processType parameters together. ' +
37
+ 'Best practice: Use when debugging issues specific to web or worker processes.')
38
+ });
39
+ /**
40
+ * Registers the get app logs tool with the MCP server.
41
+ * This tool provides access to application logs with various filtering options.
42
+ *
43
+ * @param server - The MCP server instance to register the tool with
44
+ * @param herokuRepl - The Heroku REPL instance for executing commands
45
+ */
46
+ export const registerGetAppLogsTool = (server, herokuRepl) => {
47
+ server.tool('get_app_logs', 'View application logs with flexible filtering options. Use this tool when you need to: ' +
48
+ '1) Monitor application activity in real-time, 2) Debug issues by viewing recent logs, ' +
49
+ '3) Filter logs by dyno, process type, or source.', getAppGetAppLogsOptionsSchema.shape, async (options) => {
50
+ const command = new CommandBuilder(TOOL_COMMAND_MAP.LOGS)
51
+ .addFlags({
52
+ app: options.app,
53
+ 'dyno-name': options.dynoName,
54
+ source: options.source,
55
+ 'process-type': options.processType
56
+ })
57
+ .build();
58
+ const output = await herokuRepl.executeCommand(command);
59
+ return handleCliOutput(output);
60
+ });
61
+ };