Skip to main content
Glama
mohalmah

Google Apps Script MCP Server

by mohalmah

script_projects_get_content

Retrieve the content of a Google Apps Script project by providing its script ID to access code and files for editing or analysis.

Instructions

Get the content of a Google Apps Script project.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptIdYesThe ID of the script project to retrieve content for.
versionNumberNoThe version number of the script project.
fieldsNoSelector specifying which fields to include in a partial response.
altNoData format for response.
keyNoAPI key for the project.
access_tokenNoOAuth access token.
prettyPrintNoReturns response with indentations and line breaks.

Implementation Reference

  • The main handler function that performs the HTTP GET request to retrieve the content of a Google Apps Script project using OAuth authentication.
    const executeFunction = async ({ scriptId, versionNumber, fields, alt = "json", key, access_token, prettyPrint = "true" }) => {
      const baseUrl = 'https://script.googleapis.com';
      const startTime = Date.now();
      
      try {
        logger.info('SCRIPT_GET_CONTENT', 'Starting script content retrieval', { scriptId, versionNumber });
    
        // Get OAuth access token
        const token = await getOAuthAccessToken();
        
        // Construct the URL with query parameters
        const url = new URL(`${baseUrl}/v1/projects/${scriptId}/content`);
        if (versionNumber) url.searchParams.append('versionNumber', versionNumber);
        if (fields) url.searchParams.append('fields', fields);
        url.searchParams.append('alt', alt);
        if (key) url.searchParams.append('key', key);
        if (prettyPrint) url.searchParams.append('prettyPrint', prettyPrint);
    
        logger.debug('SCRIPT_GET_CONTENT', 'Constructed API URL', {
          url: url.toString(),
          pathSegments: url.pathname.split('/'),
          queryParams: Object.fromEntries(url.searchParams)
        });
    
        // Set up headers for the request
        const headers = {
          'Accept': 'application/json',
          'Authorization': `Bearer ${token}`
        };
    
        logger.logAPICall('GET', url.toString(), headers);
    
        // Perform the fetch request
        const fetchStartTime = Date.now();
        const response = await fetch(url.toString(), {
          method: 'GET',
          headers
        });
        
        const fetchDuration = Date.now() - fetchStartTime;
        const responseSize = response.headers.get('content-length') || 'unknown';
        
        logger.logAPIResponse('GET', url.toString(), response.status, fetchDuration, responseSize);
    
        // Check if the response was successful
        if (!response.ok) {
          const errorText = await response.text();
          let errorData;
          
          try {
            errorData = JSON.parse(errorText);
          } catch (parseError) {
            errorData = { message: errorText };
          }
    
          const detailedError = {
            status: response.status,
            statusText: response.statusText,
            url: url.toString(),
            errorResponse: errorData,
            duration: Date.now() - startTime,
            scriptId,
            versionNumber,
            timestamp: new Date().toISOString()
          };
    
          logger.error('SCRIPT_GET_CONTENT', 'API request failed', detailedError);
          
          console.error('❌ API Error Details:', JSON.stringify(detailedError, null, 2));
          
          throw new Error(`API Error (${response.status}): ${errorData.error?.message || errorData.message || 'Unknown error'}`);
        }
    
        // Parse and return the response data
        const data = await response.json();
        
        logger.info('SCRIPT_GET_CONTENT', 'Successfully retrieved script content', {
          scriptId,
          versionNumber,
          filesCount: data.files?.length || 0,
          duration: Date.now() - startTime
        });
        
        console.log('✅ Successfully retrieved script content');
        return data;
      } catch (error) {
        const errorDetails = {
          message: error.message,
          stack: error.stack,
          scriptId,
          versionNumber,
          duration: Date.now() - startTime,
          timestamp: new Date().toISOString(),
          errorType: error.name || 'Unknown'
        };
    
        logger.error('SCRIPT_GET_CONTENT', 'Error getting script project content', errorDetails);
        
        console.error('❌ Error getting script project content:', errorDetails);
        
        // Return detailed error information for debugging
        return { 
          error: true,
          message: error.message,
          details: errorDetails,
          rawError: {
            name: error.name,
            stack: error.stack
          }
        };
      }
    };
  • Defines the MCP tool schema, including the function name, description, parameters (with scriptId required), and references the handler function.
    const apiTool = {
      function: executeFunction,
      definition: {
        type: 'function',
        function: {
          name: 'script_projects_get_content',
          description: 'Get the content of a Google Apps Script project.',
          parameters: {
            type: 'object',
            properties: {
              scriptId: {
                type: 'string',
                description: 'The ID of the script project to retrieve content for.'
              },
              versionNumber: {
                type: 'string',
                description: 'The version number of the script project.'
              },
              fields: {
                type: 'string',
                description: 'Selector specifying which fields to include in a partial response.'
              },
              alt: {
                type: 'string',
                description: 'Data format for response.'
              },
              key: {
                type: 'string',
                description: 'API key for the project.'
              },
              access_token: {
                type: 'string',
                description: 'OAuth access token.'
              },
              prettyPrint: {
                type: 'string',
                description: 'Returns response with indentations and line breaks.'
              }
            },
            required: ['scriptId']
          }
        }
      }
    };
    
    export { apiTool };
  • tools/paths.js:14-14 (registration)
    The tool file path is listed in toolPaths array, enabling dynamic import and registration during tool discovery.
    'google-app-script-api/apps-script-api/script-projects-get-content.js',
  • lib/tools.js:8-64 (registration)
    The discoverTools function dynamically imports and registers all tools, including script_projects_get_content, by loading modules from toolPaths and extracting their apiTool.
    export async function discoverTools() {
      logger.info('DISCOVERY', `Starting tool discovery for ${toolPaths.length} tool paths`);
      
      const toolPromises = toolPaths.map(async (file) => {
        try {
          logger.debug('DISCOVERY', `Loading tool from: ${file}`);
          const module = await import(`../tools/${file}`);
          
          if (!module.apiTool) {
            logger.warn('DISCOVERY', `Tool file missing apiTool export: ${file}`);
            return null;
          }
    
          const toolName = module.apiTool.definition?.function?.name;
          if (!toolName) {
            logger.warn('DISCOVERY', `Tool missing function name: ${file}`);
            return null;
          }
    
          // Wrap the original function with logging
          const originalFunction = module.apiTool.function;
          const wrappedFunction = withLogging(toolName, originalFunction);
    
          logger.debug('DISCOVERY', `Successfully loaded tool: ${toolName}`, {
            file,
            toolName,
            description: module.apiTool.definition?.function?.description
          });
    
          return {
            ...module.apiTool,
            function: wrappedFunction,
            path: file,
          };
        } catch (error) {
          logger.error('DISCOVERY', `Failed to load tool: ${file}`, {
            file,
            error: {
              message: error.message,
              stack: error.stack
            }
          });
          return null;
        }
      });
      
      const tools = (await Promise.all(toolPromises)).filter(Boolean);
      
      logger.info('DISCOVERY', `Tool discovery completed`, {
        totalPaths: toolPaths.length,
        successfullyLoaded: tools.length,
        failed: toolPaths.length - tools.length,
        toolNames: tools.map(t => t.definition?.function?.name).filter(Boolean)
      });
      
      return tools;
    }
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 for behavioral disclosure. It states it 'gets' content, implying a read-only operation, but doesn't mention authentication requirements (though parameters suggest OAuth or API key), rate limits, error conditions, or what format the content returns (e.g., code files, JSON). For a tool with 7 parameters and no output schema, this is a significant gap in transparency.

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 a single, clear sentence that efficiently conveys the core action without unnecessary words. It's front-loaded with the essential information ('Get the content'), making it easy to parse quickly, which is ideal for conciseness in tool definitions.

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 (7 parameters, no annotations, no output schema), the description is insufficiently complete. It doesn't explain what 'content' entails (e.g., source code, project structure), how authentication works despite parameters suggesting it, or return values, leaving the agent under-informed for effective use in a broader context with many sibling tools.

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

Parameters3/5

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

Schema description coverage is 100%, with all parameters well-documented in the schema itself (e.g., scriptId, versionNumber, fields). The description adds no additional parameter semantics beyond implying retrieval of 'content,' which aligns with the schema but doesn't provide extra context like default behaviors or parameter interactions. This meets the baseline for high schema coverage.

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 verb ('Get') and resource ('content of a Google Apps Script project'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'script_projects_get' (which might get metadata) or 'update_script_content' (which modifies content), leaving some ambiguity about its specific scope within the family of script project tools.

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. With siblings like 'script_projects_get' (likely for metadata) and 'update_script_content' (for modifications), there's no indication of the appropriate context or prerequisites for retrieving content specifically, leaving the agent to guess based on tool names 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/mohalmah/google-appscript-mcp-server'

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