Skip to main content
Glama
penysho

Google Docs MCP Server

by penysho

Servidor MCP de Google Docs

Este proyecto proporciona un servidor MCP (Protocolo de contexto de modelo) que funciona con la API de Google Docs. Estamos implementando una interfaz para manipular Google Docs utilizando IA generativa.

función

Este servidor MCP ofrece las siguientes características:

  • Leer documentos de Google Docs

  • Crear un nuevo documento de Google Docs

  • Cómo actualizar un documento existente de Google Docs

  • Cómo buscar documentos de Google Docs

Related MCP server: Claude MCP x Google Docs

Pila de tecnología

Prerrequisitos

  • Node.js (se recomienda v14 o superior)

  • npm o hilo

  • Proyecto de Google Cloud Platform y credenciales de acceso

configuración

1. Clonar o descargar el proyecto

git clone [リポジトリURL]
cd docs-mcp

2. Instalar dependencias

npm install

3. Configuración de Google Cloud Platform

  1. Crea un proyecto en Google Cloud Console (o elige un proyecto existente)

  2. Habilitar la API de Google Drive y la API de Google Docs

  3. Cree un ID de cliente OAuth 2.0 y descargue las credenciales

  4. Coloque el archivo de credenciales descargado como credentials.json en la raíz del proyecto.

4. Preferencias

  1. Cree un archivo .env en la raíz de su proyecto y configure allí sus variables de entorno:

# アプリケーション環境
NODE_ENV=development

# ログ設定
# ログレベル: ERROR, WARN, INFO, DEBUG, TRACE
LOG_LEVEL=INFO
# 標準エラー出力にログを出力するかどうか(MCPの仕様に準拠)
LOG_USE_STDERR=true

# サーバー設定
SERVER_NAME=google-docs-mcp-server
SERVER_VERSION=1.0.0

# Google API認証情報
# 認証情報ファイルのパス(デフォルトは./credentials.json)
CREDENTIALS_PATH=./credentials.json
# トークンファイルのパス(デフォルトは./token.json)
TOKEN_PATH=./token.json

Explicación de las variables de entorno:

  • NODE_ENV : El entorno de ejecución de la aplicación (desarrollo, producción, prueba)

  • LOG_LEVEL : Nivel de detalle del registro (ERROR, WARN, INFO, DEBUG, TRACE)

  • LOG_USE_STDERR : si se deben enviar los registros a la salida de error estándar (la especificación MCP utiliza la salida de error estándar)

  • SERVER_NAME : Nombre del servidor MCP

  • SERVER_VERSION : Versión del servidor MCP

  • CREDENTIALS_PATH : Ruta al archivo de credenciales de la API de Google

  • TOKEN_PATH : Ruta para almacenar el token de autenticación

  1. Inicie el servidor de desarrollo y obtenga un token:

    npm run dev

    Después de la ejecución, la URL de autorización se mostrará en la terminal. Accede a esa URL en tu navegador, inicia sesión con tu cuenta de Google y realiza la autorización. Una vez completada la autorización, copie el código de autorización que se muestra, péguelo en la terminal y presione Enter. Esto generará un archivo token.json y lo autenticará automáticamente a partir de ese momento.

Construir y ejecutar

Construir

npm run build

ejecución

Ejecutar como un servidor normal:

npm start

Ejecutándose en modo de desarrollo:

npm run dev

Úselo como servidor MCP

Este proyecto es un servidor que cumple con la especificación del Protocolo de Contexto de Modelo (MCP). Puede conectarse directamente desde los clientes MCP (Cursor, Claude.ai, etc.).

Configuración en el cliente MCP

Configuración con cursor

Para usarlo con Cursor, agregue la siguiente configuración a .cursor/mcp.json :

{
  "mcpServers": {
    "google-docs": {
      "command": "node",
      "args": ["/{プロジェクトへの絶対パス}/docs-mcp/dist/index.js"]
    }
  }
}

Otros clientes de MCP

Otros clientes MCP se comunican utilizando entrada/salida estándar (stdio). Especifique el comando apropiado según la configuración de su cliente.

Herramientas MCP proporcionadas

leer_documento_de_google

Leer el contenido de un documento de Google Docs.

Parámetros :

  • documentId (cadena): el ID del documento de Google Docs que se leerá.

Ejemplo de uso :

// MCPクライアントでの使用例
const response = await client.callTool({
  name: "read_google_document",
  arguments: {
    documentId: "your-document-id"
  }
});

crear_documento_de_google

Crea un nuevo documento de Google Docs.

Parámetros :

  • title (cadena): el título del nuevo documento.

  • content (cadena, opcional): el contenido inicial del documento.

Ejemplo de uso :

const response = await client.callTool({
  name: "create_google_document",
  arguments: {
    title: "ドキュメントタイトル",
    content: "初期コンテンツ"
  }
});

actualizar_documento_de_google

Actualizar un documento de Google Docs existente.

Parámetros :

  • documentId (cadena): el ID del documento de Google Docs que se actualizará.

  • content (cadena): el contenido que se agregará o actualizará.

  • startPosition (número, opcional): la posición para comenzar a actualizar.

  • endPosition (número, opcional): la posición donde finalizar la actualización.

Ejemplo de uso :

const response = await client.callTool({
  name: "update_google_document",
  arguments: {
    documentId: "your-document-id",
    content: "追加または更新するコンテンツ",
    startPosition: 1,
    endPosition: 10
  }
});

buscar_documentos_de_google

Busque el documento de Google Docs.

Parámetros :

  • query (cadena): La consulta de búsqueda.

  • maxResults (número, opcional): el número máximo de resultados a recuperar (predeterminado: 10).

Ejemplo de uso :

const response = await client.callTool({
  name: "search_google_documents",
  arguments: {
    query: "検索キーワード",
    maxResults: 5
  }
});

Ejemplo de uso de un programa

Ejemplo de uso del cliente MCP desde un programa TypeScript o JavaScript:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // MCPクライアントの作成
  const client = new Client({
    name: "google-docs-client",
    version: "1.0.0"
  });

  // Google Docs MCPサーバーへの接続
  const transport = new StdioClientTransport({
    command: "npm",
    args: ["run", "mcp"]
  });

  await client.connect(transport);

  // サーバー情報の取得
  const info = await client.getServerInfo();
  console.log("利用可能なツール:", info.tools);

  // ドキュメントの検索
  const searchResult = await client.callTool({
    name: "search_google_documents",
    arguments: {
      query: "会議資料",
      maxResults: 5
    }
  });
  console.log("検索結果:", searchResult);

  // 接続を閉じる
  await client.disconnect();
}

main().catch(console.error);

solución de problemas

Si ocurre un error de conexión con Cursor

  1. Realice un reinicio completo del Cursor.

  2. Asegúrese de que la configuración .cursor/mcp.json sea correcta.

  3. Inicie manualmente el servidor MCP y verifique que funciona:

    npm run dev

    Verifique que al ejecutar este comando aparezca el mensaje “Google Docs MCP Server iniciado” y que el proceso continúe ejecutándose sin salir.

  4. Verifique la sección "Servidor MCP" en la configuración de Cursor y asegúrese de que el servidor "google-docs" esté en la lista.

Si recibe un error de autenticación de Google

  1. Asegúrese de que el archivo credentials.json esté ubicado correctamente en la raíz del proyecto.

  2. Si token.json existe, elimínelo e intente autenticarse nuevamente.

  3. Verifique que la API de Google Drive y la API de Google Docs estén habilitadas para su proyecto en Google Cloud Console.

Ampliar y configurar

Este servidor MCP está diseñado teniendo en cuenta la extensibilidad, lo que le permite agregar nuevas funciones como:

  1. src/googleDocsService.ts : agrega nuevos métodos a la clase GoogleDocsService.

  2. src/index.ts : define nuevas herramientas y las registra en el servidor

Notas

  • La primera vez que ejecute la aplicación, se mostrará una pantalla de autorización para la autenticación de Google. Después de la autenticación, el token se guarda en un archivo y se utiliza automáticamente en ejecuciones posteriores.

  • Se pueden aplicar cargos de Google Cloud Platform según el uso que haga de la API.

licencia

Licencia MIT

Available Tools

4 tools
create_google_documentD
ParametersJSON Schema
NameRequiredDescriptionDefault
contentNoドキュメントの初期内容(オプション)
titleYes新しいドキュメントのタイトル

TDQS

D1/5.0
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

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

Parameters1/5

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

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

read_google_documentD
ParametersJSON Schema
NameRequiredDescriptionDefault
documentIdYes読み取るGoogle DocsドキュメントのID

TDQS

D1/5.0
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

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

Parameters1/5

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

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_google_documentsD
ParametersJSON Schema
NameRequiredDescriptionDefault
maxResultsNo取得する最大結果数(デフォルト: 10)
queryYes検索クエリ

TDQS

D1/5.0
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

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

Parameters1/5

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

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

update_google_documentD
ParametersJSON Schema
NameRequiredDescriptionDefault
contentYes追加または更新するコンテンツ
documentIdYes更新するGoogle DocsドキュメントのID
endPositionNo更新を終了する位置(オプション)
startPositionNo更新を開始する位置(オプション)

TDQS

D1/5.0
Behavior1/5

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

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

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

Parameters1/5

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

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 4 tool updatesv1.0.0
    • First observedcreate_google_document
    • First observedread_google_document
    • First observedsearch_google_documents
    • First observedupdate_google_document

TDQS

C2/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clearly distinct purpose targeting a specific operation in the Google Docs domain: create, read, search, and update. There is no overlap or ambiguity between these core functions, making it easy for an agent to select the right tool for each task.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern with 'google_document' as the common noun component. The verbs (create, read, search, update) are standard and uniformly formatted in snake_case, providing excellent predictability and readability.

Tool Count4/5

With 4 tools, the count is appropriate for basic document operations, though it feels slightly thin for a full Google Docs server. Core CRUD functions are covered, but additional tools for deletion or more advanced features might be expected in a broader scope.

Completeness3/5

The toolset covers create, read, search, and update operations, which handles basic workflows, but there are notable gaps. Missing a delete tool prevents full lifecycle management, and other common document operations like sharing or formatting are absent, limiting comprehensive coverage of the domain.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers