Raycast & Alfred Skill
Master macOS launcher automation with Raycast extensions and Alfred workflows. This skill covers TypeScript-based Raycast development, AppleScript/Python Alfred workflows, keyboard shortcuts, clipboard management, and productivity automation patterns.
When to Use This Skill
USE when:
- Building quick access tools for developer workflows
- Automating repetitive macOS tasks
- Creating custom search commands
- Building clipboard history managers
- Implementing text snippet expansion
- Creating project launchers and switchers
- Building API query tools
- Automating application control
- Creating custom keyboard shortcuts
- Building team productivity tools
DON'T USE when:
- Cross-platform automation needed (use shell scripts)
- Server-side automation (use cron/systemd)
- GUI testing automation (use Playwright/Selenium)
- Windows/Linux environments
- Heavy computation tasks (use proper CLI tools)
Prerequisites
Raycast Setup
brew install --cask raycast
brew install node
npm install -g @raycast/api
npx create-raycast-extension --name my-extension
cd my-extension
npm install
npm run dev
Alfred Setup
brew install --cask alfred
Development Environment
npm install -g typescript @types/node
pip install alfred-workflow
brew install --cask script-debugger
brew install jq
Core Capabilities
1. Raycast Script Commands
#!/bin/bash
PROJECT="$1"
PROJECT_DIR="$HOME/projects/$PROJECT"
if [ -d "$PROJECT_DIR" ]; then
code "$PROJECT_DIR"
echo "Opened $PROJECT"
else
echo "Project not found: $PROJECT"
exit 1
fi
#!/bin/bash
cd "$(pwd)" || exit 1
if [ -d ".git" ]; then
echo "Branch: $(git branch --show-current)"
echo ""
echo "Status:"
git status --short
echo ""
echo "Recent commits:"
git log --oneline -5
else
echo "Not a git repository"
exit 1
fi
import uuid
import subprocess
import sys
format_type = sys.argv[1] if len(sys.argv) > 1 else "standard"
new_uuid = str(uuid.uuid4())
if format_type == "nodash":
new_uuid = new_uuid.replace("-", "")
elif format_type == "upper":
new_uuid = new_uuid.upper()
subprocess.run(["pbcopy"], input=new_uuid.encode(), check=True)
print(f"Copied: {new_uuid}")
#!/bin/bash
PORT="$1"
PID=$(lsof -ti:$PORT 2>/dev/null)
if [ -z "$PID" ]; then
echo "No process on port $PORT"
exit 0
fi
kill -9 $PID 2>/dev/null
if [ $? -eq 0 ]; then
echo "Killed process $PID on port $PORT"
else
echo "Failed to kill process on port $PORT"
exit 1
fi
2. Raycast TypeScript Extensions
import {
ActionPanel,
Action,
List,
Icon,
LocalStorage,
showToast,
Toast,
getPreferenceValues,
} from "@raycast/api";
import { useState, useEffect } from "react";
import { exec } from "child_process";
import { promisify } from "util";
import fs from "fs";
import path from "path";
const execAsync = promisify(exec);
interface Preferences {
projectsDir: string;
editor: string;
}
interface Project {
name: string;
path: string;
lastOpened?: number;
isFavorite?: boolean;
}
export default function Command() {
const [projects, setProjects] = useState<[]>([]);
[isLoading, setIsLoading] = ();
preferences = getPreferenceValues<>();
( {
();
}, []);
() {
{
projectsDir = preferences..(, process.. || );
dirs = fs.(projectsDir, { : });
favoritesJson = .<>();
recentJson = .<>();
favorites = favoritesJson ? .(favoritesJson) : [];
recent = recentJson ? .(recentJson) : {};
: [] = dirs
.( dir.() && !dir..())
.( ({
: dir.,
: path.(projectsDir, dir.),
: recent[dir.] || ,
: favorites.(dir.),
}))
.( {
(a. && !b.) -;
(!a. && b.) ;
(b. || ) - (a. || );
});
(projectList);
} (error) {
({
: ..,
: ,
: (error),
});
} {
();
}
}
() {
{
editor = preferences. || ;
();
recentJson = .<>();
recent = recentJson ? .(recentJson) : {};
recent[project.] = .();
.(, .(recent));
({
: ..,
: ,
});
} (error) {
({
: ..,
: ,
: (error),
});
}
}
() {
favoritesJson = .<>();
favorites = favoritesJson ? .(favoritesJson) : [];
(project.) {
index = favorites.(project.);
(index > -) favorites.(index, );
} {
favorites.(project.);
}
.(, .(favorites));
();
}
(
);
}
import {
ActionPanel,
Action,
List,
Icon,
showToast,
Toast,
getPreferenceValues,
} from "@raycast/api";
import { useState } from "react";
import fetch from "node-fetch";
interface Preferences {
githubToken: string;
}
interface Repository {
id: number;
full_name: string;
description: string | null;
html_url: string;
stargazers_count: number;
language: string | null;
updated_at: string;
}
export default function Command() {
const [results, setResults] = useState<Repository[]>([]);
const [isLoading, setIsLoading] = useState(false);
const preferences = getPreferenceValues<>();
() {
(!query || query. < ) {
([]);
;
}
();
{
response = (
,
{
: {
: ,
: ,
},
}
);
(!response.) {
();
}
data = ( response.()) { : [] };
(data. || []);
} (error) {
({
: ..,
: ,
: (error),
});
} {
();
}
}
(
);
}
import {
ActionPanel,
Action,
List,
Icon,
Clipboard,
LocalStorage,
showToast,
Toast,
} from "@raycast/api";
import { useState, useEffect } from "react";
interface ClipboardItem {
id: string;
content: string;
timestamp: number;
type: "text" | "url" | "code";
}
const MAX_ITEMS = 100;
export default function Command() {
const [items, setItems] = useState<ClipboardItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
loadHistory();
}, []);
async function loadHistory() {
try {
const historyJson = .<>();
history = historyJson ? .(historyJson) : [];
(history);
} (error) {
.(, error);
} {
();
}
}
() {
.(item.);
({ : .., : });
}
() {
newItems = items.( i. !== item.);
.(, .(newItems));
(newItems);
}
() {
.(, .([]));
([]);
({ : .., : });
}
(): | | {
(content.()) ;
(content.() && (content.() || content.()))
;
;
}
() {
() {
:
.;
:
.;
:
.;
}
}
(): {
now = .();
diff = now - ts;
(diff < ) ;
(diff < ) ;
(diff < ) ;
(ts).();
}
(
);
}
3. Alfred Workflows - AppleScript
-- workflow-launcher.applescript
-- ABOUTME: Launch applications with Alfred
-- ABOUTME: AppleScript for application control
on alfred_script(q)
set appName to q
if appName is "" then
return "No application specified"
end if
try
tell application appName
activate
end tell
return "Launched " & appName
on error errMsg
return "Error: " & errMsg
end try
end alfred_script
-- window-manager.applescript
-- ABOUTME: Window positioning and management
-- ABOUTME: Move and resize windows with Alfred
on alfred_script(q)
-- Parse command: "left", "right", "top", "bottom", "maximize", "center"
set position to q
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application "Finder"
set screenBounds to bounds of window of desktop
set screenWidth to item 3 of screenBounds
set screenHeight to item 4 of screenBounds
end tell
-- Menu bar offset
set menuBarHeight to 25
tell application frontApp
if position is "left" then
set bounds of front window to {0, menuBarHeight, screenWidth / 2, screenHeight}
else if position is "right" then
set bounds of front window to {screenWidth / 2, menuBarHeight, screenWidth, screenHeight}
else if position is "top" then
set bounds of front window to {0, menuBarHeight, screenWidth, screenHeight / 2}
else if position is "bottom" then
set bounds of front window to {0, screenHeight / 2, screenWidth, screenHeight}
else if position is "maximize" then
set bounds of front window to {0, menuBarHeight, screenWidth, screenHeight}
else if position is "center" then
set winWidth to 1200
set winHeight to 800
set xPos to (screenWidth - winWidth) / 2
set yPos to ((screenHeight - winHeight) / 2) + menuBarHeight
set bounds of front window to {xPos, yPos, xPos + winWidth, yPos + winHeight}
end if
end tell
return "Moved " & frontApp & " to " & position
end alfred_script
-- clipboard-cleaner.applescript
-- ABOUTME: Clean and transform clipboard content
-- ABOUTME: Remove formatting, convert text
on alfred_script(q)
-- Get clipboard content
set clipContent to the clipboard
if q is "plain" then
-- Convert to plain text
set the clipboard to clipContent as text
return "Converted to plain text"
else if q is "trim" then
-- Trim whitespace
set trimmed to do shell script "echo " & quoted form of clipContent & " | xargs"
set the clipboard to trimmed
return "Trimmed whitespace"
else if q is "lower" then
-- Convert to lowercase
set lowered to do shell script "echo " & quoted form of clipContent & " | tr '[:upper:]' '[:lower:]'"
set the clipboard to lowered
return "Converted to lowercase"
else if q is "upper" then
-- Convert to uppercase
set uppered to do shell script "echo " & quoted form of clipContent & " | tr '[:lower:]' '[:upper:]'"
set the clipboard to uppered
return "Converted to uppercase"
else if q is "slug" then
-- Convert to URL slug
set slugged to do shell script "echo " & quoted form of clipContent & " | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd '[:alnum:]-'"
set the clipboard to slugged
return "Converted to slug: " & slugged
end if
return "Unknown command: " & q
end alfred_script
4. Alfred Workflows - Python
import sys
import json
import urllib.request
import urllib.parse
import os
def search_github(query):
"""Search GitHub repositories"""
if not query or len(query) < 2:
return []
token = os.environ.get("GITHUB_TOKEN", "")
url = f"https://api.github.com/search/repositories?q={urllib.parse.quote(query)}&sort=stars&per_page=10"
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "Alfred-GitHub-Search",
}
if token:
headers["Authorization"] = f"token {token}"
request = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(request) as response:
data = json.loads(response.read().decode())
return data.get("items", [])
except Exception as e:
return []
def format_alfred_results(repos):
"""Format results for Alfred JSON output"""
items = []
for repo repos:
items.append({
: (repo[]),
: repo[],
: ,
: repo[],
: {
:
},
: {
: {
: ,
:
},
: {
: repo[],
:
}
}
})
{: items}
__name__ == :
query = sys.argv[] (sys.argv) >
repos = search_github(query)
result = format_alfred_results(repos)
(json.dumps(result))
import sys
import json
import urllib.request
import urllib.parse
import base64
import os
JIRA_BASE_URL = os.environ.get("JIRA_URL", "https://your-company.atlassian.net")
JIRA_EMAIL = os.environ.get("JIRA_EMAIL", "")
JIRA_API_TOKEN = os.environ.get("JIRA_API_TOKEN", "")
def search_jira(query):
"""Search JIRA issues"""
if not query:
return []
jql = f'text ~ "{query}" ORDER BY updated DESC'
url = f"{JIRA_BASE_URL}/rest/api/3/search?jql={urllib.parse.quote(jql)}&maxResults=10"
auth = base64.b64encode(f"{JIRA_EMAIL}:{JIRA_API_TOKEN}".encode()).decode()
headers = {
"Accept": "application/json",
"Authorization": f"Basic {auth}",
}
request = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(request) as response:
data = json.loads(response.read().decode())
return data.get("issues", [])
except Exception e:
[]
():
items = []
status_icons = {
: ,
: ,
: ,
: ,
}
issue issues:
fields = issue[]
status = fields.get(, {}).get(, )
icon = status_icons.get(status, )
items.append({
: issue[],
: ,
: ,
: ,
: {: },
: {
: {
: issue[],
:
}
}
})
{: items}
__name__ == :
query = sys.argv[] (sys.argv) >
issues = search_jira(query)
result = format_alfred_results(issues)
(json.dumps(result))
import sys
import json
import os
import hashlib
from pathlib import Path
SNIPPETS_DIR = Path.home() / ".alfred-snippets"
SNIPPETS_DIR.mkdir(exist_ok=True)
def load_snippets():
"""Load all snippets"""
snippets = []
for file in SNIPPETS_DIR.glob("*.json"):
with open(file) as f:
snippet = json.load(f)
snippet["file"] = str(file)
snippets.append(snippet)
return sorted(snippets, key=lambda x: x.get("uses", 0), reverse=True)
def save_snippet(name, content, tags=None):
"""Save a new snippet"""
snippet_id = hashlib.md5(name.encode()).hexdigest()[:8]
snippet = {
"id": snippet_id,
"name": name,
"content": content,
"tags": tags or [],
"uses": 0,
}
with open(SNIPPETS_DIR / f"{snippet_id}.json", ) f:
json.dump(snippet, f, indent=)
snippet
():
snippet[] = snippet.get(, ) +
(snippet[], ) f:
json.dump({k: v k, v snippet.items() k != }, f, indent=)
():
snippets = load_snippets()
query:
snippets
query_lower = query.lower()
[
s s snippets
query_lower s[].lower()
(query_lower tag.lower() tag s.get(, []))
]
():
items = []
snippet snippets:
tags = .join(snippet.get(, []))
preview = snippet[][:] + (snippet[]) > snippet[]
items.append({
: snippet[],
: snippet[],
: ,
: snippet[],
: {: },
: {
: snippet[],
: snippet[]
},
: {
: snippet.get(, )
}
})
{: items}
__name__ == :
query = sys.argv[] (sys.argv) >
query.startswith():
parts = query[:].split()
(parts) >= :
name, content = parts[], parts[]
tags = parts[].split() (parts) > []
snippet = save_snippet(name, content, tags)
(json.dumps({: [{: , : }]}))
sys.exit()
snippets = search_snippets(query)
result = format_alfred_results(snippets)
(json.dumps(result))
5. Raycast Extension - API Integration
import {
ActionPanel,
Action,
Form,
showToast,
Toast,
Clipboard,
Detail,
useNavigation,
} from "@raycast/api";
import { useState } from "react";
import fetch from "node-fetch";
interface RequestResult {
status: number;
statusText: string;
headers: Record<string, string>;
body: string;
time: number;
}
function ResultView({ result }: { result: RequestResult }) {
const markdown = `
# Response
**Status:** ${result.status} ${result.statusText}
**Time:** ${result.time}ms
## Headers
\`\`\`json
${JSON.stringify(result.headers, null, 2)}
\`\`\`
## Body
\`\`\`json
${result.body}
\`\`\`
`;
return (
<Detail
markdown={markdown}
=
<>
}
/>
);
}
() {
[method, setMethod] = ();
[url, setUrl] = ();
[headers, setHeaders] = ();
[body, setBody] = ();
[isLoading, setIsLoading] = ();
{ push } = ();
() {
(!url) {
({ : .., : });
;
}
();
startTime = .();
{
: <, > = {};
(headers) {
headers.().( {
[key, ...valueParts] = line.();
(key && valueParts.) {
headerObj[key.()] = valueParts.().();
}
});
}
: = {
method,
: headerObj,
};
(body && [, , ].(method)) {
options. = body;
(!headerObj[]) {
headerObj[] = ;
}
}
response = (url, options);
responseBody = response.();
endTime = .();
: <, > = {};
response..( {
responseHeaders[key] = value;
});
formattedBody = responseBody;
{
formattedBody = .(.(responseBody), , );
} {
}
: = {
: response.,
: response.,
: responseHeaders,
: formattedBody,
: endTime - startTime,
};
();
} (error) {
({
: ..,
: ,
: (error),
});
} {
();
}
}
(
);
}
6. Keyboard Shortcuts and Snippets
{
"snippets": [
{
"name": "Python main block",
"keyword": "pymain",
"text": "if __name__ == \"__main__\":\n main()"
},
{
"name": "TypeScript async function",
"keyword": "tsasync",
"text": "async function ${1:functionName}(${2:params}): Promise<${3:void}> {\n $0\n}"
},
{
"name": "React component",
"keyword": "rcomp",
"text": "import React from 'react';\n\ninterface ${1:Component}Props {\n $2\n}\n\nexport function ${1:Component}({ $3 }: ${1:Component}Props) {\n return (\n <div>\n $0\n </div>\n );\n}"
},
{
-- alfred-hotkey-actions.applescript
-- ABOUTME: Global hotkey actions
-- ABOUTME: Quick actions for common tasks
on alfred_script(q)
-- q contains the action to perform
if q is "screenshot-region" then
do shell script "screencapture -i ~/Desktop/screenshot-$(date +%Y%m%d-%H%M%S).png"
return "Screenshot saved to Desktop"
else if q is "toggle-dark-mode" then
tell application "System Events"
tell appearance preferences
set dark mode to not dark mode
end tell
end tell
return "Toggled dark mode"
else if q is "empty-trash" then
tell application "Finder"
empty trash
end tell
return "Trash emptied"
else if q is "show-hidden" then
do shell script "defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder"
return "Hidden files visible"
else if q is "hide-hidden" then
do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder"
return "Hidden files hidden"
else if q is "flush-dns" then
do shell script "sudo dscacheutil -flushcache && sudo killall -HUP mDNSResponder" with administrator privileges
return "DNS cache flushed"
else if q is "ip-address" then
set localIP to do shell script "ipconfig getifaddr en0"
set publicIP to do shell script "curl -s ifconfig.me"
set the clipboard to publicIP
return "Local: " & localIP & " | Public: " & publicIP & " (copied)"
end if
return "Unknown action: " & q
end alfred_script
Integration Examples
Project Switcher Integration
import {
ActionPanel,
Action,
List,
Icon,
LocalStorage,
getPreferenceValues,
} from "@raycast/api";
import { useState, useEffect } from "react";
import { exec } from "child_process";
import { promisify } from "util";
import fs from "fs";
import path from "path";
const execAsync = promisify(exec);
interface Preferences {
projectDirs: string;
githubEnabled: boolean;
gitlabEnabled: boolean;
}
interface Project {
name: string;
path: string;
source: "local" | "github" | "gitlab";
url?: string;
lastAccessed?: number;
}
export default () {
[projects, setProjects] = useState<[]>([]);
[isLoading, setIsLoading] = ();
preferences = getPreferenceValues<>();
( {
();
}, []);
() {
: [] = [];
dirs = preferences..().( d.());
( dir dirs) {
expandedDir = dir.(, process.. || );
(fs.(expandedDir)) {
entries = fs.(expandedDir, { : });
( entry entries) {
(entry.() && !entry..()) {
allProjects.({
: entry.,
: path.(expandedDir, entry.),
: ,
});
}
}
}
}
accessJson = .<>();
accessTimes = accessJson ? .(accessJson) : {};
allProjects.( {
p. = accessTimes[p.] || ;
});
allProjects.( (b. || ) - (a. || ));
(allProjects);
();
}
() {
cmd =
app ===
?
: app ===
?
: ;
(cmd);
accessJson = .<>();
accessTimes = accessJson ? .(accessJson) : {};
accessTimes[project.] = .();
.(, .(accessTimes));
}
sourceIcons = {
: .,
: .,
: .,
};
(
);
}
Best Practices
1. Raycast Extension Development
import { showToast, Toast } from "@raycast/api";
async function safeFetch(url: string) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
} catch (error) {
showToast({
style: Toast.Style.Failure,
title: "Request failed",
message: String(error),
});
return null;
}
}
import { LocalStorage } from "@raycast/api";
async function saveData(key: string, data: any) {
await LocalStorage.setItem(key, JSON.(data));
}
loadData<T>(: , : T): <T> {
json = .<>(key);
json ? .(json) : defaultValue;
}
2. Alfred Workflow Best Practices
import json
import sys
def output_items(items):
"""Output Alfred JSON format"""
print(json.dumps({"items": items}))
def output_error(message):
"""Output error as Alfred item"""
output_items([{
"title": "Error",
"subtitle": message,
"icon": {"path": "error.png"}
}])
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
output_error(str(e))
sys.exit(1)
3. Performance Optimization
import { useState, useCallback } from "react";
import { useDebouncedValue } from "@raycast/utils";
function SearchCommand() {
const [query, setQuery] = useState("");
const debouncedQuery = useDebouncedValue(query, 300);
}
const cache = new Map<string, { data: any; timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000;
async function cachedFetch(url: string) {
const cached = cache.get(url);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const data = await fetch(url).then( r.());
cache.(url, { data, : .() });
data;
}
Troubleshooting
Common Issues
Issue: Raycast extension not loading
rm -rf ~/Library/Caches/com.raycast.macos
cd your-extension
npm run build
npm run lint
Issue: Alfred workflow not executing
chmod +x workflow-script.sh
./workflow-script.sh "test query"
Issue: AppleScript permissions
-- Grant accessibility permissions
-- System Preferences > Security & Privacy > Privacy > Accessibility
-- Test permissions
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
Debug Commands
./script.sh "test argument"
python3 workflow.py "test query" | jq
echo $alfred_workflow_data
log stream --predicate 'subsystem == "com.raycast.macos"'
Version History
| Version | Date | Changes |
|---|
| 1.0.0 | 2026-01-17 | Initial release with Raycast and Alfred patterns |
Resources
This skill provides production-ready patterns for macOS launcher automation, enabling keyboard-driven productivity and seamless workflow integration.