Skip to main content
Glama

create_filter

Automatically organize Gmail messages by creating filters that apply labels, forward emails, or remove labels based on sender, subject, attachments, or search queries.

Instructions

Creates a filter

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
criteriaYesFilter criteria
actionYesActions to perform on messages matching the criteria

Implementation Reference

  • src/index.ts:998-1024 (registration)
    Registration of the "create_filter" MCP tool, including description, Zod input schema for criteria and action, and inline handler that calls Gmail API to create the filter.
    server.tool("create_filter",
      "Creates a filter",
      {
        criteria: z.object({
          from: z.string().optional().describe("The sender's display name or email address"),
          to: z.string().optional().describe("The recipient's display name or email address"),
          subject: z.string().optional().describe("Case-insensitive phrase in the message's subject"),
          query: z.string().optional().describe("A Gmail search query that specifies the filter's criteria"),
          negatedQuery: z.string().optional().describe("A Gmail search query that specifies criteria the message must not match"),
          hasAttachment: z.boolean().optional().describe("Whether the message has any attachment"),
          excludeChats: z.boolean().optional().describe("Whether the response should exclude chats"),
          size: z.number().optional().describe("The size of the entire RFC822 message in bytes"),
          sizeComparison: z.enum(['smaller', 'larger']).optional().describe("How the message size in bytes should be in relation to the size field")
        }).describe("Filter criteria"),
        action: z.object({
          addLabelIds: z.array(z.string()).optional().describe("List of labels to add to messages"),
          removeLabelIds: z.array(z.string()).optional().describe("List of labels to remove from messages"),
          forward: z.string().optional().describe("Email address that the message should be forwarded to")
        }).describe("Actions to perform on messages matching the criteria")
      },
      async (params) => {
        return handleTool(config, async (gmail: gmail_v1.Gmail) => {
          const { data } = await gmail.users.settings.filters.create({ userId: 'me', requestBody: params })
          return formatResponse(data)
        })
      }
    )
  • Handler function for "create_filter" tool: authenticates via handleTool, calls gmail.users.settings.filters.create with params, formats response.
    async (params) => {
      return handleTool(config, async (gmail: gmail_v1.Gmail) => {
        const { data } = await gmail.users.settings.filters.create({ userId: 'me', requestBody: params })
        return formatResponse(data)
      })
    }
  • Zod schema defining input for "create_filter": criteria (from, to, subject, query, etc.) and action (addLabelIds, removeLabelIds, forward).
    {
      criteria: z.object({
        from: z.string().optional().describe("The sender's display name or email address"),
        to: z.string().optional().describe("The recipient's display name or email address"),
        subject: z.string().optional().describe("Case-insensitive phrase in the message's subject"),
        query: z.string().optional().describe("A Gmail search query that specifies the filter's criteria"),
        negatedQuery: z.string().optional().describe("A Gmail search query that specifies criteria the message must not match"),
        hasAttachment: z.boolean().optional().describe("Whether the message has any attachment"),
        excludeChats: z.boolean().optional().describe("Whether the response should exclude chats"),
        size: z.number().optional().describe("The size of the entire RFC822 message in bytes"),
        sizeComparison: z.enum(['smaller', 'larger']).optional().describe("How the message size in bytes should be in relation to the size field")
      }).describe("Filter criteria"),
      action: z.object({
        addLabelIds: z.array(z.string()).optional().describe("List of labels to add to messages"),
        removeLabelIds: z.array(z.string()).optional().describe("List of labels to remove from messages"),
        forward: z.string().optional().describe("Email address that the message should be forwarded to")
      }).describe("Actions to perform on messages matching the criteria")
    },
  • handleTool helper: manages OAuth2 client creation, validation, Gmail client setup, executes API call, handles errors.
    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) {
        return `Tool execution failed: ${error.message}`
      }
    }
Behavior1/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but fails completely. It doesn't indicate whether this is a read-only or mutating operation, what permissions might be required, whether the filter creation is reversible, or what happens on success/failure. For a tool that presumably creates persistent filters in a mail system, this lack of behavioral information is a critical gap.

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

Conciseness2/5

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

While technically concise with only two words, this represents under-specification rather than effective brevity. The description doesn't front-load important information and fails to provide the minimal context needed for tool selection. In conciseness scoring, under-specification that leaves critical gaps is penalized, making this a 2 rather than a higher score for brevity.

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?

Given the tool's complexity (2 required parameters with nested objects), lack of annotations, and absence of an output schema, the description is completely inadequate. It doesn't explain what the tool returns, what happens after filter creation, or any behavioral aspects. For a tool that presumably creates persistent filtering rules in a mail system, this minimal description fails to provide the necessary context for effective use.

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?

The schema description coverage is 100%, so the schema already documents both parameters ('criteria' and 'action') and their sub-properties thoroughly. The description adds no parameter information beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description, which applies here.

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

Purpose2/5

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

The description 'Creates a filter' is a tautology that merely restates the tool name without adding meaningful context. It doesn't specify what type of filter is being created (e.g., Gmail message filter), what resource it operates on, or how it differs from sibling tools like 'delete_filter' or 'list_filters'. While the verb 'creates' is clear, the lack of specificity makes this minimally informative.

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?

The description provides absolutely no guidance on when to use this tool versus alternatives. There's no mention of prerequisites, appropriate contexts, or comparisons to sibling tools like 'list_filters' or 'delete_filter'. The agent receives no help in determining when this specific creation tool should be selected over other available options.

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/nk900600/gmail-mcp'

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