Skip to main content
Glama

set_metafield

Create or update a metafield on any Shopify resource by specifying the owner, namespace, key, type, and value. Supports products, variants, collections, customers, orders, and more.

Instructions

Create or update (upsert) a single metafield on any supported Shopify resource — product, variant, collection, customer, order, draft order, shop, or shop policies. The (ownerId, namespace, key) triple is the unique identifier; calling this tool with an existing triple replaces the value, otherwise creates a new metafield. The type must be a Shopify-supported metafield type and the value must serialize per that type — e.g. JSON types take a JSON string, references take a target GID, primitives take literal text. Errors come back as MCP tool errors with the validation messages from Shopify.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ownerIdYesGID of the resource to attach the metafield to (e.g. gid://shopify/Product/123, gid://shopify/Collection/456, gid://shopify/Customer/789, gid://shopify/Order/...)
namespaceYesMetafield namespace (2-255 chars). Convention: app-specific prefix.
keyYesMetafield key within the namespace (1-64 chars).
typeYesMetafield type: 'single_line_text_field', 'multi_line_text_field', 'number_integer', 'number_decimal', 'boolean', 'json', 'url', 'date', 'date_time', 'rating', 'color', 'weight', 'volume', 'dimension', 'money', 'rich_text_field', or reference types like 'product_reference', 'collection_reference', 'file_reference'.
valueYesMetafield value, serialized per the type. JSON/reference types take a JSON string; primitives take the literal string.

Implementation Reference

  • Handler function for the set_metafield tool. Receives ownerId, namespace, key, type, and value, calls the Shopify GraphQL MetafieldsSet mutation, throws on user errors, and returns a success message with the saved metafield details.
    async (args) => {
      const data = await client.graphql<{
        metafieldsSet: {
          metafields: Metafield[];
          userErrors: ShopifyUserError[];
        };
      }>(METAFIELDS_SET_MUTATION, {
        metafields: [
          {
            ownerId: args.ownerId,
            namespace: args.namespace,
            key: args.key,
            type: args.type,
            value: args.value,
          },
        ],
      });
      throwIfUserErrors(data.metafieldsSet.userErrors, "metafieldsSet");
      const mf = data.metafieldsSet.metafields[0];
      if (!mf) {
        return {
          content: [
            { type: "text" as const, text: "metafieldsSet returned no metafield." },
          ],
        };
      }
      return {
        content: [
          {
            type: "text" as const,
            text: [
              "Metafield saved:",
              `  ${mf.namespace}.${mf.key} (${mf.type})`,
              `  = ${mf.value}`,
              `  ID: ${mf.id}`,
              `  Owner: ${mf.ownerType}`,
            ].join("\n"),
          },
        ],
      };
    },
  • Zod schema defining the input parameters for set_metafield: ownerId (GID string), namespace (2-255 chars), key (1-64 chars), type (Shopify metafield type enum), and value (serialized string per type).
    const setMetafieldSchema = {
      ownerId: z
        .string()
        .describe(
          "GID of the resource to attach the metafield to (e.g. gid://shopify/Product/123, gid://shopify/Collection/456, gid://shopify/Customer/789, gid://shopify/Order/...)",
        ),
      namespace: z
        .string()
        .min(2)
        .max(255)
        .describe("Metafield namespace (2-255 chars). Convention: app-specific prefix."),
      key: z
        .string()
        .min(1)
        .max(64)
        .describe("Metafield key within the namespace (1-64 chars)."),
      type: z
        .string()
        .describe(
          "Metafield type: 'single_line_text_field', 'multi_line_text_field', 'number_integer', 'number_decimal', 'boolean', 'json', 'url', 'date', 'date_time', 'rating', 'color', 'weight', 'volume', 'dimension', 'money', 'rich_text_field', or reference types like 'product_reference', 'collection_reference', 'file_reference'.",
        ),
      value: z
        .string()
        .describe(
          "Metafield value, serialized per the type. JSON/reference types take a JSON string; primitives take the literal string.",
        ),
    };
  • Registration of the "set_metafield" tool on the MCP server with its description, schema, and handler.
    server.tool(
      "set_metafield",
      "Create or update (upsert) a single metafield on any supported Shopify resource — product, variant, collection, customer, order, draft order, shop, or shop policies. The (ownerId, namespace, key) triple is the unique identifier; calling this tool with an existing triple replaces the value, otherwise creates a new metafield. The `type` must be a Shopify-supported metafield type and the `value` must serialize per that type — e.g. JSON types take a JSON string, references take a target GID, primitives take literal text. Errors come back as MCP tool errors with the validation messages from Shopify.",
      setMetafieldSchema,
      async (args) => {
        const data = await client.graphql<{
          metafieldsSet: {
            metafields: Metafield[];
            userErrors: ShopifyUserError[];
          };
        }>(METAFIELDS_SET_MUTATION, {
          metafields: [
            {
              ownerId: args.ownerId,
              namespace: args.namespace,
              key: args.key,
              type: args.type,
              value: args.value,
            },
          ],
        });
        throwIfUserErrors(data.metafieldsSet.userErrors, "metafieldsSet");
        const mf = data.metafieldsSet.metafields[0];
        if (!mf) {
          return {
            content: [
              { type: "text" as const, text: "metafieldsSet returned no metafield." },
            ],
          };
        }
        return {
          content: [
            {
              type: "text" as const,
              text: [
                "Metafield saved:",
                `  ${mf.namespace}.${mf.key} (${mf.type})`,
                `  = ${mf.value}`,
                `  ID: ${mf.id}`,
                `  Owner: ${mf.ownerType}`,
              ].join("\n"),
            },
          ],
        };
      },
    );
  • src/server.ts:61-61 (registration)
    Call-site where the metafield tools are registered on the MCP server during server initialization.
    registerMetafieldTools(s, shopify);
  • GraphQL mutation string used by set_metafield to send the MetafieldsSet mutation to the Shopify Admin API.
    const METAFIELDS_SET_MUTATION = /* GraphQL */ `
      mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) {
        metafieldsSet(metafields: $metafields) {
          metafields {
            id
            namespace
            key
            type
            value
            ownerType
            createdAt
            updatedAt
          }
          userErrors { field message code }
        }
      }
    `;
Behavior4/5

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

Discloses upsert logic, type/value serialization, and error format via MCP. No annotations provided, so description carries burden. Covers key behaviors without contradictions.

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?

Single paragraph with clear logical flow: purpose, uniqueness, value format, error handling. No redundant sentences.

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?

No output schema, but description omits return value on success. Given complexity, missing return info reduces completeness. Mentions errors but not success response.

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

Parameters4/5

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

Schema coverage is 100% (baseline 3). The description adds context about the triple as unique identifier and serialization rules per type, adding value beyond schema.

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

Purpose5/5

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

The description explicitly states the tool upserts a single metafield on supported Shopify resources, listing resource types. It clearly distinguishes from siblings like delete_metafield.

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

Usage Guidelines4/5

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

It explains the upsert behavior and unique triple, implying when to use. Alternative tools like delete_metafield are indirectly suggested through sibling list, but no explicit when-not-to-use.

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/miller-joe/shopify-mcp'

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