Skip to main content
Glama

PostCartsIdShippingMethods

Add a shipping method to a cart when customers select their preferred shipping option during checkout.

Instructions

Add a shipping method to a cart. Use this API route when the customer chooses their preferred shipping option.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idNo
fieldsNo

Implementation Reference

  • The handler function for the PostCartsIdShippingMethods tool (and all store API tools). It parses input into query/body params based on OpenAPI parameters and executes the POST request via Medusa SDK to /carts/{id}/shipping-methods endpoint.
    handler: async (
        input: InferToolHandlerInput<any, ZodTypeAny>
    ): Promise<any> => {
        const query = new URLSearchParams(input);
        const body = Object.entries(input).reduce(
            (acc, [key, value]) => {
                if (
                    parameters.find(
                        (p) => p.name === key && p.in === "body"
                    )
                ) {
                    acc[key] = value;
                }
                return acc;
            },
            {} as Record<string, any>
        );
        if (method === "get") {
            console.error(
                `Fetching ${refPath} with GET ${query.toString()}`
            );
            const response = await this.sdk.client.fetch(refPath, {
                method: method,
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                    "Authorization": `Bearer ${process.env.PUBLISHABLE_KEY}`
                },
                query: query
            });
            return response;
        } else {
            const response = await this.sdk.client.fetch(refPath, {
                method: method,
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                    "Authorization": `Bearer ${process.env.PUBLISHABLE_KEY}`
                },
                body: JSON.stringify(body)
            });
            return response;
        }
    }
  • Generates the Zod input schema for the tool based on the OpenAPI parameters from store.json spec for the POST /carts/{id}/shipping-methods operation.
    inputSchema: {
        ...parameters
            .filter((p) => p.in != "header")
            .reduce((acc, param) => {
                switch (param.schema.type) {
                    case "string":
                        acc[param.name] = z.string().optional();
                        break;
                    case "number":
                        acc[param.name] = z.number().optional();
                        break;
                    case "boolean":
                        acc[param.name] = z.boolean().optional();
                        break;
                    case "array":
                        acc[param.name] = z
                            .array(z.string())
                            .optional();
                        break;
                    case "object":
                        acc[param.name] = z.object({}).optional();
                        break;
                    default:
                        acc[param.name] = z.string().optional();
                }
                return acc;
            }, {} as any)
    },
  • src/index.ts:35-41 (registration)
    Registers all dynamically generated tools, including PostCartsIdShippingMethods, with the MCP server.
    tools.forEach((tool) => {
        server.tool(
            tool.name,
            tool.description,
            tool.inputSchema,
            tool.handler
        );
  • src/index.ts:15-17 (registration)
    Calls defineTools() on MedusaStoreService to generate and collect the tool definitions, including the one for PostCartsIdShippingMethods.
        ...medusaStoreService.defineTools(),
        ...medusaAdminService.defineTools()
    ];
  • Utility that wraps the raw tool handler to conform to MCP protocol response format, used for all tools including PostCartsIdShippingMethods.
    export const defineTool = (
        cb: (zod: typeof z) => ToolDefinition<any, ZodAny, any>
    ) => {
        const tool = cb(z);
    
        const wrappedHandler = async (
            input: InferToolHandlerInput<Zod.ZodAny, Zod.ZodAny>,
            _: RequestHandlerExtra
        ): Promise<{
            content: CallToolResult["content"];
            isError?: boolean;
            statusCode?: number;
        }> => {
            try {
                const result = await tool.handler(input);
                return {
                    content: [
                        {
                            type: "text",
                            text: JSON.stringify(result, null, 2)
                        }
                    ]
                };
            } catch (error) {
                return {
                    content: [
                        {
                            type: "text",
                            text: `Error: ${
                                error instanceof Error
                                    ? error.message
                                    : String(error)
                            }`
                        }
                    ],
                    isError: true
                };
            }
        };
    
        return {
            ...tool,
            handler: wrappedHandler
        };
    };
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states this is a write operation ('Add'), implying mutation, but doesn't cover critical aspects like required permissions, whether changes are reversible, rate limits, or what the response looks like. For a mutation tool with zero annotation coverage, this leaves significant gaps.

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 two sentences, front-loaded with the core purpose and followed by usage context. Every sentence earns its place with no wasted words, making it highly efficient and easy to scan.

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?

Given this is a mutation tool with 2 parameters, 0% schema coverage, no annotations, and no output schema, the description is incomplete. It lacks details on parameter usage, behavioral traits (e.g., side effects), and expected outcomes, which are essential for safe and effective tool invocation.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate for undocumented parameters. It mentions 'cart' (implied for 'id') and 'shipping method' (implied for 'fields'), but doesn't explain what 'fields' should contain (e.g., format, required data) or provide examples. This adds minimal value beyond the bare schema.

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 action ('Add a shipping method to a cart') and the resource ('cart'), which is specific and unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'PostCartsIdComplete' or 'PostCartsIdLineItems', which also modify carts but for different purposes.

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 provides clear context for when to use this tool: 'when the customer chooses their preferred shipping option.' This gives practical guidance, but it doesn't mention when NOT to use it or explicitly name alternatives like 'GetShippingOptions' for browsing options first.

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/SGFGOV/medusa-mcp'

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