1 import { Note, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Retrieve Custom Data with Medusa MCP`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to expose custom data from your store to AI tools connected to the [Medusa MCP server](../page.mdx), using abandoned carts as an example.
10
11 ## Why Add Custom API Routes?
12
13 The Medusa MCP server retrieves data by calling your store's `GET` API routes. Medusa's Admin and Store API routes cover common requests, such as listing orders or products. However, some questions need data that no existing API route returns, such as:
14
15 - Carts that customers abandoned in the last day.
16 - Products that haven't sold in the last month.
17 - Data from your own [custom modules](!docs!/learn/fundamentals/modules), such as brands or suppliers.
18
19 To answer these questions, create a custom `GET` [API route](!docs!/learn/fundamentals/api-routes) under the `/admin` or `/store` prefix that returns the data. After you deploy the API route to Cloud, the AI tool finds and calls it when you ask a related question.
20
21 <Note>
22
23 The AI tool can't find or call custom API routes under other prefixes, such as `/custom`. It also can't call `POST` or `DELETE` API routes, since the Medusa MCP server is read-only.
24
25 </Note>
26
27 <Prerequisites
28 items={[
29 {
30 text: "AI tool connected to the Medusa MCP server",
31 link: "/medusa-mcp#connect-to-the-medusa-mcp-server",
32 },
33 {
34 text: "Medusa application deployed to Cloud",
35 link: "/deployments",
36 },
37 ]}
38 />
39
40 ## Choose the API Route Prefix
41
42 The prefix of your API route determines how the AI tool calls it:
43
44 - **`/admin`**: The AI tool calls the API route as your admin user. Use this prefix for data that only admin users should access, such as abandoned carts or customer details.
45 - **`/store`**: The AI tool calls the API route as a guest customer with a publishable API key. Use this prefix for data that shoppers can access, such as products in a sales channel.
46
47 <Note type="warning">
48
49 The AI tool can't call `/store` API routes that require a logged-in customer. If the AI tool needs that data, expose it in an `/admin` API route instead.
50
51 </Note>
52
53 ---
54
55 ## Example: Retrieve Abandoned Carts
56
57 In this section, you'll create an API route that returns abandoned carts. You can then ask your AI tool questions like "Which carts were abandoned in the last 24 hours?".
58
59 ### Step 1: Add the Validation Middleware
60
61 First, define a [Zod](https://zod.dev/) schema that validates the API route's query parameters, and apply it to the API route in `src/api/middlewares.ts`:
62
63 ```ts title="src/api/middlewares.ts"
64 import {
65 defineMiddlewares,
66 validateAndTransformQuery,
67 } from "@medusajs/framework/http"
68 import { z } from "@medusajs/framework/zod"
69
70 export const AdminGetAbandonedCartsParams = z.object({
71 /**
72 * Return carts not updated in this number of hours.
73 */
74 hours: z.coerce.number().min(1).default(24),
75 /**
76 * The maximum number of carts to return.
77 */
78 limit: z.coerce.number().max(100).default(20),
79 /**
80 * The number of carts to skip.
81 */
82 offset: z.coerce.number().default(0),
83 })
84
85 export type AdminGetAbandonedCartsParamsType = z.infer<
86 typeof AdminGetAbandonedCartsParams
87 >
88
89 export default defineMiddlewares({
90 routes: [
91 {
92 matcher: "/admin/abandoned-carts",
93 methods: ["GET"],
94 middlewares: [
95 validateAndTransformQuery(
96 AdminGetAbandonedCartsParams,
97 {}
98 ),
99 ],
100 },
101 ],
102 })
103 ```
104
105 The schema accepts the following query parameters:
106
107 - `hours`: Carts that weren't updated within this number of hours are considered abandoned.
108 - `limit` and `offset`: Paginate the returned carts, similar to Medusa's list API routes.
109
110 The comments on each property help the AI tool understand what the parameter does.
111
112 The middleware validates the query parameters and sets them in the `req.validatedQuery` property. Learn more in the [Request Validation](!docs!/learn/fundamentals/api-routes/validation) chapter.
113
114 ### Step 2: Create the API Route
115
116 Next, create the API route that retrieves the abandoned carts. Create the file `src/api/admin/abandoned-carts/route.ts` with the following content:
117
118 ```ts title="src/api/admin/abandoned-carts/route.ts"
119 import {
120 AuthenticatedMedusaRequest,
121 MedusaResponse,
122 } from "@medusajs/framework/http"
123 import {
124 ContainerRegistrationKeys,
125 } from "@medusajs/framework/utils"
126 import {
127 AdminGetAbandonedCartsParamsType,
128 } from "../../middlewares"
129
130 type AbandonedCart = {
131 id: string
132 email: string | null
133 currency_code: string
134 updated_at: Date
135 items: {
136 title: string
137 quantity: number
138 unit_price: number
139 }[]
140 }
141
142 type AdminAbandonedCartsResponse = {
143 carts: AbandonedCart[]
144 count: number
145 limit: number
146 offset: number
147 }
148
149 /**
150 * List abandoned carts
151 *
152 * Retrieve carts with an email that customers didn't
153 * complete or update within the specified number of hours.
154 */
155 export const GET = async (
156 req: AuthenticatedMedusaRequest<
157 unknown,
158 AdminGetAbandonedCartsParamsType
159 >,
160 res: MedusaResponse<AdminAbandonedCartsResponse>
161 ) => {
162 const query = req.scope.resolve(
163 ContainerRegistrationKeys.QUERY
164 )
165 const { hours, limit, offset } = req.validatedQuery
166
167 const abandonedBefore = new Date(
168 Date.now() - hours * 60 * 60 * 1000
169 )
170
171 const { data: carts, metadata } = await query.graph({
172 entity: "cart",
173 fields: [
174 "id",
175 "email",
176 "currency_code",
177 "updated_at",
178 "items.title",
179 "items.quantity",
180 "items.unit_price",
181 ],
182 filters: {
183 updated_at: {
184 $lt: abandonedBefore,
185 },
186 email: {
187 $ne: null,
188 },
189 completed_at: null,
190 },
191 pagination: {
192 skip: offset,
193 take: limit,
194 },
195 })
196
197 res.json({
198 carts: carts as AbandonedCart[],
199 count: metadata?.count ?? 0,
200 limit,
201 offset,
202 })
203 }
204 ```
205
206 Keep the following in mind when you create API routes for the AI tool:
207
208 - **Add a comment above the `GET` function**: Medusa uses the comment's first line as the API route's summary and the rest as its description. The AI tool searches these to find the API route that matches your question, so use words you'd use when asking, such as "abandoned carts".
209 - **Type the request and response**: Medusa reads the query parameters from the request's type, such as the second type argument of `AuthenticatedMedusaRequest`, and the response's shape from `MedusaResponse`. Without these types, the AI tool doesn't know which parameters the API route accepts.
210 - **Paginate list responses**: Accept `limit` and `offset` query parameters, and return `count`, `limit`, and `offset` in the response, like Medusa's list API routes. The AI tool uses them to page through results, and smaller responses are faster to process.
211 - **Keep the response shallow**: Medusa truncates the documented response shape of deeply nested or very large types. Return only the fields the AI tool needs.
212
213 <Note>
214
215 Medusa reads the query parameters from the API route's types, not from the middleware. So, you need both the middleware to validate the parameters, and the types in the API route for the AI tool to know about them.
216
217 </Note>
218
219 ---
220
221 ## Deploy and Ask Your AI Tool
222
223 Medusa indexes your store's API routes, including custom ones, each time the environment builds. So, the AI tool can only find your new API route after you deploy it.
224
225 To deploy the API route, push your changes to the branch of the environment, as explained in the [Deployments](../../deployments/page.mdx) guide. Once the deployment is live, ask your AI tool a question that the API route answers. For example:
226
227 - "Which carts were abandoned in the last 24 hours in my store?"
228 - "List the emails of customers who abandoned their carts in the last 3 days, with their cart items."
229
230 The AI tool searches your store's API routes, finds the `/admin/abandoned-carts` API route, and calls it with the `hours` query parameter based on your question.
231
232 <Note>
233
234 When you update an API route's code, comments, or types, deploy the changes again so the AI tool uses the updated API route.
235
236 </Note>
237
238 ---
239
240 ## Troubleshooting
241
242 ### AI Tool Doesn't Find the Custom API Route
243
244 If the AI tool doesn't find your custom API route, make sure that:
245
246 - The API route's path starts with `/admin` or `/store`, and its folder names don't start with an underscore (`_`).
247 - The API route's file exports a `GET` function.
248 - The environment built and deployed after you added the API route. Redeploying an existing deployment reuses its previous build, so Medusa doesn't index the new API route.
249 - The comment above the `GET` function describes the data with the words you use in your question. You can also mention the API route's path in your question, such as "Use the `/admin/abandoned-carts` API route".
250
251 ### Store API Route Returns an Authentication Error
252
253 The AI tool calls `/store` API routes as a guest customer. If your `/store` API route requires a logged-in customer, the AI tool can't call it. Expose the data in an `/admin` API route instead.
254
255 ### Admin API Route Returns a Permission Error
256
257 The AI tool calls `/admin` API routes as your admin user. If your API route applies custom permission checks, make sure your admin user is allowed to access it.