Skip to main content
Glama
sailay1996

Cursor Agent MCP Server

by sailay1996

cursor_agent_search_repo

Search repository code using query terms with customizable include/exclude filters to locate specific code patterns and files efficiently.

Instructions

Search repository code with include/exclude patterns. Prompt-based wrapper.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
includeNo
excludeNo
output_formatNotext
extra_argsNo
cwdNo
executableNo
modelNo
forceNo
echo_promptNo

Implementation Reference

  • The handler function composes a prompt from the query, include, and exclude parameters and invokes the shared runCursorAgent executor to perform the repo search via the cursor-agent CLI.
    async (args) => {
      try {
        const { query, include, exclude, output_format, cwd, executable, model, force, extra_args } = args;
        const inc = include == null ? [] : (Array.isArray(include) ? include : [include]);
        const exc = exclude == null ? [] : (Array.isArray(exclude) ? exclude : [exclude]);
        const composedPrompt =
          `Search the repository for occurrences relevant to:\n` +
          `- Query: ${String(query)}\n` +
          (inc.length ? `- Include globs:\n${inc.map((p)=>`  - ${String(p)}`).join('\n')}\n` : '') +
          (exc.length ? `- Exclude globs:\n${exc.map((p)=>`  - ${String(p)}`).join('\n')}\n` : '') +
          `Return concise findings with file paths and line references.`;
        return await runCursorAgent({ prompt: composedPrompt, output_format, extra_args, cwd, executable, model, force });
      } catch (e) {
        return { content: [{ type: 'text', text: `Invalid params: ${e?.message || e}` }], isError: true };
      }
    },
  • Zod schema defining the input parameters: required 'query' string, optional 'include' and 'exclude' as string or array of globs, plus shared COMMON fields like output_format, model, etc.
    const SEARCH_REPO_SCHEMA = z.object({
      query: z.string().min(1, 'query is required'),
      include: z.union([z.string(), z.array(z.string())]).optional(),
      exclude: z.union([z.string(), z.array(z.string())]).optional(),
      ...COMMON,
    });
  • server.js:339-359 (registration)
    Registration of the 'cursor_agent_search_repo' tool on the MCP server, providing name, description, schema, and inline handler function.
    server.tool(
      'cursor_agent_search_repo',
      'Search repository code with include/exclude patterns. Prompt-based wrapper.',
      SEARCH_REPO_SCHEMA.shape,
      async (args) => {
        try {
          const { query, include, exclude, output_format, cwd, executable, model, force, extra_args } = args;
          const inc = include == null ? [] : (Array.isArray(include) ? include : [include]);
          const exc = exclude == null ? [] : (Array.isArray(exclude) ? exclude : [exclude]);
          const composedPrompt =
            `Search the repository for occurrences relevant to:\n` +
            `- Query: ${String(query)}\n` +
            (inc.length ? `- Include globs:\n${inc.map((p)=>`  - ${String(p)}`).join('\n')}\n` : '') +
            (exc.length ? `- Exclude globs:\n${exc.map((p)=>`  - ${String(p)}`).join('\n')}\n` : '') +
            `Return concise findings with file paths and line references.`;
          return await runCursorAgent({ prompt: composedPrompt, output_format, extra_args, cwd, executable, model, force });
        } catch (e) {
          return { content: [{ type: 'text', text: `Invalid params: ${e?.message || e}` }], isError: true };
        }
      },
    );
  • Shared helper function that normalizes arguments and spawns the cursor-agent CLI process, used by all tools including search_repo.
    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;
    }
  • Low-level helper that spawns the cursor-agent CLI subprocess, handles output capture, timeouts, and error conditions; called by runCursorAgent.
    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,
           });
         }
       });
     });
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but offers minimal information. It mentions 'Prompt-based wrapper' which hints at some AI/LLM interaction, but doesn't explain what this entails—such as whether it uses external APIs, has rate limits, requires authentication, or how it handles errors. For a tool with 10 parameters and no annotation coverage, this leaves critical behavioral traits undocumented.

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 with only two short phrases, making it front-loaded and efficient. However, the second phrase 'Prompt-based wrapper' is ambiguous and doesn't add clear value, slightly reducing its effectiveness. Overall, it avoids unnecessary verbosity but could be more informative.

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 the complexity of 10 parameters, 0% schema coverage, no annotations, and no output schema, the description is incomplete. It doesn't explain the tool's behavior, return values, error handling, or most parameter meanings. For a search tool with many configuration options, this leaves too many gaps for an agent to use it effectively.

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%, meaning none of the 10 parameters have descriptions in the schema. The tool description only vaguely references 'include/exclude patterns' and 'Prompt-based wrapper', which partially relates to 'include', 'exclude', and possibly 'model' or 'extra_args', but fails to explain most parameters like 'cwd', 'executable', 'force', 'echo_prompt', or the specifics of 'output_format'. This doesn't adequately compensate for the lack of schema documentation.

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 'Search repository code with include/exclude patterns' which provides a basic verb+resource combination, but it's vague about what 'Prompt-based wrapper' means and doesn't clearly distinguish this search functionality from potential sibling tools like cursor_agent_analyze_files or cursor_agent_raw. The purpose is understandable but lacks specificity about scope and differentiation.

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?

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention any context, prerequisites, or exclusions, nor does it reference sibling tools. An agent would have to guess based on tool names alone, which is insufficient for informed selection.

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