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,
            },
          ],
        };
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool retrieves information ('Get'), implying it is read-only, but does not clarify permissions, potential errors (e.g., if no frontmost app exists), or response format. For a tool with zero annotation coverage, this leaves significant behavioral gaps unaddressed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise and front-loaded, consisting of a single sentence that directly states the tool's purpose. There is no wasted language or redundancy, making it efficient and easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (0 parameters, no output schema), the description is minimally adequate. It explains what the tool does but lacks details on behavioral aspects like error handling or return values. Without annotations or output schema, the description should ideally provide more context, but it meets the basic requirement for a simple read operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters, and schema description coverage is 100%, so no parameter documentation is needed. The description does not add parameter details beyond the schema, but with no parameters, this is acceptable. A baseline of 4 is appropriate as the description does not need to compensate for any parameter gaps.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Get') and resource ('name of the frontmost application'), making the purpose specific and understandable. It distinguishes itself from siblings like 'system_launch_app' or 'system_quit_app' by focusing on information retrieval rather than control. However, it lacks explicit differentiation from other system tools (e.g., 'system_get_battery_status'), which slightly reduces clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It does not mention prerequisites (e.g., needing frontmost app permissions), exclusions, or comparisons to similar tools like 'system_get_battery_status'. Without such context, the agent must infer usage based on the tool name alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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