Skip to main content
Glama
sailay1996

Cursor Agent MCP Server

by sailay1996

cursor_agent_run

Execute cursor-agent CLI commands with prompts to generate text, JSON, or markdown outputs for repository analysis and code tasks.

Instructions

Run cursor-agent with a prompt and desired output format (legacy single-shot).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYes
output_formatNotext
extra_argsNo
cwdNo
executableNo
modelNo
forceNo

Implementation Reference

  • server.js:398-409 (registration)
    Registration of the 'cursor_agent_run' MCP tool, including inline handler that delegates to runCursorAgent.
    server.tool(
     'cursor_agent_run',
     'Run cursor-agent with a prompt and desired output format (legacy single-shot).',
     RUN_SCHEMA.shape,
     async (args) => {
       try {
         return await runCursorAgent(args);
       } catch (e) {
         return { content: [{ type: 'text', text: `Invalid params: ${e?.message || e}` }], isError: true };
       }
     },
    );
  • Zod input schema defining parameters for the cursor_agent_run tool (prompt, output_format, extra_args, etc.).
    const RUN_SCHEMA = z.object({
      prompt: z.string().min(1, 'prompt is required'),
      output_format: z.enum(['text', 'json', 'markdown']).default('text'),
      extra_args: z.array(z.string()).optional(),
      cwd: z.string().optional(),
      // Optional override for the executable path if not on PATH
      executable: z.string().optional(),
      // Optional model and force for parity with other tools/env overrides
      model: z.string().optional(),
      force: z.boolean().optional(),
    });
  • Primary handler logic for cursor_agent_run: processes input, constructs argv with prompt as positional, invokes the agent process, handles echoing.
    // Accepts either a flat args object or an object with an "arguments" field (some hosts).
    async function runCursorAgent(input) {
      const source = (input && typeof input === 'object' && input.arguments && typeof input.prompt === 'undefined')
        ? input.arguments
        : input;
    
      const {
        prompt,
        output_format = 'text',
        extra_args,
        cwd,
        executable,
        model,
        force,
      } = source || {};
    
      const argv = [...(extra_args ?? []), String(prompt)];
      const usedPrompt = argv.length ? String(argv[argv.length - 1]) : '';
     
      // Optional prompt echo and debug diagnostics
      if (process.env.DEBUG_CURSOR_MCP === '1') {
        try {
          const preview = usedPrompt.slice(0, 400).replace(/\n/g, '\\n');
          console.error('[cursor-mcp] prompt:', preview);
          if (extra_args?.length) console.error('[cursor-mcp] extra_args:', JSON.stringify(extra_args));
          if (model) console.error('[cursor-mcp] model:', model);
          if (typeof force === 'boolean') console.error('[cursor-mcp] force:', String(force));
        } catch {}
      }
     
      const result = await invokeCursorAgent({ argv, output_format, cwd, executable, model, force });
     
      // Echo prompt either when env is set or when caller provided echo_prompt: true (if host forwards unknown args it's fine)
      const echoEnabled = process.env.CURSOR_AGENT_ECHO_PROMPT === '1' || source?.echo_prompt === true;
      if (echoEnabled) {
        const text = `Prompt used:\n${usedPrompt}`;
        const content = Array.isArray(result?.content) ? result.content : [];
        return { ...result, content: [{ type: 'text', text }, ...content] };
      }
     
      return result;
    }
  • Core helper function that spawns the cursor-agent CLI process, handles arguments, environment overrides, timeouts, idle kill, and captures output/error.
    async function invokeCursorAgent({ argv, output_format = 'text', cwd, executable, model, force, print = true }) {
     const cmd = resolveExecutable(executable);
    
     // Compute model/force from args/env
     const userArgs = [...(argv ?? [])];
     const hasModelFlag = userArgs.some((a) => a === '-m' || a === '--model' || /^(?:-m=|--model=)/.test(String(a)));
     const envModel = process.env.CURSOR_AGENT_MODEL && process.env.CURSOR_AGENT_MODEL.trim();
     const effectiveModel = model?.trim?.() || envModel;
    
     const hasForceFlag = userArgs.some((a) => a === '-f' || a === '--force');
     const envForce = (() => {
       const v = (process.env.CURSOR_AGENT_FORCE || '').toLowerCase();
       return v === '1' || v === 'true' || v === 'yes' || v === 'on';
     })();
     const effectiveForce = typeof force === 'boolean' ? force : envForce;
    
     const finalArgv = [
       ...(print ? ['--print', '--output-format', output_format] : []),
       ...userArgs,
       ...(hasForceFlag || !effectiveForce ? [] : ['-f']),
       ...(hasModelFlag || !effectiveModel ? [] : ['-m', effectiveModel]),
     ];
    
     return new Promise((resolve) => {
       let settled = false;
       let out = '';
       let err = '';
       let idleTimer = null;
       let killedByIdle = false;
    
       const cleanup = () => {
         if (mainTimer) clearTimeout(mainTimer);
         if (idleTimer) clearTimeout(idleTimer);
       };
    
       if (process.env.DEBUG_CURSOR_MCP === '1') {
         try {
           console.error('[cursor-mcp] spawn:', cmd, ...finalArgv);
         } catch {}
       }
    
       const child = spawn(cmd, finalArgv, {
         shell: false, // safer across platforms; rely on PATH/PATHEXT
         cwd: cwd || process.cwd(),
         env: process.env,
       });
       try { child.stdin?.end(); } catch {}
    
       const idleMs = Number.parseInt(process.env.CURSOR_AGENT_IDLE_EXIT_MS || '0', 10);
       const scheduleIdleKill = () => {
         if (!Number.isFinite(idleMs) || idleMs <= 0) return;
         if (idleTimer) clearTimeout(idleTimer);
         idleTimer = setTimeout(() => {
           killedByIdle = true;
           try { child.kill('SIGKILL'); } catch {}
         }, idleMs);
       };
    
       child.stdout.on('data', (d) => {
         out += d.toString();
         scheduleIdleKill();
       });
    
       child.stderr.on('data', (d) => {
         err += d.toString();
       });
    
       child.on('error', (e) => {
         if (settled) return;
         settled = true;
         cleanup();
         if (process.env.DEBUG_CURSOR_MCP === '1') {
           try { console.error('[cursor-mcp] error:', e); } catch {}
         }
         const msg =
           `Failed to start "${cmd}": ${e?.message || e}\n` +
           `Args: ${JSON.stringify(finalArgv)}\n` +
           (process.env.CURSOR_AGENT_PATH ? `CURSOR_AGENT_PATH=${process.env.CURSOR_AGENT_PATH}\n` : '');
         resolve({ content: [{ type: 'text', text: msg }], isError: true });
       });
    
       const defaultTimeout = 30000;
       const timeoutMs = Number.parseInt(process.env.CURSOR_AGENT_TIMEOUT_MS || String(defaultTimeout), 10);
       const mainTimer = setTimeout(() => {
         try { child.kill('SIGKILL'); } catch {}
         if (settled) return;
         settled = true;
         cleanup();
         resolve({
           content: [{ type: 'text', text: `cursor-agent timed out after ${Number.isFinite(timeoutMs) ? timeoutMs : defaultTimeout}ms` }],
           isError: true,
         });
       }, Number.isFinite(timeoutMs) ? timeoutMs : defaultTimeout);
    
       child.on('close', (code) => {
         if (settled) return;
         settled = true;
         cleanup();
         if (process.env.DEBUG_CURSOR_MCP === '1') {
           try { console.error('[cursor-mcp] exit:', code, 'stdout bytes=', out.length, 'stderr bytes=', err.length); } catch {}
         }
         if (code === 0 || (killedByIdle && out)) {
           resolve({ content: [{ type: 'text', text: out || '(no output)' }] });
         } else {
           resolve({
             content: [{ type: 'text', text: `cursor-agent exited with code ${code}\n${err || out || '(no output)'}` }],
             isError: true,
           });
         }
       });
     });
    }
  • Helper to resolve the cursor-agent executable path from explicit arg, env, or PATH default.
    function resolveExecutable(explicit) {
      if (explicit && explicit.trim()) return explicit.trim();
      if (process.env.CURSOR_AGENT_PATH && process.env.CURSOR_AGENT_PATH.trim()) {
        return process.env.CURSOR_AGENT_PATH.trim();
      }
      // default assumes "cursor-agent" is on PATH
      return 'cursor-agent';
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'legacy single-shot' which hints at behavioral traits (single interaction vs. chat), but doesn't disclose critical details like what 'cursor-agent' does, whether it's read-only or mutating, authentication needs, rate limits, or what 'run' entails. The description is insufficient for a tool with 7 parameters.

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

Conciseness4/5

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

The description is very concise (one sentence) and front-loaded with the core action. However, it's arguably too brief given the tool's complexity, as it omits necessary context for understanding the tool's purpose and parameters.

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

Completeness2/5

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

Given high complexity (7 parameters, 0% schema coverage, no annotations, no output schema), the description is incomplete. It doesn't explain what 'cursor-agent' is, what 'run' does, the meaning of most parameters, or expected return values. The minimal information provided is inadequate for effective tool use.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate. It mentions 'prompt and desired output format', which covers only 2 of 7 parameters (prompt and output_format). It doesn't explain the semantics of extra_args, cwd, executable, model, or force, leaving most parameters undocumented.

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

Purpose3/5

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

The description states the tool 'Run cursor-agent with a prompt and desired output format (legacy single-shot)', which provides a basic verb ('Run') and resource ('cursor-agent') but is vague about what 'cursor-agent' actually does. It distinguishes from some siblings by mentioning 'legacy single-shot', but doesn't clearly differentiate from all alternatives like 'cursor_agent_chat' or 'cursor_agent_raw'.

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 minimal guidance with 'legacy single-shot', implying this is an older or simpler version compared to other tools, but doesn't explicitly state when to use this vs. alternatives like 'cursor_agent_chat' or 'cursor_agent_plan_task'. No exclusions or prerequisites are mentioned.

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/sailay1996/cursor-agent-mcp'

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