forked from getsentry/XcodeBuildMCP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_macos.ts
More file actions
335 lines (304 loc) · 9.93 KB
/
build_macos.ts
File metadata and controls
335 lines (304 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
* macOS Build Tools - Tools for building and running macOS applications
*
* This module provides specialized tools for building and running macOS applications
* using xcodebuild. It supports both workspace and project-based builds with architecture
* specification (arm64 or x86_64).
*
* Responsibilities:
* - Building macOS applications from project files and workspaces
* - Running macOS applications after building
* - Supporting architecture-specific builds (arm64, x86_64)
* - Handling build configuration and derived data paths
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { exec } from 'child_process';
import { promisify } from 'util';
import { log } from '../utils/logger.js';
import { XcodePlatform, executeXcodeCommand } from '../utils/xcode.js';
import { createTextResponse } from '../utils/validation.js';
import { ToolResponse } from '../types/common.js';
import { executeXcodeBuild } from '../utils/build-utils.js';
import { z } from 'zod';
import {
registerTool,
workspacePathSchema,
projectPathSchema,
schemeSchema,
configurationSchema,
derivedDataPathSchema,
extraArgsSchema,
} from './common.js';
// Schema for architecture parameter
const archSchema = z
.enum(['arm64', 'x86_64'])
.optional()
.describe('Architecture to build for (arm64 or x86_64). For macOS only.');
// --- Private Helper Functions ---
/**
* Internal logic for building macOS apps.
*/
async function _handleMacOSBuildLogic(params: {
workspacePath?: string;
projectPath?: string;
scheme: string;
configuration: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
}): Promise<ToolResponse> {
log('info', `Starting macOS build for scheme ${params.scheme} (internal)`);
return executeXcodeBuild(
{
...params,
},
{
platform: XcodePlatform.macOS,
arch: params.arch,
logPrefix: 'macOS Build',
},
'build',
);
}
async function _getAppPathFromBuildSettings(params: {
workspacePath?: string;
projectPath?: string;
scheme: string;
configuration: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
}): Promise<{ success: boolean; appPath?: string; error?: string }> {
try {
// Create the command array for xcodebuild
const command = ['xcodebuild', '-showBuildSettings'];
// Add the workspace or project
if (params.workspacePath) {
command.push('-workspace', params.workspacePath);
} else if (params.projectPath) {
command.push('-project', params.projectPath);
}
// Add the scheme and configuration
command.push('-scheme', params.scheme);
command.push('-configuration', params.configuration);
// Add derived data path if provided
if (params.derivedDataPath) {
command.push('-derivedDataPath', params.derivedDataPath);
}
// Add extra args if provided
if (params.extraArgs && params.extraArgs.length > 0) {
command.push(...params.extraArgs);
}
// Execute the command directly
const result = await executeXcodeCommand(command, 'Get Build Settings for Launch');
if (!result.success) {
return {
success: false,
error: result.error || 'Failed to get build settings',
};
}
// Parse the output to extract the app path
const buildSettingsOutput = result.output;
const builtProductsDirMatch = buildSettingsOutput.match(/BUILT_PRODUCTS_DIR = (.+)$/m);
const fullProductNameMatch = buildSettingsOutput.match(/FULL_PRODUCT_NAME = (.+)$/m);
if (!builtProductsDirMatch || !fullProductNameMatch) {
return { success: false, error: 'Could not extract app path from build settings' };
}
const appPath = `${builtProductsDirMatch[1].trim()}/${fullProductNameMatch[1].trim()}`;
return { success: true, appPath };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return { success: false, error: errorMessage };
}
}
/**
* Internal logic for building and running macOS apps.
*/
async function _handleMacOSBuildAndRunLogic(params: {
workspacePath?: string;
projectPath?: string;
scheme: string;
configuration: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
}): Promise<ToolResponse> {
log('info', 'Handling macOS build & run logic...');
const _warningMessages: { type: 'text'; text: string }[] = [];
const _warningRegex = /\[warning\]: (.*)/g;
try {
// First, build the app
const buildResult = await _handleMacOSBuildLogic(params);
// 1. Check if the build itself failed
if (buildResult.isError) {
return buildResult; // Return build failure directly
}
const buildWarningMessages = buildResult.content?.filter((c) => c.type === 'text') ?? [];
// 2. Build succeeded, now get the app path using the helper
const appPathResult = await _getAppPathFromBuildSettings(params);
// 3. Check if getting the app path failed
if (!appPathResult.success) {
log('error', 'Build succeeded, but failed to get app path to launch.');
const response = createTextResponse(
`✅ Build succeeded, but failed to get app path to launch: ${appPathResult.error}`,
false, // Build succeeded, so not a full error
);
if (response.content) {
response.content.unshift(...buildWarningMessages);
}
return response;
}
const appPath = appPathResult.appPath; // We know this is a valid string now
log('info', `App path determined as: ${appPath}`);
// 4. Launch the app using the verified path
// Launch the app
try {
await promisify(exec)(`open "${appPath}"`);
log('info', `✅ macOS app launched successfully: ${appPath}`);
const successResponse: ToolResponse = {
content: [
...buildWarningMessages,
{
type: 'text',
text: `✅ macOS build and run succeeded for scheme ${params.scheme}. App launched: ${appPath}`,
},
],
};
return successResponse;
} catch (launchError) {
const errorMessage = launchError instanceof Error ? launchError.message : String(launchError);
log('error', `Build succeeded, but failed to launch app ${appPath}: ${errorMessage}`);
const errorResponse = createTextResponse(
`✅ Build succeeded, but failed to launch app ${appPath}. Error: ${errorMessage}`,
false, // Build succeeded
);
if (errorResponse.content) {
errorResponse.content.unshift(...buildWarningMessages);
}
return errorResponse;
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
log('error', `Error during macOS build & run logic: ${errorMessage}`);
const errorResponse = createTextResponse(
`Error during macOS build and run: ${errorMessage}`,
true,
);
return errorResponse;
}
}
// --- Public Tool Definitions ---
// Register macOS build workspace tool
export function registerMacOSBuildWorkspaceTool(server: McpServer): void {
type WorkspaceParams = {
workspacePath: string;
scheme: string;
configuration?: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
};
registerTool<WorkspaceParams>(
server,
'build_mac_ws',
'Builds a macOS app using xcodebuild from a workspace.',
{
workspacePath: workspacePathSchema,
scheme: schemeSchema,
configuration: configurationSchema,
derivedDataPath: derivedDataPathSchema,
arch: archSchema,
extraArgs: extraArgsSchema,
},
async (params) =>
_handleMacOSBuildLogic({
...params,
configuration: params.configuration ?? 'Debug',
}),
);
}
// Register macOS build project tool
export function registerMacOSBuildProjectTool(server: McpServer): void {
type ProjectParams = {
projectPath: string;
scheme: string;
configuration?: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
};
registerTool<ProjectParams>(
server,
'build_mac_proj',
'Builds a macOS app using xcodebuild from a project file.',
{
projectPath: projectPathSchema,
scheme: schemeSchema,
configuration: configurationSchema,
derivedDataPath: derivedDataPathSchema,
arch: archSchema,
extraArgs: extraArgsSchema,
},
async (params) =>
_handleMacOSBuildLogic({
...params,
configuration: params.configuration ?? 'Debug',
}),
);
}
// Register macOS build and run workspace tool
export function registerMacOSBuildAndRunWorkspaceTool(server: McpServer): void {
type WorkspaceParams = {
workspacePath: string;
scheme: string;
configuration?: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
};
registerTool<WorkspaceParams>(
server,
'build_run_mac_ws',
'Builds and runs a macOS app from a workspace in one step.',
{
workspacePath: workspacePathSchema,
scheme: schemeSchema,
configuration: configurationSchema,
derivedDataPath: derivedDataPathSchema,
extraArgs: extraArgsSchema,
},
async (params) =>
_handleMacOSBuildAndRunLogic({
...params,
configuration: params.configuration ?? 'Debug',
}),
);
}
// Register macOS build and run project tool
export function registerMacOSBuildAndRunProjectTool(server: McpServer): void {
type ProjectParams = {
projectPath: string;
scheme: string;
configuration?: string;
derivedDataPath?: string;
arch?: string;
extraArgs?: string[];
};
registerTool<ProjectParams>(
server,
'build_run_mac_proj',
'Builds and runs a macOS app from a project file in one step.',
{
projectPath: projectPathSchema,
scheme: schemeSchema,
configuration: configurationSchema,
derivedDataPath: derivedDataPathSchema,
extraArgs: extraArgsSchema,
},
async (params) =>
_handleMacOSBuildAndRunLogic({
...params,
configuration: params.configuration ?? 'Debug',
}),
);
}