@heroku/mcp-server 0.0.1 → 1.0.1

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.
package/README.md CHANGED
@@ -1,105 +1,126 @@
1
1
  # heroku-mcp-server
2
2
 
3
+ > The Heroku Platform MCP Server works on Common Runtime, Cedar Private and Shield Spaces, and Fir Private Spaces.
4
+
3
5
  ## Overview
4
6
 
5
7
  The Heroku Platform MCP Server is a specialized Model Context Protocol (MCP) implementation designed to facilitate
6
- seamless interaction between Large Language Models and the Heroku Platform. This server aims at providing a robust set
7
- of tools and capabilities that enable LLMs to read, manage, and operate Heroku Platform resources.
8
+ seamless interaction between large language models (LLMs) and the Heroku Platform. This server provides a robust set of
9
+ tools and capabilities that enable LLMs to read, manage, and operate Heroku Platform resources.
8
10
 
9
11
  Key Features:
10
12
 
11
13
  - Direct interaction with Heroku Platform resources through LLM-driven tools
12
- - Secure and authenticated access to Heroku Platform APIs, leveraging Heroku CLI
14
+ - Secure and authenticated access to Heroku Platform APIs, leveraging the Heroku CLI
13
15
  - Natural language interface for Heroku Platform interactions
14
16
 
15
17
  Note: The Heroku Platform MCP Server is currently in early development. As we continue to enhance and refine the
16
18
  implementation, the available functionality and tools may evolve. We welcome feedback and contributions to help shape
17
19
  the future of this project.
18
20
 
19
- ## Installation
21
+ ## Install the Heroku Platform MCP Server
20
22
 
21
- Install the Heroku Platform MCP Server globally using npm:
23
+ Install the Heroku Platform MCP Server globally using`npm`:
22
24
 
23
25
  ```sh
24
- npm -i -g @heroku/mcp-server
26
+ npm i -g @heroku/mcp-server
25
27
  ```
26
28
 
27
- ## Configuration
29
+ ## Authentication
28
30
 
29
- ### Authentication Setup
31
+ Generate a Heroku authorization token with one of these methods:
30
32
 
31
- Generate a Heroku authorization token using one of these methods:
33
+ - Use the Heroku CLI command:
32
34
 
33
- - Through your Heroku Dashboard account profile
34
- - Using the Heroku CLI command:
35
35
  ```sh
36
36
  heroku authorizations:create
37
37
  ```
38
- - Using an existing token in the CLI
38
+
39
+ - Use an existing token in the CLI
40
+
39
41
  ```sh
40
42
  heroku auth:token
41
43
  ```
44
+
42
45
  Copy the token and use it as your `HEROKU_API_KEY` in the following steps.
43
46
 
44
- ### Usage with [Claude Desktop](https://claude.ai/download)
47
+ - In your [Heroku Dashboard](https://dashboard.heroku.com/account/applications):
48
+ 1. Select your avatar, then select **Account Settings**.
49
+ 2. Open the Applications tab.
50
+ 3. Next to **Authorizations**, click **Create authorization**.
45
51
 
46
- Add this to your `claude_desktop_config.json`:
52
+ ## Configure the Heroku Platform MCP Server
53
+
54
+ You can configure Claude Desktop, Zed, Cursor, and Windsurf to work with the Heroku Platform MCP Server.
55
+
56
+ ### [Claude Desktop](https://claude.ai/download)
57
+
58
+ Add this snippet to your `claude_desktop_config.json`:
47
59
 
48
60
  ```json
49
- "mcpServers": {
50
- "heroku": {
51
- "command": "heroku-mcp-server",
52
- "env": {
53
- "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
61
+ {
62
+ "mcpServers": {
63
+ "heroku": {
64
+ "command": "npx -y @heroku/mcp-server",
65
+ "env": {
66
+ "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
67
+ }
54
68
  }
55
69
  }
56
70
  }
57
71
  ```
58
72
 
59
- ### Usage with [Zed](https://github.com/zed-industries/zed)
73
+ ### [Zed](https://github.com/zed-industries/zed)
60
74
 
61
- Add this to your Zed settings.json:
75
+ Add this snippet to your Zed `settings.json`:
62
76
 
63
77
  ```json
64
- "context_servers": [
65
- "heroku-mcp-server": {
66
- "command": {
67
- "path": "heroku-mcp-server",
68
- "env": {
69
- "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
78
+ {
79
+ "context_servers": {
80
+ "heroku": {
81
+ "command": {
82
+ "path": "npx",
83
+ "args": ["-y", "@heroku/mcp-server"],
84
+ "env": {
85
+ "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
86
+ }
70
87
  }
71
88
  }
72
89
  }
73
- ],
90
+ }
74
91
  ```
75
92
 
76
- ### Usage with [Cursor](https://www.cursor.com/)
93
+ ### [Cursor](https://www.cursor.com/)
77
94
 
78
- Add this to your Cursor mcp.json:
95
+ Add this snippet to your Cursor `mcp.json`:
79
96
 
80
97
  ```json
81
- "mcpServers": {
82
- "heroku": {
83
- "command": "heroku-mcp-server",
84
- "env": {
85
- "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
98
+ {
99
+ "mcpServers": {
100
+ "heroku": {
101
+ "command": "npx -y @heroku/mcp-server",
102
+ "env": {
103
+ "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
104
+ }
86
105
  }
87
- },
106
+ }
88
107
  }
89
108
  ```
90
109
 
91
- ### Usage with [Windsurf](https://www.windsurf.com/)
110
+ ### [Windsurf](https://www.windsurf.com/)
92
111
 
93
- Add this to your Windsurf mcp_config.json:
112
+ Add this snippet to your Windsurf `mcp_config.json`:
94
113
 
95
114
  ```json
96
- "mcpServers": {
97
- "heroku": {
98
- "command": "heroku-mcp-server",
99
- "env": {
100
- "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
115
+ {
116
+ "mcpServers": {
117
+ "heroku": {
118
+ "command": "npx -y @heroku/mcp-server",
119
+ "env": {
120
+ "HEROKU_API_KEY": "<YOUR_HEROKU_AUTH_TOKEN>"
121
+ }
101
122
  }
102
- },
123
+ }
103
124
  }
104
125
  ```
105
126
 
@@ -107,95 +128,101 @@ Add this to your Windsurf mcp_config.json:
107
128
 
108
129
  ### Application Management
109
130
 
110
- - `list_apps` - List Heroku applications with filtering options for owned apps, collaborator apps, team apps, and
111
- private space apps
112
- - `get_app_info` - Get detailed information about an app including configuration, dynos, add-ons, and more
113
- - `create_app` - Create a new Heroku application with customizable settings for region, team, and private space
114
- - `rename_app` - Rename an existing Heroku application
115
- - `transfer_app` - Transfer app ownership to another user or team
116
- - `deploy_to_heroku` - Deploy projects to Heroku with app.json configuration, supporting team deployments, private
117
- spaces, and environment setup
131
+ - `list_apps` - List all Heroku apps. You can filter apps by personal, collaborator, team, or space.
132
+ - `get_app_info` - Get detailed information about an app, including its configuration, dynos, and add-ons.
133
+ - `create_app` - Create a new app with customizable settings for region, team, and space.
134
+ - `rename_app` - Rename an existing app.
135
+ - `transfer_app` - Transfer ownership of an app to another user or team.
136
+ - `deploy_to_heroku` - Deploy projects to Heroku with an `app.json` configuration, supporting team deployments, private
137
+ spaces, and environment setups.
118
138
 
119
139
  ### Process & Dyno Management
120
140
 
121
- - `ps_list` - List all dynos for an app
122
- - `ps_scale` - Scale dyno quantity up/down or resize dynos
123
- - `ps_restart` - Restart specific dynos, process types, or all dynos
141
+ - `ps_list` - List all dynos for an app.
142
+ - `ps_scale` - Scale the number of dynos up or down, or resize dynos.
143
+ - `ps_restart` - Restart specific dynos, process types, or all dynos.
124
144
 
125
145
  ### Add-ons
126
146
 
127
- - `list_addons` - List all add-ons across apps or for a specific app
128
- - `get_addon_info` - Get detailed information about a specific add-on
129
- - `create_addon` - Provision a new add-on for an app
147
+ - `list_addons` - List all add-ons for all apps or for a specific app.
148
+ - `get_addon_info` - Get detailed information about a specific add-on.
149
+ - `create_addon` - Provision a new add-on for an app.
130
150
 
131
151
  ### Maintenance & Logs
132
152
 
133
- - `maintenance_on` - Enable maintenance mode for an app
134
- - `maintenance_off` - Disable maintenance mode
135
- - `get_app_logs` - View application logs with filtering options
153
+ - `maintenance_on` - Enable maintenance mode for an app.
154
+ - `maintenance_off` - Disable maintenance mode for an app.
155
+ - `get_app_logs` - View application logs.
136
156
 
137
157
  ### Pipeline Management
138
158
 
139
- - `pipelines_create` - Create a new pipeline
140
- - `pipelines_promote` - Promote apps to the next stage in a pipeline
141
- - `pipelines_list` - List available pipelines
142
- - `pipelines_info` - Get detailed pipeline information
159
+ - `pipelines_create` - Create a new pipeline.
160
+ - `pipelines_promote` - Promote apps to the next stage in a pipeline.
161
+ - `pipelines_list` - List available pipelines.
162
+ - `pipelines_info` - Get detailed pipeline information.
143
163
 
144
164
  ### Team & Space Management
145
165
 
146
- - `list_teams` - List teams you belong to
147
- - `list_private_spaces` - List available private spaces
166
+ - `list_teams` - List teams you belong to.
167
+ - `list_private_spaces` - List available spaces.
148
168
 
149
169
  ### PostgreSQL Database Management
150
170
 
151
- - `pg_psql` - Execute SQL queries against Heroku PostgreSQL database
152
- - `pg_info` - Display detailed database information
153
- - `pg_ps` - View active queries and execution details
154
- - `pg_locks` - View database locks and identify blocking transactions
155
- - `pg_outliers` - Identify resource-intensive queries
156
- - `pg_credentials` - Manage database credentials and access
157
- - `pg_kill` - Terminate specific database processes
158
- - `pg_maintenance` - Show database maintenance information
159
- - `pg_backups` - Manage database backups and schedules
160
- - `pg_upgrade` - Upgrade PostgreSQL to a newer version
171
+ - `pg_psql` - Execute SQL queries against the Heroku PostgreSQL database.
172
+ - `pg_info` - Display detailed database information.
173
+ - `pg_ps` - View active queries and execution details.
174
+ - `pg_locks` - View database locks and identify blocking transactions.
175
+ - `pg_outliers` - Identify resource-intensive queries.
176
+ - `pg_credentials` - Manage database credentials and access.
177
+ - `pg_kill` - Terminate specific database processes.
178
+ - `pg_maintenance` - Show database maintenance information.
179
+ - `pg_backups` - Manage database backups and schedules.
180
+ - `pg_upgrade` - Upgrade PostgreSQL to a newer version.
161
181
 
162
182
  ## Debugging
163
183
 
164
- You can use the MCP inspector or the vscode run/debug to run and debug the server.
184
+ You can use the [MCP inspector](https://modelcontextprotocol.io/docs/tools/inspector) or the
185
+ [VS Code Run and Debug function](https://code.visualstudio.com/docs/debugtest/debugging#_start-a-debugging-session) to
186
+ run and debug the server.
187
+
188
+ 1. Link the project as a global CLI using `npm link` from the project root.
189
+ 2. Build with `npm run build:dev` or watch for file changes and build automatically with `npm run build:watch`.
165
190
 
166
- 1. link the project as a global CLI using `npm link` from the project root
167
- 2. build using `npm run build:dev`, or;
168
- 3. to watch for file changes and build automatically use `npm run build:watch`
191
+ ### Use the MCP Inspector
169
192
 
170
- Option 1 - use the @modelcontextprotocol/inspector (no breakpoints in code):
193
+ Use the MCP inspector with no breakpoints in the code:
171
194
 
172
195
  ```
173
196
  # Breakpoints are not available
174
197
  npx @modelcontextprotocol/inspector heroku-mcp-server
175
198
  ```
176
199
 
177
- Option 2 - use the VSCode run/debug launcher (fully functional breakpoints in code):
178
-
179
- 1. Locate and click on the run debug
180
- 2. select the configuration labeled "MCP Server Launcher" in the dropdown
181
- 3. click on the green run/debug button
182
-
183
- Or if you've installed the package in a specific directory or are developing on it:
200
+ Alternatively, if you installed the package in a specific directory or are actively developing on the Heroku MCP server:
184
201
 
185
202
  ```
186
- cd path/to/servers/src/git
203
+ cd /path/to/servers
187
204
  npx @modelcontextprotocol/inspector dist/index.js
188
205
  ```
189
206
 
207
+ ### Use the VS Code Run and Debug Function
208
+
209
+ Use the VS Code
210
+ [Run and Debug launcher](https://code.visualstudio.com/docs/debugtest/debugging#_start-a-debugging-session) with fully
211
+ functional breakpoints in the code:
212
+
213
+ 1. Locate and select the run debug.
214
+ 2. Select the configuration labeled "`MCP Server Launcher`" in the dropdown.
215
+ 3. Select the run/debug button.
216
+
190
217
  ### VS Code / Cursor Debugging Setup
191
218
 
192
- To setup local debugging with breakpoints:
219
+ To set up local debugging with breakpoints:
193
220
 
194
- 1. Store your Heroku auth token in VS Code user settings:
221
+ 1. Store your Heroku auth token in the VS Code user settings:
195
222
 
196
- - Open Command Palette (Cmd/Ctrl + Shift + P)
197
- - Type "Preferences: Open User Settings (JSON)"
198
- - Add the following:
223
+ - Open the Command Palette (Cmd/Ctrl + Shift + P).
224
+ - Type `Preferences: Open User Settings (JSON)`.
225
+ - Add the following snippet:
199
226
 
200
227
  ```json
201
228
  {
@@ -273,7 +300,8 @@ To setup local debugging with breakpoints:
273
300
  }
274
301
  ```
275
302
 
276
- 4. To debug:
277
- - Set breakpoints in your TypeScript files
278
- - Press F5 or use the Run and Debug sidebar
279
- - The debugger will automatically build your TypeScript files before launching
303
+ 4. (Optional) Set breakpoints in your TypeScript files.
304
+
305
+ 5. Press F5 or use the **`Run and Debug`** sidebar.
306
+
307
+ Note: the debugger automatically builds your TypeScript files before launching.
package/dist/index.js CHANGED
@@ -59,6 +59,7 @@ pipelines.registerPipelinesListTool(server, herokuRepl);
59
59
  pipelines.registerPipelinesInfoTool(server, herokuRepl);
60
60
  // Deploy-to-Heroku tool
61
61
  deployToHeroku.registerDeployToHerokuTool(server);
62
+ deployToHeroku.registerDeployOneOffDynoTool(server);
62
63
  /**
63
64
  * Run the server
64
65
  */
@@ -1,10 +1,12 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import * as pjson from '../../package.json' with { type: 'json' };
4
5
  const heroku = path.parse(path.relative(process.cwd(), fileURLToPath(import.meta.resolve('heroku', import.meta.url))));
5
6
  const herokuRunPath = path.join(heroku.dir, '../', 'bin/run');
6
7
  const COMMAND_END_RESULTS_MESSAGE = '<<<END RESULTS>>>';
7
8
  const READY_MESSAGE = 'heroku >';
9
+ const VERSION = pjson.default.version;
8
10
  /**
9
11
  * A class that manages a Heroku CLI REPL process
10
12
  * and allows for durably executing commands via a queue.
@@ -37,6 +39,7 @@ export class HerokuREPL {
37
39
  pauseIteratorResolver;
38
40
  commandTimeout;
39
41
  commandTimeoutId;
42
+ userAgent = `Heroku-MCP-Server/${VERSION} (${process.platform}; ${process.arch}; node/${process.version})`;
40
43
  /**
41
44
  * Create a new HerokuREPL instance
42
45
  *
@@ -124,7 +127,11 @@ export class HerokuREPL {
124
127
  signal: this.abortController.signal,
125
128
  env: {
126
129
  ...process.env,
127
- HEROKU_MCP_MODE: 'true'
130
+ HEROKU_MCP_MODE: 'true',
131
+ HEROKU_MCP_SERVER_VERSION: VERSION,
132
+ HEROKU_HEADERS: JSON.stringify({
133
+ 'User-Agent': this.userAgent
134
+ })
128
135
  }
129
136
  });
130
137
  this.process.stdout?.on('data', (data) => {
@@ -2,6 +2,8 @@ import { EventEmitter } from 'node:events';
2
2
  import { expect } from 'chai';
3
3
  import sinon from 'sinon';
4
4
  import { HerokuREPL } from './heroku-cli-repl.js';
5
+ import * as pjson from '../../package.json' with { type: 'json' };
6
+ const VERSION = pjson.default.version;
5
7
  describe('HerokuREPL', () => {
6
8
  let repl;
7
9
  let mockProcess;
@@ -36,6 +38,10 @@ describe('HerokuREPL', () => {
36
38
  it('should create a new process when initialized', () => {
37
39
  expect(spawnStub.calledOnce).to.be.true;
38
40
  expect(spawnStub.firstCall.args[2].env.HEROKU_MCP_MODE).to.equal('true');
41
+ expect(spawnStub.firstCall.args[2].env.HEROKU_MCP_SERVER_VERSION).to.equal(VERSION);
42
+ expect(spawnStub.firstCall.args[2].env.HEROKU_HEADERS).to.equal(JSON.stringify({
43
+ 'User-Agent': `Heroku-MCP-Server/${VERSION} (${process.platform}; ${process.arch}; node/${process.version})`
44
+ }));
39
45
  });
40
46
  });
41
47
  describe('executeCommand', () => {
@@ -0,0 +1,252 @@
1
+ /**
2
+ * [Heroku Platform API - Dyno](https://devcenter.heroku.com/articles/platform-api-reference#dyno)
3
+ * Dynos encapsulate running processes of an app on Heroku. Detailed information about dyno sizes can be found at: [https://devcenter.heroku.com/articles/dyno-types](https://devcenter.heroku.com/articles/dyno-types).
4
+ */
5
+ export default class DynoService {
6
+ endpoint;
7
+ /**
8
+ * @param endpoint The endpoint to the API.
9
+ */
10
+ constructor(endpoint) {
11
+ this.endpoint = endpoint;
12
+ }
13
+ /**
14
+ * Create a new dyno.
15
+ *
16
+ * @param appIdentity unique identifier of app or unique name of app.
17
+ * @param payload Object to send to the endpoint.
18
+ * @param requestInit The initializer for the request.
19
+ * @returns The response from the API.
20
+ */
21
+ async create(appIdentity, payload, requestInit = {}) {
22
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos`, {
23
+ ...requestInit,
24
+ body: JSON.stringify(payload, null, 2),
25
+ method: 'POST',
26
+ headers: {
27
+ ...requestInit?.headers,
28
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
29
+ 'Content-Type': 'application/json'
30
+ }
31
+ });
32
+ if (response.ok) {
33
+ return (await response.json());
34
+ }
35
+ let message = response.statusText;
36
+ try {
37
+ ({ message } = (await response.json()));
38
+ }
39
+ catch {
40
+ // no-op
41
+ }
42
+ throw new Error(`${response.status}: ${message}`, { cause: response });
43
+ }
44
+ /**
45
+ * Restart dyno.
46
+ *
47
+ * @param appIdentity unique identifier of app or unique name of app.
48
+ * @param dynoIdentity unique identifier of this dyno or the name of this process on this dyno.
49
+ * @param requestInit The initializer for the request.
50
+ * @returns The response from the API.
51
+ */
52
+ async restart(appIdentity, dynoIdentity, requestInit = {}) {
53
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos/${dynoIdentity}`, {
54
+ ...requestInit,
55
+ method: 'DELETE',
56
+ headers: {
57
+ ...requestInit?.headers,
58
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
59
+ 'Content-Type': 'application/json'
60
+ }
61
+ });
62
+ if (response.ok) {
63
+ return (await response.json());
64
+ }
65
+ let message = response.statusText;
66
+ try {
67
+ ({ message } = (await response.json()));
68
+ }
69
+ catch {
70
+ // no-op
71
+ }
72
+ throw new Error(`${response.status}: ${message}`, { cause: response });
73
+ }
74
+ /**
75
+ * Restart dynos of a given formation type.
76
+ *
77
+ * @param appIdentity unique identifier of app or unique name of app.
78
+ * @param dynoFormationType the formation type of this process on this dyno
79
+ * @example "run".
80
+ * @param requestInit The initializer for the request.
81
+ * @returns The response from the API.
82
+ */
83
+ async restartFormation(appIdentity, dynoFormationType, requestInit = {}) {
84
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/formations/${dynoFormationType}`, {
85
+ ...requestInit,
86
+ method: 'DELETE',
87
+ headers: {
88
+ ...requestInit?.headers,
89
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
90
+ 'Content-Type': 'application/json'
91
+ }
92
+ });
93
+ if (response.ok) {
94
+ return (await response.json());
95
+ }
96
+ let message = response.statusText;
97
+ try {
98
+ ({ message } = (await response.json()));
99
+ }
100
+ catch {
101
+ // no-op
102
+ }
103
+ throw new Error(`${response.status}: ${message}`, { cause: response });
104
+ }
105
+ /**
106
+ * Restart all dynos.
107
+ *
108
+ * @param appIdentity unique identifier of app or unique name of app.
109
+ * @param requestInit The initializer for the request.
110
+ * @returns The response from the API.
111
+ */
112
+ async restartAll(appIdentity, requestInit = {}) {
113
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos`, {
114
+ ...requestInit,
115
+ method: 'DELETE',
116
+ headers: {
117
+ ...requestInit?.headers,
118
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
119
+ 'Content-Type': 'application/json'
120
+ }
121
+ });
122
+ if (response.ok) {
123
+ return (await response.json());
124
+ }
125
+ let message = response.statusText;
126
+ try {
127
+ ({ message } = (await response.json()));
128
+ }
129
+ catch {
130
+ // no-op
131
+ }
132
+ throw new Error(`${response.status}: ${message}`, { cause: response });
133
+ }
134
+ /**
135
+ * Stop dyno.
136
+ *
137
+ * @param appIdentity unique identifier of app or unique name of app.
138
+ * @param dynoIdentity unique identifier of this dyno or the name of this process on this dyno.
139
+ * @param requestInit The initializer for the request.
140
+ * @returns The response from the API.
141
+ */
142
+ async stop(appIdentity, dynoIdentity, requestInit = {}) {
143
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos/${dynoIdentity}/actions/stop`, {
144
+ ...requestInit,
145
+ method: 'POST',
146
+ headers: {
147
+ ...requestInit?.headers,
148
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
149
+ 'Content-Type': 'application/json'
150
+ }
151
+ });
152
+ if (response.ok) {
153
+ return (await response.json());
154
+ }
155
+ let message = response.statusText;
156
+ try {
157
+ ({ message } = (await response.json()));
158
+ }
159
+ catch {
160
+ // no-op
161
+ }
162
+ throw new Error(`${response.status}: ${message}`, { cause: response });
163
+ }
164
+ /**
165
+ * Stop dynos of a given formation type.
166
+ *
167
+ * @param appIdentity unique identifier of app or unique name of app.
168
+ * @param dynoFormationType the formation type of this process on this dyno
169
+ * @example "run".
170
+ * @param requestInit The initializer for the request.
171
+ * @returns The response from the API.
172
+ */
173
+ async stopFormation(appIdentity, dynoFormationType, requestInit = {}) {
174
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/formations/${dynoFormationType}/actions/stop`, {
175
+ ...requestInit,
176
+ method: 'POST',
177
+ headers: {
178
+ ...requestInit?.headers,
179
+ Accept: 'application/vnd.heroku+json; version=3.sdk',
180
+ 'Content-Type': 'application/json'
181
+ }
182
+ });
183
+ if (response.ok) {
184
+ return (await response.json());
185
+ }
186
+ let message = response.statusText;
187
+ try {
188
+ ({ message } = (await response.json()));
189
+ }
190
+ catch {
191
+ // no-op
192
+ }
193
+ throw new Error(`${response.status}: ${message}`, { cause: response });
194
+ }
195
+ /**
196
+ * Info for existing dyno.
197
+ *
198
+ * @param appIdentity unique identifier of app or unique name of app.
199
+ * @param dynoIdentity unique identifier of this dyno or the name of this process on this dyno.
200
+ * @param requestInit The initializer for the request.
201
+ * @returns The response from the API.
202
+ */
203
+ async info(appIdentity, dynoIdentity, requestInit = {}) {
204
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos/${dynoIdentity}`, {
205
+ ...requestInit,
206
+ method: 'GET',
207
+ headers: {
208
+ ...requestInit?.headers,
209
+ Accept: 'application/vnd.heroku+json; version=3.sdk'
210
+ }
211
+ });
212
+ if (response.ok) {
213
+ return (await response.json());
214
+ }
215
+ let message = response.statusText;
216
+ try {
217
+ ({ message } = (await response.json()));
218
+ }
219
+ catch {
220
+ // no-op
221
+ }
222
+ throw new Error(`${response.status}: ${message}`, { cause: response });
223
+ }
224
+ /**
225
+ * List existing dynos.
226
+ *
227
+ * @param appIdentity unique identifier of app or unique name of app.
228
+ * @param requestInit The initializer for the request.
229
+ * @returns The response from the API.
230
+ */
231
+ async list(appIdentity, requestInit = {}) {
232
+ const response = await fetch(`${this.endpoint}/apps/${appIdentity}/dynos`, {
233
+ ...requestInit,
234
+ method: 'GET',
235
+ headers: {
236
+ ...requestInit?.headers,
237
+ Accept: 'application/vnd.heroku+json; version=3.sdk'
238
+ }
239
+ });
240
+ if (response.ok) {
241
+ return (await response.json());
242
+ }
243
+ let message = response.statusText;
244
+ try {
245
+ ({ message } = (await response.json()));
246
+ }
247
+ catch {
248
+ // no-op
249
+ }
250
+ throw new Error(`${response.status}: ${message}`, { cause: response });
251
+ }
252
+ }
@@ -0,0 +1,140 @@
1
+ import * as tls from 'node:tls';
2
+ /**
3
+ * Implements the Heroku Rendezvous protocol for connecting to one-off dynos
4
+ * See: https://devcenter.heroku.com/articles/one-off-dynos#rendezvous
5
+ */
6
+ export class RendezvousConnection {
7
+ options;
8
+ connection = null;
9
+ timeout = 1000 * 60 * 60; // 1 hour timeout
10
+ output = '';
11
+ exitCode = null;
12
+ /**
13
+ * Creates a new RendezvousConnection
14
+ *
15
+ * @param options The options for the rendezvous connection
16
+ */
17
+ constructor(options) {
18
+ this.options = options;
19
+ }
20
+ /**
21
+ * Establishes a connection to the dyno using the rendezvous protocol
22
+ * and returns the output once the dyno completes
23
+ *
24
+ * @returns A promise that resolves with the dyno output and exit code
25
+ */
26
+ async connect() {
27
+ try {
28
+ this.updateStatus('starting');
29
+ this.connection = tls.connect(Number.parseInt(this.options.uri.port, 10), this.options.uri.hostname, {
30
+ rejectUnauthorized: this.options.rejectUnauthorized
31
+ });
32
+ await this.setupConnection();
33
+ // Return the captured output and exit code
34
+ return {
35
+ output: this.output,
36
+ exitCode: this.exitCode ?? 0
37
+ };
38
+ }
39
+ catch (error) {
40
+ if (error instanceof Error) {
41
+ throw error;
42
+ }
43
+ throw new Error('Failed to establish connection');
44
+ }
45
+ }
46
+ /**
47
+ * Closes the rendezvous connection if open
48
+ */
49
+ close() {
50
+ if (this.connection) {
51
+ this.connection.end();
52
+ this.connection = null;
53
+ }
54
+ }
55
+ /**
56
+ * Sets up the connection
57
+ *
58
+ * @returns A promise that resolves when the connection is complete
59
+ */
60
+ setupConnection() {
61
+ if (!this.connection)
62
+ throw new Error('Connection not initialized');
63
+ return new Promise((resolve, reject) => {
64
+ this.connection.setTimeout(this.timeout);
65
+ this.connection.setEncoding('utf8');
66
+ // Setup event handlers
67
+ this.connection.on('connect', () => this.handleConnect());
68
+ this.connection.on('data', (data) => this.handleData(data));
69
+ this.connection.on('close', () => resolve());
70
+ this.connection.on('error', (err) => reject(err));
71
+ this.connection.on('timeout', () => this.handleTimeout());
72
+ // Handle process termination
73
+ process.once('SIGINT', () => {
74
+ this.close();
75
+ reject(new Error('Process terminated'));
76
+ });
77
+ });
78
+ }
79
+ /**
80
+ * Handles the initial connection setup
81
+ */
82
+ handleConnect() {
83
+ if (!this.connection)
84
+ return;
85
+ const pathnameWithSearchParams = this.options.uri.pathname + this.options.uri.search;
86
+ this.connection.write(pathnameWithSearchParams.slice(1) + '\r\n', () => {
87
+ this.updateStatus('connecting');
88
+ });
89
+ }
90
+ /**
91
+ * Handles incoming data from the connection
92
+ * Captures both output and exit code from the dyno
93
+ *
94
+ * @param data The data received from the connection
95
+ */
96
+ handleData(data) {
97
+ // Check for exit code in the data
98
+ const exitCodeMatch = data.match(/\[exit\s*(\d+)\]/);
99
+ if (exitCodeMatch) {
100
+ this.exitCode = parseInt(exitCodeMatch[1], 10);
101
+ // Create a new variable for the modified data
102
+ const cleanedData = data.replace(/\[exit\s*\d+\]/, '');
103
+ // Append to output buffer
104
+ this.output += cleanedData;
105
+ // Call onData callback if provided
106
+ if (this.options.onData) {
107
+ this.options.onData(cleanedData);
108
+ }
109
+ }
110
+ else {
111
+ // Append to output buffer
112
+ this.output += data;
113
+ // Call onData callback if provided
114
+ if (this.options.onData) {
115
+ this.options.onData(data);
116
+ }
117
+ }
118
+ // Update status if we detect completion
119
+ if (this.exitCode !== null) {
120
+ this.updateStatus('complete');
121
+ }
122
+ }
123
+ /**
124
+ * Handles connection timeout events
125
+ */
126
+ handleTimeout() {
127
+ this.close();
128
+ throw new Error('Connection timed out');
129
+ }
130
+ /**
131
+ * Updates the connection status
132
+ *
133
+ * @param status The new status to set
134
+ */
135
+ updateStatus(status) {
136
+ if (this.options.showStatus && this.options.onStatusChange) {
137
+ this.options.onStatusChange(status);
138
+ }
139
+ }
140
+ }
@@ -8,91 +8,9 @@ import AppSetupService from '../services/app-setup-service.js';
8
8
  import BuildService from '../services/build-service.js';
9
9
  import { generateRequestInit } from '../utils/generate-request-init.js';
10
10
  import { packSources } from '../utils/tarball.js';
11
+ import DynoService from '../services/dyno-service.js';
12
+ import { RendezvousConnection } from '../services/rendezvous.js';
11
13
  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
14
  /**
97
15
  * The DeploymentError class is used when
98
16
  * an error occurs during the deployment of
@@ -141,6 +59,7 @@ export class DeployToHeroku extends AbortController {
141
59
  sourcesService = new SourceService('https://api.heroku.com');
142
60
  appSetupService = new AppSetupService('https://api.heroku.com');
143
61
  buildService = new BuildService('https://api.heroku.com');
62
+ dynoService = new DynoService('https://api.heroku.com');
144
63
  requestInit;
145
64
  isExistingDeployment = false;
146
65
  deploymentOptions;
@@ -211,17 +130,29 @@ export class DeployToHeroku extends AbortController {
211
130
  * and returns it. The Promise returned from this function
212
131
  * is expected to be awaited on in a try...catch.
213
132
  *
214
- * It performs the following tasks:
133
+ * For regular deployments, it performs:
215
134
  * 1. Validates the app.json configuration file
216
135
  * 2. Validates the Procfile
217
136
  * 3. Creates and deploys a new Heroku application
218
137
  * 4. Adds the new Heroku app to the git remote
219
138
  * 5. Displays a notification with options to view the app in the explorer
220
139
  *
140
+ * For one-off dynos, it:
141
+ * 1. Creates and configures the dyno
142
+ * 2. Waits for the dyno to start
143
+ * 3. Establishes a rendezvous connection to capture output
144
+ * 4. Monitors execution until completion
145
+ * 5. Handles automatic cleanup if timeToLive is specified
146
+ *
221
147
  * @returns The deployment process wrapped in a promise
222
148
  */
223
149
  runOperation = async () => {
224
150
  const { tarballUri } = this.deploymentOptions;
151
+ // If command is present, this is a one-off dyno deployment
152
+ if ('command' in this.deploymentOptions) {
153
+ return this.deployOneOffDyno();
154
+ }
155
+ // Regular app deployment flow
225
156
  // app.json is required on an initial deployment using this flow
226
157
  if (!tarballUri && !this.isExistingDeployment) {
227
158
  await this.validateAppJson();
@@ -258,13 +189,18 @@ export class DeployToHeroku extends AbortController {
258
189
  const tarball = await packSources(rootUri, generatedAppJson);
259
190
  const { source_blob: sourceBlob } = await this.sourcesService.create(this.requestInit);
260
191
  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);
192
+ try {
193
+ const response = await fetch(sourceBlob.put_url, {
194
+ method: 'PUT',
195
+ body: tarball
196
+ });
197
+ if (!response.ok) {
198
+ const uploadErrorMessage = `Error uploading tarball to S3 bucket. The server responded with: ${response.status} - ${response.statusText}`;
199
+ throw new Error(uploadErrorMessage);
200
+ }
201
+ }
202
+ catch (error) {
203
+ throw new DeploymentError(error.message);
268
204
  }
269
205
  }
270
206
  // The user has right-clicked on a
@@ -289,6 +225,92 @@ export class DeployToHeroku extends AbortController {
289
225
  }
290
226
  return result;
291
227
  }
228
+ /**
229
+ * Deploys a one-off dyno to the app and captures its output.
230
+ * This method:
231
+ * 1. Creates and configures the dyno with the specified settings
232
+ * 2. Waits for the dyno to start
233
+ * 3. Establishes a rendezvous connection to capture output
234
+ * 4. Monitors execution until completion
235
+ * 5. Handles automatic cleanup if timeToLive is specified
236
+ *
237
+ * @returns A promise resolving to an object containing:
238
+ * - dyno: The Heroku dyno object
239
+ * - output: The complete output from the dyno's execution
240
+ * - exitCode: The process exit code (0 for success, non-zero for failure)
241
+ * - name: The name of the app the dyno was created in
242
+ * - errorMessage: Optional error message if execution failed
243
+ * @throws {DeploymentError} If the deployment fails, dyno crashes, or no attach URL is available
244
+ * @throws {Error} For general deployment failures with detailed error messages
245
+ */
246
+ async deployOneOffDyno() {
247
+ const { name, command, size, timeToLive, env, sources } = this.deploymentOptions;
248
+ try {
249
+ // If sources are provided, pack them and modify the command
250
+ let finalCommand = command;
251
+ if (sources?.length) {
252
+ const commands = [
253
+ 'TEMP_DIR=$(mktemp -d)',
254
+ 'cd $TEMP_DIR',
255
+ ...sources.map((source) => `printf '%s' '${source.contents.replace(/'/g, "'\\''")}' > ${source.relativePath}`),
256
+ command,
257
+ 'cd - > /dev/null',
258
+ 'rm -rf $TEMP_DIR'
259
+ ];
260
+ finalCommand = commands.join(' && ');
261
+ }
262
+ // Create and start the one-off dyno
263
+ const dyno = await this.dynoService.create(name, {
264
+ command: finalCommand,
265
+ size: size ?? 'basic',
266
+ type: 'run',
267
+ // eslint-disable-next-line camelcase
268
+ time_to_live: timeToLive,
269
+ attach: true,
270
+ env: env ?? {},
271
+ // eslint-disable-next-line camelcase
272
+ force_no_tty: true
273
+ }, this.requestInit);
274
+ // Connect to the dyno and capture output
275
+ const rendezvous = new RendezvousConnection({
276
+ uri: new URL(dyno.attach_url),
277
+ rejectUnauthorized: true,
278
+ showStatus: true,
279
+ onStatusChange: (status) => {
280
+ // eslint-disable-next-line no-console
281
+ console.log(`Dyno status: ${status}`);
282
+ }
283
+ });
284
+ // Capture the output and exit code
285
+ const { output, exitCode } = await rendezvous.connect();
286
+ // Set up auto-stop if timeToLive is specified
287
+ if (timeToLive) {
288
+ const timeoutFunc = async () => {
289
+ try {
290
+ await this.dynoService.stop(name, dyno.id, this.requestInit);
291
+ }
292
+ catch (error) {
293
+ // eslint-disable-next-line no-console
294
+ console.warn('Failed to stop dyno:', error);
295
+ }
296
+ };
297
+ setTimeout(() => void timeoutFunc(), timeToLive * 1000);
298
+ }
299
+ return {
300
+ dyno,
301
+ output,
302
+ exitCode,
303
+ name,
304
+ errorMessage: exitCode !== 0 ? `Dyno exited with code ${exitCode}` : undefined
305
+ };
306
+ }
307
+ catch (error) {
308
+ if (error instanceof DeploymentError) {
309
+ throw error;
310
+ }
311
+ throw new Error(`One-off dyno deployment failed: ${error instanceof Error ? error.message : String(error)}`);
312
+ }
313
+ }
292
314
  /**
293
315
  * Reads and validates the app.json. If it is invalid,
294
316
  * the errors are logged and the user is informed that
@@ -447,3 +469,166 @@ export class DeployToHeroku extends AbortController {
447
469
  return output;
448
470
  }
449
471
  }
472
+ /**
473
+ * Schema for validating Heroku deployment parameters.
474
+ * This schema enforces the structure and types of deployment options
475
+ * including required fields and optional configurations.
476
+ */
477
+ export const deployToHerokuSchema = z
478
+ .object({
479
+ name: z
480
+ .string()
481
+ .min(5)
482
+ .max(30)
483
+ .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.'),
484
+ rootUri: z
485
+ .string()
486
+ .min(1)
487
+ .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."),
488
+ tarballUri: z
489
+ .string()
490
+ .optional()
491
+ .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.'),
492
+ teamId: z
493
+ .string()
494
+ .optional()
495
+ .describe('Heroku team identifier for team-scoped deployments. Use teams_list tool to get a list of teams if needed.'),
496
+ spaceId: z
497
+ .string()
498
+ .optional()
499
+ .describe('Heroku private space identifier for space-scoped deployments. Use spaces_list tool to get a list of spaces if needed.'),
500
+ internalRouting: z
501
+ .boolean()
502
+ .optional()
503
+ .describe('Enables internal routing within private spaces. Use this flag when you need to configure private spaces for internal routing.'),
504
+ env: z
505
+ .record(z.string(), z.any())
506
+ .optional()
507
+ .describe('Key-value pairs of environment variables for the deployment that override the ones in app.json'),
508
+ appJson: z.string()
509
+ .describe(`Stringified app.json configuration for deployment. Used for dynamic configurations or converted projects.
510
+ The app.json string must be valid and conform to the following schema: ${JSON.stringify(appJsonSchema, null, 0)}`)
511
+ })
512
+ .strict();
513
+ /**
514
+ * Registers the deploy_to_heroku tool with the MCP server.
515
+ * This tool handles deployment of applications to Heroku using app.json configuration.
516
+ * It supports team and private space deployments, environment variable configuration,
517
+ * and custom app.json specifications.
518
+ *
519
+ * @param server - The MCP server instance to register the tool with
520
+ */
521
+ export const registerDeployToHerokuTool = (server) => {
522
+ server.tool('deploy_to_heroku', 'Deploy projects to Heroku, replaces manual git push workflows. Use this tool when you need to: ' +
523
+ '1) Deploy a new application with specific app.json configuration, 2) Update an existing application with new code, ' +
524
+ '3) Configure team or private space deployments, or 4) Set up environment-specific configurations. ' +
525
+ 'Important: Check for an app.json file first. If an app.json does not exist in the workspace, you must create one and pass it in via the appJson parameter. ' +
526
+ 'The tool handles app creation, source code deployment, and environment setup. ' +
527
+ 'Requires valid app.json in workspace or provided via configuration. ' +
528
+ 'Supports team deployments, private spaces, and custom environment variables.' +
529
+ '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) => {
530
+ const deployToHeroku = new DeployToHeroku();
531
+ const result = await deployToHeroku.run({
532
+ rootUri: options.rootUri,
533
+ tarballUri: options.tarballUri,
534
+ name: options.name,
535
+ teamId: options.teamId,
536
+ spaceId: options.spaceId,
537
+ internalRouting: options.internalRouting,
538
+ env: options.env,
539
+ appJson: options.appJson ? new TextEncoder().encode(options.appJson) : undefined
540
+ });
541
+ if (result?.errorMessage) {
542
+ return {
543
+ success: false,
544
+ message: result.errorMessage,
545
+ content: [{ type: 'text', text: result.errorMessage }]
546
+ };
547
+ }
548
+ const successMessage = `Successfully deployed to ${result?.name ?? 'Heroku'}`;
549
+ return {
550
+ success: true,
551
+ message: successMessage,
552
+ content: [{ type: 'text', text: successMessage }],
553
+ data: result
554
+ };
555
+ });
556
+ };
557
+ // Define the schema for deploying to a one-off dyno
558
+ export const deployOneOffDynoSchema = z
559
+ .object({
560
+ name: z.string().min(5).max(30).describe('Name of the Heroku app for the one-off dyno.'),
561
+ command: z.string().describe('Command to execute in the one-off dyno.'),
562
+ sources: z
563
+ .array(z.object({
564
+ relativePath: z
565
+ .string()
566
+ .describe('A virtual path to the source file used to create the tarball entry for this file.'),
567
+ contents: z.string().describe('Contents of the source file represented as a string.')
568
+ }))
569
+ .optional()
570
+ .describe('Array of objects representing the source files to include in the dyno.'),
571
+ size: z.string().optional().describe('Dyno size (optional).').default('standard-1x'),
572
+ timeToLive: z.number().optional().describe('Dyno lifespan in seconds (optional).').default(3600),
573
+ env: z.record(z.string(), z.any()).optional().describe('Environment variables for the dyno (optional).')
574
+ })
575
+ .strict();
576
+ export const execToolSchemaDescription = `
577
+ Execute code or a command on a Heroku one-off dyno in a sandboxed environment with network and filesystem access.
578
+
579
+ **Requirements:**
580
+ - Display command output to the user.
581
+ - Determine app language using the 'app_info' tool to identify the Heroku buildpack.
582
+ - Use shell commands for environment setup (e.g., package installations) before execution.
583
+ - Output must utilize standard input/output.
584
+
585
+ **Capabilities:**
586
+ - Network and filesystem access
587
+ - Environment variables support
588
+ - File creation and execution in supported languages
589
+ - Temporary directory management
590
+
591
+ **Guidelines:**
592
+ 1. Use the appropriate Heroku-supported language runtime.
593
+ 2. Ensure correct syntax and module imports for the chosen language.
594
+ 3. Organize code into classes/functions, executed from the top level.
595
+ 4. For external packages:
596
+ - Specify in the appropriate package manager file.
597
+ - Minimize dependencies.
598
+ - Prefer native modules when possible.
599
+
600
+ **Example (Node.js package manager file):**
601
+ \`\`\`json
602
+ {
603
+ "type": "module",
604
+ "dependencies": {
605
+ "axios": "^1.6.0"
606
+ }
607
+ }
608
+ \`\`\`
609
+ `;
610
+ /**
611
+ * Registers the deploy_one_off_dyno tool with the MCP server.
612
+ * This tool handles deployment of one-off dynos to Heroku using the specified command and configuration.
613
+ *
614
+ * @param server - The MCP server instance to register the tool with
615
+ */
616
+ export const registerDeployOneOffDynoTool = (server) => {
617
+ server.tool('deploy_one_off_dyno', execToolSchemaDescription, deployOneOffDynoSchema.shape, async (options) => {
618
+ const deployToHeroku = new DeployToHeroku();
619
+ const result = (await deployToHeroku.run(options));
620
+ if (result?.errorMessage) {
621
+ return {
622
+ success: false,
623
+ message: result.errorMessage,
624
+ content: [{ type: 'text', text: result.errorMessage }]
625
+ };
626
+ }
627
+ return {
628
+ success: true,
629
+ message: result.output ?? 'Successfully deployed one-off dyno to Heroku',
630
+ content: [{ type: 'text', text: result.output }],
631
+ data: result
632
+ };
633
+ });
634
+ };
@@ -9,6 +9,8 @@ import SourceService from '../services/source-service.js';
9
9
  import AppSetupService from '../services/app-setup-service.js';
10
10
  import BuildService from '../services/build-service.js';
11
11
  import sinon from 'sinon';
12
+ import { RendezvousConnection } from '../services/rendezvous.js';
13
+ import DynoService from '../services/dyno-service.js';
12
14
  describe('DeployToHeroku', () => {
13
15
  // Increase timeout for async tests
14
16
  const TEST_TIMEOUT = 30000;
@@ -22,6 +24,7 @@ describe('DeployToHeroku', () => {
22
24
  let appSetupServiceStub;
23
25
  let buildServiceStub;
24
26
  let fetchStub;
27
+ let dynoServiceStub;
25
28
  beforeEach(async () => {
26
29
  // Create a temporary directory for each test
27
30
  tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'deploy-test-'));
@@ -30,6 +33,7 @@ describe('DeployToHeroku', () => {
30
33
  sourceServiceStub = sinon.createStubInstance(SourceService);
31
34
  appSetupServiceStub = sinon.createStubInstance(AppSetupService);
32
35
  buildServiceStub = sinon.createStubInstance(BuildService);
36
+ dynoServiceStub = sinon.createStubInstance(DynoService);
33
37
  const readable = Readable.from((async function* () {
34
38
  yield 'test log output';
35
39
  })());
@@ -47,7 +51,8 @@ describe('DeployToHeroku', () => {
47
51
  appService: appServiceStub,
48
52
  sourcesService: sourceServiceStub,
49
53
  appSetupService: appSetupServiceStub,
50
- buildService: buildServiceStub
54
+ buildService: buildServiceStub,
55
+ dynoService: dynoServiceStub
51
56
  });
52
57
  });
53
58
  afterEach(async () => {
@@ -162,5 +167,41 @@ describe('DeployToHeroku', () => {
162
167
  expect(result.errorMessage).to.include('Error 2');
163
168
  }
164
169
  });
170
+ it('should deploy a one-off dyno and capture output', async function () {
171
+ this.timeout(TEST_TIMEOUT);
172
+ // Create test app.json
173
+ await createTempFile('app.json', JSON.stringify({
174
+ name: 'test-app',
175
+ description: 'Test app',
176
+ stack: 'heroku-22'
177
+ }));
178
+ const mockDyno = {
179
+ id: 'dyno-id',
180
+ attach_url: 'https://test.com/attach',
181
+ command: 'echo "Hello, World!"'
182
+ };
183
+ const mockDynoResult = {
184
+ dyno: mockDyno,
185
+ output: 'Hello, World!',
186
+ exitCode: 0,
187
+ name: 'test-app'
188
+ };
189
+ dynoServiceStub.create.resolves(mockDyno);
190
+ const rendezvousStub = sinon.stub(RendezvousConnection.prototype, 'connect').resolves({
191
+ output: 'Hello, World!',
192
+ exitCode: 0
193
+ });
194
+ const options = {
195
+ name: 'test-app',
196
+ command: 'echo "Hello, World!"',
197
+ rootUri: tempDir
198
+ };
199
+ const result = await deployToHeroku.run(options);
200
+ expect(result).to.not.be.null;
201
+ expect(result).to.have.property('output', 'Hello, World!');
202
+ expect(result).to.have.property('exitCode', 0);
203
+ expect(dynoServiceStub.create.calledOnce).to.be.true;
204
+ expect(rendezvousStub.calledOnce).to.be.true;
205
+ });
165
206
  });
166
207
  });
@@ -7,7 +7,7 @@ import * as tar from 'tar-stream';
7
7
  * Creates a compressed tarball (tar.gz) from the contents of a workspace folder.
8
8
  * The function respects git ignore rules and excludes node_modules directory.
9
9
  *
10
- * @param root - The workspace folder to create a tarball from
10
+ * @param root - The workspace folder to create a tarball from or undefined when only generated content should be included
11
11
  * @param additionalContents - Additional contents to include in the tarball
12
12
  * @returns A Promise that resolves to a Uint8Array containing the compressed tarball data
13
13
  *
@@ -25,7 +25,7 @@ import * as tar from 'tar-stream';
25
25
  * @throws {Error} If unable to read workspace files or create the tarball
26
26
  */
27
27
  export async function packSources(root, additionalContents = []) {
28
- const files = await getSourceFilePaths(root);
28
+ const files = root ? await getSourceFilePaths(root) : [];
29
29
  const pack = tar.pack();
30
30
  const gzip = zlib.createGzip();
31
31
  const chunks = [];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@heroku/mcp-server",
3
3
  "description": "Heroku Platform MCP Server",
4
- "version": "0.0.1",
4
+ "version": "1.0.1",
5
5
  "author": "Heroku",
6
6
  "bugs": "https://github.com/heroku/heroku-mcp-server/issues",
7
7
  "bin": {
@@ -10,7 +10,7 @@
10
10
  "type": "module",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "^1.8.0",
13
- "heroku": "10.4.1-alpha.3",
13
+ "heroku": "10.4.1-alpha.4",
14
14
  "jsonschema": "^1.5.0",
15
15
  "tar-stream": "^3.1.7",
16
16
  "zod": "^3.24.2",
@@ -22,7 +22,7 @@
22
22
  "@modelcontextprotocol/inspector": "^0.7.0",
23
23
  "@types/chai": "^5.2.1",
24
24
  "@types/mocha": "^10.0.10",
25
- "@types/node": "^22.13.14",
25
+ "@types/node": "^20.x",
26
26
  "@types/sinon": "^17.0.4",
27
27
  "@types/tar-stream": "^3.1.3",
28
28
  "@typescript-eslint/eslint-plugin": "^8.28.0",
@@ -43,7 +43,7 @@
43
43
  "typescript": "^5.8.2"
44
44
  },
45
45
  "engines": {
46
- "node": ">=22"
46
+ "node": ">=20"
47
47
  },
48
48
  "exports": {
49
49
  "./*": {