Skip to main content
Glama
DynamicEndpoints

Microsoft 365 Core MCP Server

generate_word_document

Create professional Word documents with formatted sections, tables, charts, and table of contents from analysis data using Microsoft 365 services.

Instructions

Create professional Word documents with formatted sections, tables, charts, and table of contents from analysis data.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesAction: create new document, get existing, list all, export to format, or append content
fileNameNoName for the new document file (for create action)
driveIdNoOneDrive/SharePoint drive ID (default: user's OneDrive)
folderIdNoFolder ID within the drive (default: root)
templateNoTemplate configuration for document styling
sectionsNoArray of content sections to create
fileIdNoFile ID for get/export/append actions
formatNoExport format (for export action)
contentNoContent to append (for append action)
filterNoOData filter for list action
topNoNumber of results to return (for list action)

Implementation Reference

  • Registers the 'generate_word_document' tool with MCP server, linking to handleWordDocuments handler and wordDocumentArgsSchema
      "generate_word_document",
      "Create professional Word documents with formatted sections, tables, charts, and table of contents from analysis data.",
      wordDocumentArgsSchema.shape,
      {"readOnlyHint":false,"destructiveHint":false,"idempotentHint":false},
      wrapToolHandler(async (args: WordDocumentArgs) => {
        this.validateCredentials();
        try {
          const result = await handleWordDocuments(args, this.getGraphClient());
          return { content: [{ type: 'text', text: result }] };
        } catch (error) {
          if (error instanceof McpError) {
            throw error;
          }
          throw new McpError(
            ErrorCode.InternalError,
            `Error generating Word document: ${error instanceof Error ? error.message : 'Unknown error'}`
          );
        }
      })
    );
  • Main handler function for Word document operations, dispatches to specific actions like create (which generates the document)
    export async function handleWordDocuments(
      args: WordDocumentArgs,
      graphClient: Client
    ): Promise<string> {
      try {
        switch (args.action) {
          case 'create':
            return await createDocument(args, graphClient);
          case 'get':
            return await getDocument(args, graphClient);
          case 'list':
            return await listDocuments(args, graphClient);
          case 'export':
            return await exportDocument(args, graphClient);
          case 'append':
            return await appendToDocument(args, graphClient);
          default:
            throw new McpError(
              ErrorCode.InvalidRequest,
              `Unknown action: ${args.action}`
            );
        }
      } catch (error) {
        if (error instanceof McpError) throw error;
        throw new McpError(
          ErrorCode.InternalError,
          `Word document operation failed: ${error instanceof Error ? error.message : 'Unknown error'}`
        );
      }
    }
  • Core generation logic for creating Word documents from sections and template, generates XML content and uploads via Graph API
    async function createDocument(
      args: WordDocumentArgs,
      graphClient: Client
    ): Promise<string> {
      if (!args.fileName) {
        throw new McpError(ErrorCode.InvalidRequest, 'fileName is required for create action');
      }
    
      if (!args.sections || args.sections.length === 0) {
        throw new McpError(ErrorCode.InvalidRequest, 'At least one section is required');
      }
    
      // Determine drive location (default to user's OneDrive)
      const driveId = args.driveId || 'me';
      const folderPath = args.folderId ? `/items/${args.folderId}` : '/root';
    
      // Create Word document file
      const fileName = args.fileName.endsWith('.docx') ? args.fileName : `${args.fileName}.docx`;
      
      // Generate document content
      const documentContent = generateDocumentXML(args.sections, args.template);
      
      const uploadedFile = await graphClient
        .api(`/drives/${driveId}${folderPath}:/${fileName}:/content`)
        .header('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        .put(documentContent);
    
      return JSON.stringify({
        success: true,
        fileId: uploadedFile.id,
        fileName: uploadedFile.name,
        webUrl: uploadedFile.webUrl,
        driveId: uploadedFile.parentReference?.driveId,
        message: `Word document "${fileName}" created successfully with ${args.sections.length} sections`
      }, null, 2);
    }
  • Zod schema defining input parameters for generate_word_document tool, including sections, template, file locations
    export const wordDocumentArgsSchema = z.object({
      action: z.enum(['create', 'get', 'list', 'export', 'append'])
        .describe('Action: create new document, get existing, list all, export to format, or append content'),
      fileName: z.string().optional()
        .describe('Name for the new document file (for create action)'),
      driveId: z.string().optional()
        .describe('OneDrive/SharePoint drive ID (default: user\'s OneDrive)'),
      folderId: z.string().optional()
        .describe('Folder ID within the drive (default: root)'),
      template: wordTemplateSchema.optional()
        .describe('Template configuration for document styling'),
      sections: z.array(wordSectionSchema).optional()
        .describe('Array of content sections to create'),
      fileId: z.string().optional()
        .describe('File ID for get/export/append actions'),
      format: z.enum(['docx', 'pdf', 'html', 'txt']).optional()
        .describe('Export format (for export action)'),
      content: z.string().optional()
        .describe('Content to append (for append action)'),
      filter: z.string().optional()
        .describe('OData filter for list action'),
      top: z.number().optional()
        .describe('Number of results to return (for list action)')
    });
  • Generates Word document XML content from sections and template (core document building logic)
    function generateDocumentXML(sections: WordSection[], template?: WordTemplate): Buffer {
      // This is a simplified implementation
      // For production, integrate with docx library: https://docx.js.org/
      
      let content = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <w:body>`;
    
      // Add header if specified
      if (template?.header) {
        content += `
        <w:p>
          <w:pPr>
            <w:pStyle w:val="Header"/>
          </w:pPr>
          <w:r>
            <w:t>${escapeXml(template.header)}</w:t>
          </w:r>
        </w:p>`;
      }
    
      // Add sections
      sections.forEach(section => {
        content += generateSectionXML(section);
      });
    
      // Add footer if specified
      if (template?.footer) {
        content += `
        <w:p>
          <w:pPr>
            <w:pStyle w:val="Footer"/>
          </w:pPr>
          <w:r>
            <w:t>${escapeXml(template.footer)}</w:t>
          </w:r>
        </w:p>`;
      }
    
      content += `
      </w:body>
    </w:document>`;
    
      return Buffer.from(content, 'utf-8');
    }
Behavior3/5

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

Annotations indicate this is a non-readOnly, non-idempotent, non-destructive tool, which the description doesn't contradict. The description adds context about creating 'professional' documents with specific formatting, but doesn't disclose important behavioral traits like authentication needs, rate limits, error conditions, or what happens with existing files. With annotations covering basic safety, this earns a baseline score.

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. It could be slightly more structured by explicitly mentioning the multi-action nature (create/get/list/export/append) hinted in the schema, but it's appropriately sized without wasted words.

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

Completeness3/5

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

For a complex tool with 11 parameters, nested objects, no output schema, and annotations covering only basic hints, the description is minimally adequate. It states what the tool does but lacks details on return values, error handling, or advanced usage scenarios that would help an agent use it effectively.

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?

With 100% schema description coverage, the schema fully documents all 11 parameters. The description mentions 'analysis data' which loosely relates to the sections parameter, but adds no specific semantics beyond what the schema provides. The baseline is 3 when schema does the heavy lifting.

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 tool creates Word documents with specific formatting features (sections, tables, charts, table of contents) from analysis data. It distinguishes from sibling tools like generate_html_report and generate_powerpoint_presentation by specifying Word documents, but doesn't explicitly differentiate from generate_professional_report which might overlap in purpose.

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, when-not-to-use scenarios, or compare with sibling tools like generate_professional_report or generate_html_report. The agent must infer usage from the description 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/DynamicEndpoints/m365-core-mcp'

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