Skip to main content
Glama

create_draft

Create a draft email in Gmail with recipients, subject, and body, or use raw base64url encoded format for complete message control.

Instructions

Create a draft email in Gmail. Note the mechanics of the raw parameter.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
rawNoThe entire email message in base64url encoded RFC 2822 format, ignores params.to, cc, bcc, subject, body, includeBodyHtml if provided
threadIdNoThe thread ID to associate this draft with
toNoList of recipient email addresses
ccNoList of CC recipient email addresses
bccNoList of BCC recipient email addresses
subjectNoThe subject of the email
bodyNoThe body of the email
includeBodyHtmlNoWhether to include the parsed HTML in the return for each body, excluded by default because they can be excessively large

Implementation Reference

  • Handler function for the 'create_draft' tool. Handles input parameters, constructs raw message if not provided, calls Gmail API to create the draft, processes the payload, and formats the response.
    async (params) => {
      return handleTool(config, async (gmail: gmail_v1.Gmail) => {
        let raw = params.raw
        if (!raw) raw = await constructRawMessage(gmail, params)
    
        const draftCreateParams: DraftCreateParams = { userId: 'me', requestBody: { message: { raw } } }
        if (params.threadId && draftCreateParams.requestBody?.message) {
          draftCreateParams.requestBody.message.threadId = params.threadId
        }
    
        const { data } = await gmail.users.drafts.create(draftCreateParams)
    
        if (data.message?.payload) {
          data.message.payload = processMessagePart(
            data.message.payload,
            params.includeBodyHtml
          )
        }
    
        return formatResponse(data)
      })
    }
  • Input schema (Zod) for the 'create_draft' tool defining parameters like raw, threadId, to, cc, bcc, subject, body, and includeBodyHtml.
      raw: z.string().optional().describe("The entire email message in base64url encoded RFC 2822 format, ignores params.to, cc, bcc, subject, body, includeBodyHtml if provided"),
      threadId: z.string().optional().describe("The thread ID to associate this draft with"),
      to: z.array(z.string()).optional().describe("List of recipient email addresses"),
      cc: z.array(z.string()).optional().describe("List of CC recipient email addresses"),
      bcc: z.array(z.string()).optional().describe("List of BCC recipient email addresses"),
      subject: z.string().optional().describe("The subject of the email"),
      body: z.string().optional().describe("The body of the email"),
      includeBodyHtml: z.boolean().optional().describe("Whether to include the parsed HTML in the return for each body, excluded by default because they can be excessively large")
    },
  • src/index.ts:262-296 (registration)
    Registration of the 'create_draft' tool on the MCP server, including name, description, schema, and handler.
    server.tool("create_draft",
      "Create a draft email in Gmail. Note the mechanics of the raw parameter.",
      {
        raw: z.string().optional().describe("The entire email message in base64url encoded RFC 2822 format, ignores params.to, cc, bcc, subject, body, includeBodyHtml if provided"),
        threadId: z.string().optional().describe("The thread ID to associate this draft with"),
        to: z.array(z.string()).optional().describe("List of recipient email addresses"),
        cc: z.array(z.string()).optional().describe("List of CC recipient email addresses"),
        bcc: z.array(z.string()).optional().describe("List of BCC recipient email addresses"),
        subject: z.string().optional().describe("The subject of the email"),
        body: z.string().optional().describe("The body of the email"),
        includeBodyHtml: z.boolean().optional().describe("Whether to include the parsed HTML in the return for each body, excluded by default because they can be excessively large")
      },
      async (params) => {
        return handleTool(config, async (gmail: gmail_v1.Gmail) => {
          let raw = params.raw
          if (!raw) raw = await constructRawMessage(gmail, params)
    
          const draftCreateParams: DraftCreateParams = { userId: 'me', requestBody: { message: { raw } } }
          if (params.threadId && draftCreateParams.requestBody?.message) {
            draftCreateParams.requestBody.message.threadId = params.threadId
          }
    
          const { data } = await gmail.users.drafts.create(draftCreateParams)
    
          if (data.message?.payload) {
            data.message.payload = processMessagePart(
              data.message.payload,
              params.includeBodyHtml
            )
          }
    
          return formatResponse(data)
        })
      }
    )
  • Shared helper function 'handleTool' used by create_draft (and other tools) to manage OAuth2 authentication, credential validation, Gmail client creation, API execution, and error handling.
    const handleTool = async (queryConfig: Record<string, any> | undefined, apiCall: (gmail: gmail_v1.Gmail) => Promise<any>) => {
      try {
        const oauth2Client = queryConfig ? createOAuth2Client(queryConfig) : defaultOAuth2Client
        if (!oauth2Client) throw new Error('OAuth2 client could not be created, please check your credentials')
    
        const credentialsAreValid = await validateCredentials(oauth2Client)
        if (!credentialsAreValid) throw new Error('OAuth2 credentials are invalid, please re-authenticate')
    
        const gmailClient = queryConfig ? google.gmail({ version: 'v1', auth: oauth2Client }) : defaultGmailClient
        if (!gmailClient) throw new Error('Gmail client could not be created, please check your credentials')
    
        const result = await apiCall(gmailClient)
        return result
      } catch (error: any) {
        // Check for specific authentication errors
        if (
          error.message?.includes("invalid_grant") ||
          error.message?.includes("refresh_token") ||
          error.message?.includes("invalid_client") ||
          error.message?.includes("unauthorized_client") ||
          error.code === 401 ||
          error.code === 403
        ) {
          return formatResponse({
            error: `Authentication failed: ${error.message}. Please re-authenticate by running: npx @shinzolabs/gmail-mcp auth`,
          });
        }
    
        return formatResponse({ error: `Tool execution failed: ${error.message}` });
      }
    }
  • Helper function 'constructRawMessage' used by create_draft to build the base64url-encoded RFC 2822 raw message from parameters, handling thread quoting and headers.
    const constructRawMessage = async (gmail: gmail_v1.Gmail, params: NewMessage) => {
      let thread: Thread | null = null
      if (params.threadId) {
        const threadParams = { userId: 'me', id: params.threadId, format: 'full' }
        const { data } = await gmail.users.threads.get(threadParams)
        thread = data
      }
    
      const message = []
      if (params.to?.length) message.push(`To: ${wrapTextBody(params.to.join(', '))}`)
      if (params.cc?.length) message.push(`Cc: ${wrapTextBody(params.cc.join(', '))}`)
      if (params.bcc?.length) message.push(`Bcc: ${wrapTextBody(params.bcc.join(', '))}`)
      if (thread) {
        message.push(...getThreadHeaders(thread).map(header => wrapTextBody(header)))
      } else if (params.subject) {
        message.push(`Subject: ${wrapTextBody(params.subject)}`)
      } else {
        message.push('Subject: (No Subject)')
      }
      message.push('Content-Type: text/plain; charset="UTF-8"')
      message.push('Content-Transfer-Encoding: quoted-printable')
      message.push('MIME-Version: 1.0')
      message.push('')
    
      if (params.body) message.push(wrapTextBody(params.body))
    
      if (thread) {
        const quotedContent = getQuotedContent(thread)
        if (quotedContent) {
          message.push('')
          message.push(wrapTextBody(quotedContent))
        }
      }
    
      return Buffer.from(message.join('\r\n')).toString('base64url').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but lacks critical behavioral details. It mentions 'Note the mechanics of the raw parameter' but doesn't explain what the tool actually does beyond creation (e.g., where drafts are stored, if it requires authentication, or what happens on failure). This is inadequate for a mutation tool.

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 extremely concise with only two sentences, front-loading the core purpose. Every word earns its place, with no redundant or unnecessary information.

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?

For a mutation tool with 8 parameters, no annotations, and no output schema, the description is incomplete. It fails to explain behavioral aspects like permissions, side effects, or return values, leaving significant gaps for an AI agent to understand proper usage.

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%, so the schema fully documents all 8 parameters. The description adds minimal value by noting the 'mechanics of the raw parameter' but doesn't elaborate on what those mechanics are or provide additional context beyond the schema's parameter descriptions.

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 ('Create') and resource ('draft email in Gmail'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'send_draft' or 'send_message', which would require a 5.

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 like 'send_message' or 'send_draft', nor does it mention prerequisites or context for creating drafts. It only hints at parameter mechanics without addressing 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/faithk7/gmail-mcp'

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