Skip to main content
Glama
andresfrei

Google Drive MCP Server

by andresfrei

get_file_content

Extract text content from Google Drive files including Docs, Sheets, and text documents using file ID to access document data.

Instructions

Get content from a Google Drive file (Docs, Sheets, TXT, MD)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
driveIdNo
fileIdYes

Implementation Reference

  • The handler function of the get_file_content tool. It validates the fileId parameter, fetches the file content using googleDriveService, and returns both text and structured content.
    handler: async (params: { fileId: string; driveId?: string }) => {
      const { fileId, driveId } = params;
    
      if (!fileId) {
        throw new Error("fileId is required");
      }
    
      const fileContent = await googleDriveService.getFileContent(
        fileId,
        driveId
      );
    
      return {
        content: [
          {
            type: "text" as const,
            text: JSON.stringify(fileContent, null, 2),
          },
        ],
        structuredContent: {
          fileId: fileContent.fileId,
          name: fileContent.fileName,
          mimeType: fileContent.mimeType,
          content: fileContent.content,
        },
      };
    },
  • Input and output schemas defined using Zod for the get_file_content tool.
    config: {
      title: "Get File Content",
      description: "Get content from a Google Drive file (Docs, Sheets, TXT, MD)",
      inputSchema: {
        fileId: z.string().describe("ID of the file to read"),
        driveId: z.string().optional().describe("Drive ID (if specified)"),
      },
      outputSchema: {
        fileId: z.string(),
        name: z.string(),
        mimeType: z.string(),
        content: z.string(),
      },
    },
  • Dynamic registration of all exported tools (including get_file_content) to the MCP server using registerTool.
    // Registro automático de todas las tools
    const toolList = Object.values(tools);
    toolList.forEach((tool) => {
      server.registerTool(tool.name, tool.config as any, tool.handler as any);
    });
    
    logger.info(`MCP Server initialized with ${toolList.length} tools`);
  • Helper service method that performs the actual Google Drive API calls to retrieve and export file content based on file type.
    async getFileContent(fileId: string, driveId?: string): Promise<FileContent> {
      const targetDriveId =
        driveId || Object.keys(drivesConfigLoader.getConfig().drives)[0];
      const drive = await this.getDriveClient(targetDriveId);
    
      try {
        // Obtener metadatos del archivo
        const metadata = await drive.files.get({
          fileId,
          fields: "id, name, mimeType",
        });
    
        const file = metadata.data;
        const mimeType = file.mimeType!;
        let content = "";
    
        // Google Docs: exportar como texto plano
        if (mimeType === SUPPORTED_MIME_TYPES.GOOGLE_DOC) {
          const response = await drive.files.export({
            fileId,
            mimeType: SUPPORTED_MIME_TYPES.EXPORT_TEXT,
          });
          content = response.data as string;
        }
        // Google Sheets: exportar como CSV
        else if (mimeType === SUPPORTED_MIME_TYPES.GOOGLE_SHEET) {
          const response = await drive.files.export({
            fileId,
            mimeType: SUPPORTED_MIME_TYPES.EXPORT_CSV,
          });
          content = response.data as string;
        }
        // Archivos de texto plano: descarga directa
        else if (
          mimeType === SUPPORTED_MIME_TYPES.TEXT_PLAIN ||
          mimeType === SUPPORTED_MIME_TYPES.TEXT_MARKDOWN ||
          mimeType === "text/markdown" ||
          file.name?.endsWith(".txt") ||
          file.name?.endsWith(".md")
        ) {
          const response = await drive.files.get(
            { fileId, alt: "media" },
            { responseType: "text" }
          );
          content = response.data as string;
        }
        // Tipo de archivo no soportado
        else {
          throw new Error(`Unsupported file type: ${mimeType}`);
        }
    
        logger.info(`Retrieved content for file: ${file.name} (${mimeType})`);
    
        return {
          fileId: file.id!,
          fileName: file.name!,
          mimeType,
          content,
          extractedAt: new Date().toISOString(),
        };
      } catch (error) {
        logger.error("Error getting file content", {
          fileId,
          driveId: targetDriveId,
          error,
        });
        throw error;
      }
    }
  • TypeScript interface defining the parameters for getFileContent.
    export interface GetFileContentParams {
      fileId: string;
      driveId?: string;
    }
  • TypeScript interface for the file content returned by the service.
    export interface FileContent {
      fileId: string;
      fileName: string;
      mimeType: string;
      content: string;
      extractedAt: string;
    }
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 mentions the action ('Get content') and supported file types, but lacks critical details such as authentication requirements, rate limits, error handling (e.g., for unsupported formats), or what the output looks like (e.g., raw text, structured data). For a read operation with no annotation coverage, this is a significant gap.

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 a single, efficient sentence that front-loads the core purpose ('Get content from a Google Drive file') and adds specific details (file types). There's no wasted verbiage, making it appropriately concise for the tool's complexity.

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 tool's complexity (2 parameters, no annotations, no output schema), the description is incomplete. It covers the basic purpose and file types but misses essential context: parameter explanations, behavioral traits (e.g., read-only nature, potential errors), and output details. Without annotations or output schema, the description should do more to guide the agent.

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 for undocumented parameters. It doesn't explain the meaning or usage of 'driveId' and 'fileId' parameters (e.g., how to obtain them, their format, or that 'driveId' is optional). The mention of file types implies some parameter context but doesn't directly address the input schema, leaving key semantics unclear.

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 content') and resource ('from a Google Drive file'), making the purpose understandable. It also specifies supported file types (Docs, Sheets, TXT, MD), which adds useful detail. However, it doesn't explicitly differentiate from sibling tools like 'list_files' or 'search_files', which might also involve file content access.

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 doesn't mention prerequisites (e.g., needing file permissions), exclusions (e.g., unsupported file types beyond those listed), or comparisons to siblings like 'search_files' for content-based queries. This leaves the agent with minimal context for tool 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/andresfrei/mcp-google-drive-server'

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