Skip to main content
Glama

create_draft_order

Create a new draft order for editable carts or quotes. Add product variants or custom items, then attach a customer or send an invoice URL for payment.

Instructions

Create a new draft order — Shopify's term for an editable cart/quote not yet placed as an order. Each line item is EITHER a variant reference (variantId + quantity) for catalog products, OR a custom item (title + originalUnitPrice + quantity) for one-off charges or services not in the catalog. Optionally attach a customer, email, internal note, tags, and choose whether to copy the customer's default address. Returns the new draft's GID and an invoice URL the customer can use to pay. Drafts stay OPEN until you call complete_draft_order or send the invoice.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
lineItemsYesAt least one line item. Each item is EITHER a variant reference (just variantId + quantity) OR a custom item (title + originalUnitPrice + quantity, no variantId). Mixing both shapes in one item is rejected by the refine() validator.
customerIdNoGID of an existing customer to attach to the draft. Get one from list_customers. Optional — drafts can be customer-less and converted to a guest checkout.
emailNoEmail address for the order. Useful when you don't have a customer record yet but want to email the invoice URL.
noteNoInternal note visible to staff only (not the customer).
tagsNoTags to apply to the draft for filtering/segmentation.
useCustomerDefaultAddressNoIf true and customerId is set, copy the customer's default shipping address onto the draft.

Implementation Reference

  • The handler function for the 'create_draft_order' tool. It builds the input object from validated args, calls the Shopify GraphQL mutation DraftOrderCreate, handles user errors, and returns a text response with the new draft order's name, ID, total, and invoice URL.
      server.tool(
      "create_draft_order",
      "Create a new draft order — Shopify's term for an editable cart/quote not yet placed as an order. Each line item is EITHER a variant reference (variantId + quantity) for catalog products, OR a custom item (title + originalUnitPrice + quantity) for one-off charges or services not in the catalog. Optionally attach a customer, email, internal note, tags, and choose whether to copy the customer's default address. Returns the new draft's GID and an invoice URL the customer can use to pay. Drafts stay OPEN until you call complete_draft_order or send the invoice.",
      createDraftOrderSchema,
      async (args) => {
        const input: Record<string, unknown> = {
          lineItems: mapLineItemsForInput(args.lineItems),
        };
        if (args.customerId) input.customerId = args.customerId;
        if (args.email) input.email = args.email;
        if (args.note) input.note = args.note;
        if (args.tags) input.tags = args.tags;
        if (args.useCustomerDefaultAddress !== undefined) {
          input.useCustomerDefaultAddress = args.useCustomerDefaultAddress;
        }
    
        const data = await client.graphql<{
          draftOrderCreate: {
            draftOrder: DraftOrder | null;
            userErrors: ShopifyUserError[];
          };
        }>(CREATE_DRAFT_ORDER_MUTATION, { input });
        throwIfUserErrors(data.draftOrderCreate.userErrors, "draftOrderCreate");
        const d = data.draftOrderCreate.draftOrder;
        if (!d) {
          return {
            content: [
              { type: "text" as const, text: "draftOrderCreate returned no draft order." },
            ],
          };
        }
        const total = `${d.totalPriceSet.shopMoney.amount} ${d.totalPriceSet.shopMoney.currencyCode}`;
        return {
          content: [
            {
              type: "text" as const,
              text: [
                `Created draft order ${d.name} [${d.status}]`,
                `  ID: ${d.id}`,
                `  Total: ${total}`,
                d.invoiceUrl ? `  Invoice: ${d.invoiceUrl}` : "",
              ]
                .filter(Boolean)
                .join("\n"),
            },
          ],
        };
      },
    );
  • The Zod schema (createDraftOrderSchema) defining input validation for create_draft_order: lineItems (array of variant or custom items), customerId, email, note, tags, and useCustomerDefaultAddress.
    const createDraftOrderSchema = {
      lineItems: z
        .array(lineItemSchema)
        .min(1)
        .describe(
          "At least one line item. Each item is EITHER a variant reference (just variantId + quantity) OR a custom item (title + originalUnitPrice + quantity, no variantId). Mixing both shapes in one item is rejected by the refine() validator.",
        ),
      customerId: z
        .string()
        .optional()
        .describe(
          "GID of an existing customer to attach to the draft. Get one from list_customers. Optional — drafts can be customer-less and converted to a guest checkout.",
        ),
      email: z
        .string()
        .email()
        .optional()
        .describe(
          "Email address for the order. Useful when you don't have a customer record yet but want to email the invoice URL.",
        ),
      note: z
        .string()
        .optional()
        .describe("Internal note visible to staff only (not the customer)."),
      tags: z
        .array(z.string())
        .optional()
        .describe("Tags to apply to the draft for filtering/segmentation."),
      useCustomerDefaultAddress: z
        .boolean()
        .optional()
        .describe(
          "If true and customerId is set, copy the customer's default shipping address onto the draft.",
        ),
    };
  • The lineItemSchema used by createDraftOrderSchema. Validates each line item as either a variant reference (variantId + quantity) or a custom item (title + originalUnitPrice + quantity), using a refine() to enforce mutual exclusivity.
    const lineItemSchema = z
      .object({
        variantId: z
          .string()
          .optional()
          .describe("GID of a product variant. Omit for custom items."),
        quantity: z.number().int().min(1).default(1),
        title: z
          .string()
          .optional()
          .describe("Custom line-item title (required if variantId omitted)."),
        originalUnitPrice: z
          .string()
          .optional()
          .describe("Unit price as a decimal string, e.g. '19.99'. Required for custom items."),
      })
      .refine(
        (li) =>
          (li.variantId && !li.title && !li.originalUnitPrice) ||
          (!li.variantId && li.title && li.originalUnitPrice),
        {
          message:
            "Provide either variantId OR (title + originalUnitPrice) for a line item, not both.",
        },
      );
  • The mapLineItemsForInput helper function that transforms validated line items into the shape expected by the Shopify GraphQL mutation input.
    function mapLineItemsForInput(
      items: z.infer<typeof lineItemSchema>[] | undefined,
    ):
      | Array<{
          variantId?: string;
          quantity: number;
          title?: string;
          originalUnitPrice?: string;
        }>
      | undefined {
      if (!items) return undefined;
      return items.map((li) => {
        if (li.variantId) {
          return { variantId: li.variantId, quantity: li.quantity };
        }
        return {
          title: li.title!,
          quantity: li.quantity,
          originalUnitPrice: li.originalUnitPrice!,
        };
      });
    }
  • The registerDraftOrderTools function that registers all draft order tools (including create_draft_order) on the MCP server. Called from src/server.ts line 62 with the MCP server and ShopifyClient instances.
    export function registerDraftOrderTools(
      server: McpServer,
      client: ShopifyClient,
    ): void {
      server.tool(
        "list_draft_orders",
        "List draft orders (carts/quotes that haven't yet been completed into real orders), most recently updated first. Returns each draft's name (e.g. 'D1023'), status (OPEN/COMPLETED/INVOICE_SENT), total price, customer name, and whether it's already been converted to an order. Supports Shopify's draft-order query syntax for filtering by status, customer, tag, or update time. Cursor-paginated.",
        listDraftOrdersSchema,
        async (args) => {
          const data = await client.graphql<{
            draftOrders: Connection<DraftOrder>;
          }>(LIST_DRAFT_ORDERS_QUERY, {
            first: args.first,
            after: args.after,
            query: args.query,
          });
          const lines = [
            `Found ${data.draftOrders.edges.length} draft order(s):`,
            ...data.draftOrders.edges.map(({ node }) => {
              const total = `${node.totalPriceSet.shopMoney.amount} ${node.totalPriceSet.shopMoney.currencyCode}`;
              const customer = node.customer?.displayName ?? "(no customer)";
              const completed = node.order
                ? ` → order ${node.order.name}`
                : "";
              return `  ${node.name} [${node.status}] ${total} — ${customer}${completed} — ${node.id}`;
            }),
          ];
          return { content: [{ type: "text" as const, text: lines.join("\n") }] };
        },
      );
    
      server.tool(
        "get_draft_order",
        "Fetch a single draft order with full details: status, customer, line items (with quantity, title, and unit price), invoice URL, and the resulting real order if it's already been completed. Use to inspect a draft before calling update_draft_order or complete_draft_order. Returns a friendly text summary.",
        getDraftOrderSchema,
        async (args) => {
          const data = await client.graphql<{ draftOrder: DraftOrder | null }>(
            GET_DRAFT_ORDER_QUERY,
            { id: args.id },
          );
          if (!data.draftOrder) {
            return {
              content: [
                { type: "text" as const, text: `Draft order not found: ${args.id}` },
              ],
            };
          }
          const d = data.draftOrder;
          const total = `${d.totalPriceSet.shopMoney.amount} ${d.totalPriceSet.shopMoney.currencyCode}`;
          const customer = d.customer
            ? `${d.customer.displayName ?? ""} <${d.customer.email ?? ""}>`
            : "(no customer)";
          const lineItemLines =
            d.lineItems?.edges.map(({ node }) => {
              const price = node.originalUnitPriceSet
                ? `@ ${node.originalUnitPriceSet.shopMoney.amount} ${node.originalUnitPriceSet.shopMoney.currencyCode}`
                : "";
              return `    - ${node.quantity}× ${node.title} ${price}`.trim();
            }) ?? [];
          return {
            content: [
              {
                type: "text" as const,
                text: [
                  `${d.name} [${d.status}]`,
                  `  ID: ${d.id}`,
                  `  Total: ${total}`,
                  `  Customer: ${customer}`,
                  d.invoiceUrl ? `  Invoice: ${d.invoiceUrl}` : "",
                  d.order ? `  Completed as order: ${d.order.name} (${d.order.id})` : "",
                  "  Line items:",
                  ...lineItemLines,
                ]
                  .filter(Boolean)
                  .join("\n"),
              },
            ],
          };
        },
      );
    
        server.tool(
        "create_draft_order",
        "Create a new draft order — Shopify's term for an editable cart/quote not yet placed as an order. Each line item is EITHER a variant reference (variantId + quantity) for catalog products, OR a custom item (title + originalUnitPrice + quantity) for one-off charges or services not in the catalog. Optionally attach a customer, email, internal note, tags, and choose whether to copy the customer's default address. Returns the new draft's GID and an invoice URL the customer can use to pay. Drafts stay OPEN until you call complete_draft_order or send the invoice.",
        createDraftOrderSchema,
        async (args) => {
          const input: Record<string, unknown> = {
            lineItems: mapLineItemsForInput(args.lineItems),
          };
          if (args.customerId) input.customerId = args.customerId;
          if (args.email) input.email = args.email;
          if (args.note) input.note = args.note;
          if (args.tags) input.tags = args.tags;
          if (args.useCustomerDefaultAddress !== undefined) {
            input.useCustomerDefaultAddress = args.useCustomerDefaultAddress;
          }
    
          const data = await client.graphql<{
            draftOrderCreate: {
              draftOrder: DraftOrder | null;
              userErrors: ShopifyUserError[];
            };
          }>(CREATE_DRAFT_ORDER_MUTATION, { input });
          throwIfUserErrors(data.draftOrderCreate.userErrors, "draftOrderCreate");
          const d = data.draftOrderCreate.draftOrder;
          if (!d) {
            return {
              content: [
                { type: "text" as const, text: "draftOrderCreate returned no draft order." },
              ],
            };
          }
          const total = `${d.totalPriceSet.shopMoney.amount} ${d.totalPriceSet.shopMoney.currencyCode}`;
          return {
            content: [
              {
                type: "text" as const,
                text: [
                  `Created draft order ${d.name} [${d.status}]`,
                  `  ID: ${d.id}`,
                  `  Total: ${total}`,
                  d.invoiceUrl ? `  Invoice: ${d.invoiceUrl}` : "",
                ]
                  .filter(Boolean)
                  .join("\n"),
              },
            ],
          };
        },
      );
    
      server.tool(
        "update_draft_order",
        "Modify an existing OPEN draft order's customer, email, note, tags, or line items. Important: if `lineItems` is provided, it REPLACES the existing items entirely (not a merge or append) — read the current items first if you need to preserve any. Cannot update completed drafts; those are real orders. To pause and pick up a draft later, leave it OPEN and re-invoke update later; nothing here triggers payment.",
        updateDraftOrderSchema,
        async (args) => {
          const input: Record<string, unknown> = {};
          const mapped = mapLineItemsForInput(args.lineItems);
          if (mapped) input.lineItems = mapped;
          if (args.customerId) input.customerId = args.customerId;
          if (args.email) input.email = args.email;
          if (args.note) input.note = args.note;
          if (args.tags) input.tags = args.tags;
    
          const data = await client.graphql<{
            draftOrderUpdate: {
              draftOrder: DraftOrder | null;
              userErrors: ShopifyUserError[];
            };
          }>(UPDATE_DRAFT_ORDER_MUTATION, { id: args.id, input });
          throwIfUserErrors(data.draftOrderUpdate.userErrors, "draftOrderUpdate");
          const d = data.draftOrderUpdate.draftOrder;
          if (!d) {
            return {
              content: [
                { type: "text" as const, text: "draftOrderUpdate returned no draft order." },
              ],
            };
          }
          const total = `${d.totalPriceSet.shopMoney.amount} ${d.totalPriceSet.shopMoney.currencyCode}`;
          return {
            content: [
              {
                type: "text" as const,
                text: `Updated draft order ${d.name} [${d.status}] — Total: ${total}`,
              },
            ],
          };
        },
      );
    
      server.tool(
        "complete_draft_order",
        "Convert an OPEN draft order into a real Shopify order. With paymentPending=false (default), Shopify attempts to capture payment immediately; the call fails if no payment method is on file. With paymentPending=true, the order is created in payment-pending status — useful when collecting payment offline (cash, bank transfer, manual processing). Once completed, the draft transitions to COMPLETED and the new order's GID is returned. The transition is one-way: completed drafts cannot be re-opened or edited via draft tools (use the order tools, or refund/cancel for the resulting order).",
        completeDraftOrderSchema,
        async (args) => {
          const data = await client.graphql<{
            draftOrderComplete: {
              draftOrder: DraftOrder | null;
              userErrors: ShopifyUserError[];
            };
          }>(COMPLETE_DRAFT_ORDER_MUTATION, {
            id: args.id,
            paymentPending: args.paymentPending ?? false,
          });
          throwIfUserErrors(data.draftOrderComplete.userErrors, "draftOrderComplete");
          const d = data.draftOrderComplete.draftOrder;
          if (!d) {
            return {
              content: [
                { type: "text" as const, text: "draftOrderComplete returned no draft order." },
              ],
            };
          }
          const orderInfo = d.order
            ? ` → order ${d.order.name} (${d.order.id})`
            : "";
          return {
            content: [
              {
                type: "text" as const,
                text: `Completed draft order ${d.name} [${d.status}]${orderInfo}`,
              },
            ],
          };
        },
      );
    
      server.tool(
        "delete_draft_order",
        "Permanently delete a draft order. Only OPEN/INVOICE_SENT drafts can be deleted — completed drafts are real orders and orders cannot be deleted (cancel them instead). Irreversible. Returns the deleted GID, or a no-op message if the GID didn't match anything.",
        deleteDraftOrderSchema,
        async (args) => {
          const data = await client.graphql<{
            draftOrderDelete: {
              deletedId: string | null;
              userErrors: ShopifyUserError[];
            };
          }>(DELETE_DRAFT_ORDER_MUTATION, { input: { id: args.id } });
          throwIfUserErrors(data.draftOrderDelete.userErrors, "draftOrderDelete");
          return {
            content: [
              {
                type: "text" as const,
                text: data.draftOrderDelete.deletedId
                  ? `Deleted draft order ${data.draftOrderDelete.deletedId}.`
                  : "No draft order matched; nothing deleted.",
              },
            ],
          };
        },
      );
    }
Behavior5/5

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

Despite no annotations, the description thoroughly discloses behavior: line item constraints (variant vs custom), optional attachments, draft state (OPEN), and return values (GID, invoice URL). No contradictions.

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 informative but slightly verbose with multiple clauses. However, every sentence adds value and it is well front-loaded with the purpose. Could be slightly tighter but effective.

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

Completeness5/5

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

For a complex tool with 6 parameters and no output schema, the description provides all necessary context: line item rules, optional fields, draft lifecycle, and return values. High completeness given the schema coverage.

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

Parameters5/5

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

Schema coverage is 100%, and the description adds substantial detail: explains line item shapes, rejection of mixed shapes, purpose of email vs customerId, and distinction between custom and variant items. Exceeds schema alone.

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 clearly states it creates a draft order (editable cart/quote), distinguishing it from related tools like complete_draft_order and create_order. It provides specific Shopify terminology and context.

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?

The description explains when to use (for editable carts/quotes) and mentions subsequent actions (complete_draft_order or send invoice). It implicitly distinguishes from create_order but lacks explicit 'when not to use' or direct alternatives.

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