Skip to main content
Glama

PostShippingOptionsIdCalculate

Calculate shipping costs for a cart using a specific shipping option ID to determine accurate delivery pricing.

Instructions

Calculate the price of a shipping option in a cart.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idNo
fieldsNo

Implementation Reference

  • src/index.ts:34-42 (registration)
    Registers all dynamically generated MCP tools from Medusa store and admin services onto the MCP server. The tool 'PostShippingOptionsIdCalculate' is registered here as part of the store tools.
    tools.forEach((tool) => {
        server.tool(
            tool.name,
            tool.description,
            tool.inputSchema,
            tool.handler
        );
    });
  • The handler function that implements the logic for the 'PostShippingOptionsIdCalculate' tool (and all store tools). It constructs query/body from input and calls the Medusa SDK to perform the API request to /shipping-options/{id}/calculate.
        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;
            }
        }
    };
  • Dynamically generates the Zod input schema for the tool based on the OpenAPI spec parameters for the shipping options calculate endpoint.
    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)
    },
  • Generates the tool definition objects for all store API paths, including the one named 'PostShippingOptionsIdCalculate' from the store.json OpenAPI spec.
    defineTools(store = storeJson): any[] {
        const paths = Object.entries(store.paths) as [string, SdkRequestType][];
        const tools = paths.map(([path, refFunction]) =>
            this.wrapPath(path, refFunction)
        );
        return tools;
    }
  • Utility function used to define and wrap each tool handler with error handling and MCP protocol response formatting.
    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 full burden. It mentions 'Calculate' but doesn't disclose behavioral traits such as whether this is a read-only operation, if it requires authentication, potential side effects (e.g., updating cart state), rate limits, or error handling. This leaves critical operational details unspecified for a tool that likely interacts with cart data.

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 a single, direct sentence with no wasted words, effectively front-loading the core purpose. It's appropriately sized for a simple tool, though its brevity contributes to gaps in other dimensions like guidelines and parameter details.

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 the complexity (a calculation tool with 2 parameters), no annotations, 0% schema coverage, and no output schema, the description is incomplete. It fails to explain parameters, behavioral context, or return values, leaving the agent with significant uncertainty about how and when to use this tool effectively in the broader cart and shipping workflow.

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. It doesn't explain the 'id' (e.g., cart ID, shipping option ID) or 'fields' parameters, their formats, or required values. Without this, the agent lacks essential context to invoke the tool correctly, making the description insufficient for the two undocumented parameters.

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 ('Calculate') and resource ('price of a shipping option in a cart'), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'PostCartsIdShippingMethods' or 'GetShippingOptions', which might handle related shipping operations, leaving some ambiguity about its specific role.

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. With siblings like 'PostCartsIdShippingMethods' (which might set shipping methods) and 'GetShippingOptions' (which might list options), there's no indication of prerequisites, context (e.g., after adding items to a cart), or exclusions, relying solely on the agent to infer usage.

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