Skip to main content
Glama

system_get_frontmost_app

Retrieve the name of the currently active application on macOS to identify what program is in focus for automation or monitoring tasks.

Instructions

[System control and information] Get the name of the frontmost application

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler implementation: AppleScript code that retrieves the name of the currently frontmost application using System Events.
    {
      name: "get_frontmost_app",
      description: "Get the name of the frontmost application",
      script:
        'tell application "System Events" to get name of first process whose frontmost is true',
    },
  • Tool registration in listTools handler: constructs tool name as 'system_get_frontmost_app' from category 'system' and script 'get_frontmost_app'.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: this.categories.flatMap((category) =>
        category.scripts.map((script) => ({
          name: `${category.name}_${script.name}`, // Changed from dot to underscore
          description: `[${category.description}] ${script.description}`,
          inputSchema: script.schema || {
            type: "object",
            properties: {},
          },
        })),
      ),
    }));
  • src/index.ts:2-25 (registration)
    Imports and registers the 'system' category containing the 'get_frontmost_app' script definition.
    import { systemCategory } from "./categories/system.js";
    import { calendarCategory } from "./categories/calendar.js";
    import { finderCategory } from "./categories/finder.js";
    import { clipboardCategory } from "./categories/clipboard.js";
    import { notificationsCategory } from "./categories/notifications.js";
    import { itermCategory } from "./categories/iterm.js";
    import { mailCategory } from "./categories/mail.js";
    import { pagesCategory } from "./categories/pages.js";
    import { shortcutsCategory } from "./categories/shortcuts.js";
    import { messagesCategory } from "./categories/messages.js";
    import { notesCategory } from "./categories/notes.js";
    
    const server = new AppleScriptFramework({
      name: "applescript-server",
      version: "1.0.4",
      debug: false,
    });
    
    // Log startup information using stderr (server isn't connected yet)
    console.error(`[INFO] Starting AppleScript MCP server - PID: ${process.pid}`);
    
    // Add all categories
    console.error("[INFO] Registering categories...");
    server.addCategory(systemCategory);
  • Helper function that executes the AppleScript via osascript, used for all tools including system_get_frontmost_app.
    private async executeScript(script: string): Promise<string> {
      // Log script execution (truncate long scripts for readability)
      const scriptPreview = script.length > 100 ? script.substring(0, 100) + "..." : script;
      this.log("debug", "Executing AppleScript", { scriptPreview });
      
      try {
        const startTime = Date.now();
        const { stdout } = await execAsync(
          `osascript -e '${script.replace(/'/g, "'\"'\"'")}'`,
        );
        const executionTime = Date.now() - startTime;
        
        this.log("debug", "AppleScript executed successfully", { 
          executionTimeMs: executionTime,
          outputLength: stdout.length
        });
        
        return stdout.trim();
      } catch (error) {
        // Properly type check the error object
        let errorMessage = "Unknown error occurred";
        if (error && typeof error === "object") {
          if ("message" in error && typeof error.message === "string") {
            errorMessage = error.message;
          } else if (error instanceof Error) {
            errorMessage = error.message;
          }
        } else if (typeof error === "string") {
          errorMessage = error;
        }
        
        this.log("error", "AppleScript execution failed", { 
          error: errorMessage,
          scriptPreview
        });
        
        throw new Error(`AppleScript execution failed: ${errorMessage}`);
      }
    }
  • MCP CallTool request handler: parses 'system_get_frontmost_app', locates script, executes it, and returns result.
    // Handle tool execution
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const toolName = request.params.name;
      this.log("info", "Tool execution requested", { 
        tool: toolName,
        hasArguments: !!request.params.arguments
      });
      
      try {
        // Split on underscore instead of dot
        const [categoryName, ...scriptNameParts] =
          toolName.split("_");
        const scriptName = scriptNameParts.join("_"); // Rejoin in case script name has underscores
    
        const category = this.categories.find((c) => c.name === categoryName);
        if (!category) {
          this.log("warning", "Category not found", { categoryName });
          throw new McpError(
            ErrorCode.MethodNotFound,
            `Category not found: ${categoryName}`,
          );
        }
    
        const script = category.scripts.find((s) => s.name === scriptName);
        if (!script) {
          this.log("warning", "Script not found", { 
            categoryName, 
            scriptName 
          });
          throw new McpError(
            ErrorCode.MethodNotFound,
            `Script not found: ${scriptName}`,
          );
        }
    
        this.log("debug", "Generating script content", { 
          categoryName, 
          scriptName,
          isFunction: typeof script.script === "function"
        });
        
        const scriptContent =
          typeof script.script === "function"
            ? script.script(request.params.arguments)
            : script.script;
    
        const result = await this.executeScript(scriptContent);
        
        this.log("info", "Tool execution completed successfully", { 
          tool: toolName,
          resultLength: result.length
        });
    
        return {
          content: [
            {
              type: "text",
              text: result,
            },
          ],
        };

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/joshrutkowski/applescript-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server