I've been trying a lot to run npx and node commands from swift using the process and task commands but I'm getting permission issues.
Is there a way to resolve it?
Code:
private static func shell(_ command: String) async throws -> String {
let process = Process()
let pipe = Pipe()
let errorPipe = Pipe()
// Set up environment variables
var env = ProcessInfo.processInfo.environment
env["PATH"] = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
process.environment = env
process.executableURL = URL(fileURLWithPath: "/bin/zsh")
process.arguments = ["-l", "-c", command] // -l flag for login shell to get proper environment
process.standardOutput = pipe
process.standardError = errorPipe
do {
try process.run()
let outputData = try pipe.fileHandleForReading.readToEnd() ?? Data()
let errorData = try errorPipe.fileHandleForReading.readToEnd() ?? Data()
let output = String(data: outputData, encoding: .utf8) ?? ""
let errorOutput = String(data: errorData, encoding: .utf8) ?? ""
process.waitUntilExit()
// Improved error handling with more detailed output
guard process.terminationStatus == 0 else {
print("Command failed with status: \(process.terminationStatus)")
print("Standard output: \(output)")
print("Error output: \(errorOutput)")
let errorMessage = errorOutput.isEmpty ? output : errorOutput
throw MCPError.processError(errorMessage)
}
return output.trimmingCharacters(in: .whitespacesAndNewlines)
} catch {
print("Shell command failed: \(error.localizedDescription)")
print("Attempted command: \(command)")
if let mcpError = error as? MCPError {
throw mcpError
}
throw MCPError.processError("Shell execution failed: \(error.localizedDescription)")
}
}
Error:
Shell command failed: The operation couldn’t be completed. (zestmcp.URLSchemeHandler.MCPError error 0.)
Attempted command: node --version