Merge pull request #231 from modelcontextprotocol/fix/chrome-applescript-json-stringify-interpolation

fix(examples/chrome-applescript): use JSON.stringify for AppleScript string interpolation
This commit is contained in:
Tobin South 2026-04-17 13:04:22 -07:00 • committed by GitHub
commit f9a551bf47
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -33,17 +33,6 @@ class ChromeControlServer {
this.setupHandlers(); this.setupHandlers();
} }
// Helper methods
escapeForAppleScript(str) {
if (typeof str !== "string") return str;
// Basic AppleScript string escaping
return str
.replace(/\\/g, "\\\\") // Escape backslashes first
.replace(/"/g, '\\"') // Then escape double quotes
.replace(/\n/g, "\\n") // Escape newlines
.replace(/\r/g, "\\r"); // Escape carriage returns
}
async checkChromeAvailable() { async checkChromeAvailable() {
try { try {
const script = 'tell application "Google Chrome" to return "available"'; const script = 'tell application "Google Chrome" to return "available"';
@ -289,10 +278,23 @@ class ChromeControlServer {
throw new Error("URL is required and must be a string"); throw new Error("URL is required and must be a string");
} }
const escapedUrl = this.escapeForAppleScript(url); try {
new URL(url);
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: url is not a valid url - ${error.message}`,
},
],
isError: true,
};
}
const script = new_tab const script = new_tab
? `tell application "Google Chrome" to open location "${escapedUrl}"` ? `tell application "Google Chrome" to open location ${JSON.stringify(url)}`
: `tell application "Google Chrome" to set URL of active tab of front window to "${escapedUrl}"`; : `tell application "Google Chrome" to set URL of active tab of front window to ${JSON.stringify(url)}`;
await this.executeAppleScript(script); await this.executeAppleScript(script);
return { return {
@ -644,8 +646,6 @@ class ChromeControlServer {
})(); })();
`; `;
const escapedCode = this.escapeForAppleScript(wrappedCode);
const script = const script =
safeTabId != null safeTabId != null
? ` ? `
@ -653,7 +653,7 @@ class ChromeControlServer {
repeat with w in windows repeat with w in windows
repeat with t in tabs of w repeat with t in tabs of w
if (id of t as string) is "${safeTabId}" then if (id of t as string) is "${safeTabId}" then
set result to execute t javascript "${escapedCode}" set result to execute t javascript ${JSON.stringify(wrappedCode)}
return result return result
end if end if
end repeat end repeat
@ -663,7 +663,7 @@ class ChromeControlServer {
` `
: ` : `
tell application "Google Chrome" tell application "Google Chrome"
execute active tab of front window javascript "${escapedCode}" execute active tab of front window javascript ${JSON.stringify(wrappedCode)}
end tell end tell
`; `;