Skip to main content
Glama

brave_web_search_code_mode

Execute custom JavaScript code on Brave Search API results to extract specific data, reducing context usage by processing raw responses in a secure sandbox.

Instructions

Performs a web search using the Brave Search API, and then runs a custom JavaScript code string against the RAW API RESPONSE in a secure QuickJS sandbox. This drastically reduces context window usage by only returning the output of your script. Use this for broad information gathering, recent events, or when you need diverse web sources and only need specific parts of the result. Your script should read the 'DATA' global variable (a JSON string of the API response), process it, and use console.log() to print the desired output.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query (max 400 chars, 50 words)
countNoNumber of results (1-20, default 10)
offsetNoPagination offset (max 9, default 0)
codeYesJavaScript code to execute against the 'DATA' variable. E.g. `const r = JSON.parse(DATA); console.log(r.web.results.map(x => x.title).join(', '));`
languageNoLanguage of the code. Only 'javascript' is supported.javascript

Implementation Reference

  • The handler function that implements the logic for brave_web_search_code_mode, which performs a web search and then processes the result in a sandboxed JavaScript environment.
    export async function braveWebSearchCodeModeHandler(args: unknown) {
      if (!isBraveWebSearchCodeModeArgs(args)) {
        throw new Error("Invalid arguments for brave_web_search_code_mode");
      }
    
      const { query, count = 10, offset = 0, code, language = "javascript" } = args;
    
      if (language.toLowerCase() !== "javascript") {
        return {
          content: [{ type: "text", text: "Unsupported language. Only 'javascript' is supported." }],
          isError: true,
        };
      }
    
      // 1. Fetch raw data
      console.error(`Fetching web search for code mode: "${query}"`);
      const rawDataStr = await performWebSearchRaw(query, count, offset);
      const beforeSizeKB = (Buffer.byteLength(rawDataStr, 'utf8') / 1024).toFixed(1);
    
      // 2. Run code mode sandbox
      console.error(`Executing code mode sandbox...`);
      const { stdout, error, executionTimeMs } = await runInSandbox(rawDataStr, code);
    
      if (error) {
        return {
          content: [{ type: "text", text: `Sandboxed Execution Failed:\n${error}` }],
          isError: true,
        };
      }
    
      // 3. Compute reduction
      const finalOutput = stdout.trim() || "[No output from script]";
      const afterSizeKB = (Buffer.byteLength(finalOutput, 'utf8') / 1024).toFixed(1);
      const reductionPct = (100 - (Number(afterSizeKB) / Number(beforeSizeKB)) * 100).toFixed(1);
    
      const header = `[code-mode: ${beforeSizeKB}KB -> ${afterSizeKB}KB (${reductionPct}% reduction) in ${executionTimeMs}ms]\n\n`;
    
      return {
        content: [{ type: "text", text: header + finalOutput }],
        isError: false,
      };
    }
  • The MCP tool definition (schema) for brave_web_search_code_mode, including input parameters and tool description.
    export const BRAVE_WEB_SEARCH_CODE_MODE_TOOL: Tool = {
      name: "brave_web_search_code_mode",
      description:
        "Performs a web search using the Brave Search API, and then runs a custom JavaScript code string against the RAW API RESPONSE in a secure QuickJS sandbox. " +
        "This drastically reduces context window usage by only returning the output of your script. " +
        "Use this for broad information gathering, recent events, or when you need diverse web sources and only need specific parts of the result. " +
        "Your script should read the 'DATA' global variable (a JSON string of the API response), process it, and use console.log() to print the desired output.",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "Search query (max 400 chars, 50 words)",

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/dcostenco/BCBA'

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