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;
    }

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-drive'

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