Raw
1 import { Note, Prerequisites, Table } from "docs-ui"
2
3 export const metadata = {
4 title: `Connect a Custom Agent to Medusa MCP`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to connect an AI agent that you build yourself to the [Medusa MCP server](../page.mdx) using OAuth and a Client ID Metadata Document.
10
11 ## How Custom Agents Authenticate
12
13 The Medusa MCP server follows the [2026-07-28 MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) and authenticates agents with OAuth 2.1. Your agent sends the user to Cloud to log in and approve the connection, then receives an access token that it sends with every request to the Medusa MCP server.
14
15 Before the OAuth flow starts, your agent must identify itself with a client ID. The 2026-07-28 specification deprecates Dynamic Client Registration in favor of Client ID Metadata Documents, so use a Client ID Metadata Document for new agents. The Medusa MCP server only supports Dynamic Client Registration for local agents, for backwards compatibility:
16
17 <Table>
18 <Table.Header>
19 <Table.Row>
20 <Table.HeaderCell>
21 Method
22 </Table.HeaderCell>
23 <Table.HeaderCell>
24 Use when
25 </Table.HeaderCell>
26 <Table.HeaderCell>
27 Redirect URIs
28 </Table.HeaderCell>
29 </Table.Row>
30 </Table.Header>
31 <Table.Body>
32 <Table.Row>
33 <Table.Cell>
34
35 [Client ID Metadata Document (CIMD)](#option-1-client-id-metadata-document)
36
37 </Table.Cell>
38 <Table.Cell>
39 Your agent is hosted, or you want the consent page to show your agent's name. Requires approval from Medusa.
40 </Table.Cell>
41 <Table.Cell>
42 The URIs listed in your document.
43 </Table.Cell>
44 </Table.Row>
45 <Table.Row>
46 <Table.Cell>
47
48 [Dynamic Client Registration](#option-2-dynamic-client-registration-for-local-agents)
49
50 </Table.Cell>
51 <Table.Cell>
52 Your agent runs on the user's machine, such as a CLI or desktop app. Doesn't require approval.
53 </Table.Cell>
54 <Table.Cell>
55
56 `localhost`, `127.0.0.1`, or `[::1]` only.
57
58 </Table.Cell>
59 </Table.Row>
60 </Table.Body>
61 </Table>
62
63 Both methods use the same [authorization flow](#run-the-authorization-flow) after your agent has a client ID.
64
65 <Note title="Tip">
66
67 The official [MCP SDKs](https://modelcontextprotocol.io/docs/sdk) discover the Medusa MCP server's OAuth endpoints, register the client, and run the authorization flow for you. If your agent uses an MCP SDK, refer to [Use an MCP SDK](#use-an-mcp-sdk).
68
69 </Note>
70
71 ### Prerequisites
72
73 <Prerequisites
74 items={[
75 {
76 text: "Cloud account",
77 link: "/sign-up",
78 },
79 {
80 text: "Environments built on or after October 8, 2026",
81 link: "/medusa-mcp#step-1-rebuild-environments",
82 },
83 ]}
84 />
85
86 ---
87
88 ## Option 1: Client ID Metadata Document
89
90 A Client ID Metadata Document (CIMD) is a JSON file that describes your agent, such as its name and the URLs that Cloud can redirect the user to after they approve the connection. You host the document at an HTTPS URL, and that URL becomes your agent's client ID.
91
92 When your agent starts the authorization flow, Cloud fetches the document from the client ID URL, validates it, and shows the agent's name on the consent page.
93
94 ### Prerequisite: Request Host Approval
95
96 <Prerequisites
97 items={[
98 {
99 text: "Medusa approval for your document's host",
100 link: "mailto:support@medusajs.com",
101 },
102 ]}
103 />
104
105 To protect the Medusa MCP server from requests to unknown servers, Cloud only fetches metadata documents from approved hosts. Until Medusa approves your document's host, Cloud rejects authorization requests from your agent with an `invalid_client_id` error.
106
107 Before you set up the document, email [support@medusajs.com](mailto:support@medusajs.com) to request approval with:
108
109 - The name of your Cloud organization.
110 - The URL that you'll host your document at, for example, `https://agent.example.com/oauth/client.json`.
111 - A short description of your agent.
112
113 Once Medusa informs you that it approved your host, follow the steps below.
114
115 ### Step 1: Create the Document
116
117 Create a JSON document with the following properties:
118
119 ```json title="client.json"
120 {
121 "client_id": "https://agent.example.com/oauth/client.json",
122 "client_name": "Example Agent",
123 "client_uri": "https://agent.example.com",
124 "redirect_uris": [
125 "https://agent.example.com/oauth/callback"
126 ]
127 }
128 ```
129
130 Where:
131
132 - `client_id`: The exact URL that you host the document at. Cloud rejects the document if this value doesn't match the URL it fetched the document from.
133 - `client_name`: The agent's name. Cloud shows it on the consent page.
134 - `client_uri`: (Optional) Your agent's website. Cloud only shows it on the consent page if it's an HTTPS URL.
135 - `redirect_uris`: The URLs that Cloud can redirect the user to with the authorization code. Your agent's authorization request must use one of these URLs exactly.
136
137 <Note>
138
139 If your agent runs on the user's machine and listens on a random `localhost` port, add the redirect URI without worrying about the port, such as `http://localhost/callback`. Cloud ignores the port when it compares `localhost`, `127.0.0.1`, and `[::1]` redirect URIs.
140
141 </Note>
142
143 ### Step 2: Host the Document
144
145 Host the document at the URL that you set in `client_id`. The URL must:
146
147 - Use HTTPS.
148 - Have a path, such as `/oauth/client.json`. A bare domain like `https://agent.example.com` isn't a valid client ID.
149 - Return the document directly with a `200` status. Cloud doesn't follow redirects.
150 - Return a document smaller than 64 KB within five seconds.
151
152 Cloud caches the document based on its `Cache-Control` response header, for between five minutes and one day. If the response has no `Cache-Control` header, Cloud caches it for one hour. So, changes to the document, such as new redirect URIs, can take up to the cache duration to take effect.
153
154 After you host the document, use its URL as the `client_id` in the [authorization flow](#run-the-authorization-flow).
155
156 ---
157
158 ## Option 2: Dynamic Client Registration for Local Agents
159
160 If your agent runs on your or the user's machine and receives the authorization code on a `localhost` redirect URI, you can register it with Dynamic Client Registration without approval from Medusa. For example, Claude Code can use this method to register a local agent.
161
162 <Note type="warning">
163
164 The MCP specification deprecates Dynamic Client Registration, and the Medusa MCP server only keeps it for backwards compatibility. Prefer a [Client ID Metadata Document](#option-1-client-id-metadata-document), which also works for local agents.
165
166 </Note>
167
168 Send a `POST` request to the `registration_endpoint` from the [authorization server metadata](#step-1-discover-the-oauth-endpoints):
169
170 ```bash
171 curl -X POST "$REGISTRATION_ENDPOINT" \
172 -H "Content-Type: application/json" \
173 -d '{
174 "client_name": "Example Agent",
175 "redirect_uris": [
176 "http://localhost:3334/callback"
177 ]
178 }'
179 ```
180
181 The response includes a `client_id` that you use in the [authorization flow](#run-the-authorization-flow). Cloud returns the same shared client ID to every agent that registers this way, so the consent page doesn't show your agent's `client_name`.
182
183 The registration fails with an `invalid_redirect_uri` error if any redirect URI isn't a `localhost`, `127.0.0.1`, or `[::1]` URL. To use other redirect URIs, use a [Client ID Metadata Document](#option-1-client-id-metadata-document) instead.
184
185 ---
186
187 ## Run the Authorization Flow
188
189 After your agent has a client ID, it runs the OAuth authorization code flow with PKCE to get an access token.
190
191 PKCE (Proof Key for Code Exchange) protects the authorization code from interception. Your agent generates a random secret called the code verifier, sends a hash of it when it starts the flow, and sends the verifier itself when it exchanges the code for a token. The Medusa MCP server requires PKCE with the `S256` method.
192
193 ### Step 1: Discover the OAuth Endpoints
194
195 Retrieve the authorization server metadata:
196
197 ```bash
198 curl \
199 https://cloud.medusajs.com/.well-known/oauth-authorization-server
200 ```
201
202 The response includes the `authorization_endpoint`, `token_endpoint`, and `registration_endpoint` URLs, and `client_id_metadata_document_supported: true`. Use the URLs from the response instead of hardcoding them.
203
204 <Note>
205
206 The Medusa MCP server also returns a `401` response with a `WWW-Authenticate` header when your agent calls it without a token. The header's `resource_metadata` parameter points to the protected resource metadata, which lists Cloud as the authorization server. MCP clients that follow the [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) use this to discover the endpoints.
207
208 </Note>
209
210 ### Step 2: Send the User to the Authorization Endpoint
211
212 Generate a code verifier and its `S256` code challenge, then open the following URL in the user's browser:
213
214 ```text
215 {authorization_endpoint}
216 ?response_type=code
217 &client_id={client_id}
218 &redirect_uri={redirect_uri}
219 &scope=openid
220 &code_challenge={code_challenge}
221 &code_challenge_method=S256
222 &state={state}
223 &resource=https://cloud.medusajs.com/mcp
224 ```
225
226 Where:
227
228 - `authorization_endpoint`: The `authorization_endpoint` URL from the [authorization server metadata](#step-1-discover-the-oauth-endpoints) that you retrieved in the previous step.
229 - `client_id`: Your document's URL, or the client ID returned by Dynamic Client Registration. URL-encode it.
230 - `redirect_uri`: One of your registered redirect URIs.
231 - `scope`: One or more of `openid`, `email`, and `profile`, separated by spaces. Cloud rejects other scopes with an `unsupported_scope` error.
232 - `code_challenge`: The Base64URL-encoded SHA-256 hash of the code verifier.
233 - `state`: A random value that your agent checks when Cloud redirects back, to prevent cross-site request forgery.
234 - `resource`: The Medusa MCP server's URL, `https://cloud.medusajs.com/mcp`. If you omit it, the access token doesn't grant access to the Medusa MCP server.
235
236 <Note type="warning">
237
238 Use a new code verifier and `state` value for every authorization request, and never log or share the code verifier.
239
240 </Note>
241
242 The user logs in to their Cloud account and [approves the connection](../page.mdx#approve-the-connection) on the consent page, selecting the environments that your agent can access. Cloud then redirects the user to your `redirect_uri` with a `code` and the `state` query parameters.
243
244 ### Step 3: Exchange the Code for Tokens
245
246 Send a `POST` request to the `token_endpoint` with the authorization code and code verifier:
247
248 ```bash
249 curl -X POST "$TOKEN_ENDPOINT" \
250 -H "Content-Type: application/x-www-form-urlencoded" \
251 --data-urlencode "grant_type=authorization_code" \
252 --data-urlencode "code=$CODE" \
253 --data-urlencode "redirect_uri=$REDIRECT_URI" \
254 --data-urlencode "client_id=$CLIENT_ID" \
255 --data-urlencode "code_verifier=$CODE_VERIFIER"
256 ```
257
258 The `redirect_uri` must be the same value that you sent in the authorization request. Your agent doesn't send a client secret.
259
260 The response includes an `access_token`, its `expires_in` duration in seconds, and a `refresh_token`. Store both tokens securely.
261
262 ### Step 4: Call the Medusa MCP Server
263
264 Connect your agent's MCP client to the Medusa MCP server, which is a Streamable HTTP server at `https://cloud.medusajs.com/mcp`. Send the access token in the `Authorization` header of every request.
265
266 For example, the following request calls the `list_connected_environments` tool:
267
268 ```bash
269 curl -X POST https://cloud.medusajs.com/mcp \
270 -H "Authorization: Bearer $ACCESS_TOKEN" \
271 -H "Content-Type: application/json" \
272 -H "Accept: application/json, text/event-stream" \
273 -H "MCP-Protocol-Version: 2026-07-28" \
274 -H "Mcp-Method: tools/call" \
275 -H "Mcp-Name: list_connected_environments" \
276 -d '{
277 "jsonrpc": "2.0",
278 "id": 1,
279 "method": "tools/call",
280 "params": {
281 "name": "list_connected_environments",
282 "arguments": {},
283 "_meta": {
284 "io.modelcontextprotocol/protocolVersion": "2026-07-28",
285 "io.modelcontextprotocol/clientInfo": {
286 "name": "example-agent",
287 "version": "1.0.0"
288 },
289 "io.modelcontextprotocol/clientCapabilities": {}
290 }
291 }
292 }'
293 ```
294
295 The 2026-07-28 specification has no `initialize` handshake. Each request carries the protocol version and client details in its `_meta` field, and the `MCP-Protocol-Version`, `Mcp-Method`, and `Mcp-Name` headers must match the request body.
296
297 Refer to the [Medusa MCP](../page.mdx#available-tools) guide for the tools that your agent can call.
298
299 ### Step 5: Refresh the Access Token
300
301 When the access token expires, send a `POST` request to the `token_endpoint` with the refresh token:
302
303 ```bash
304 curl -X POST "$TOKEN_ENDPOINT" \
305 -H "Content-Type: application/x-www-form-urlencoded" \
306 --data-urlencode "grant_type=refresh_token" \
307 --data-urlencode "refresh_token=$REFRESH_TOKEN" \
308 --data-urlencode "client_id=$CLIENT_ID"
309 ```
310
311 The response includes a new access token and a new refresh token. Cloud rotates the refresh token on every refresh, so store the new refresh token and discard the old one. A refresh token expires after seven days.
312
313 If the refresh fails with an `invalid_grant` error, start the [authorization flow](#step-2-send-the-user-to-the-authorization-endpoint) again.
314
315 ---
316
317 ## Use an MCP SDK
318
319 The official [MCP SDKs](https://modelcontextprotocol.io/docs/sdk) implement the authorization flow in this guide. You provide your client's details and storage for tokens, and the SDK discovers the endpoints, registers the client, and refreshes tokens.
320
321 For example, with the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk), set the `clientMetadataUrl` property of your `OAuthClientProvider` implementation to your document's URL:
322
323 ```ts title="medusa-auth-provider.ts"
324 import type {
325 OAuthClientProvider,
326 } from "@modelcontextprotocol/sdk/client/auth.js"
327
328 class MedusaAuthProvider implements OAuthClientProvider {
329 clientMetadataUrl =
330 "https://agent.example.com/oauth/client.json"
331
332 get redirectUrl() {
333 return "https://agent.example.com/oauth/callback"
334 }
335
336 get clientMetadata() {
337 return {
338 client_name: "Example Agent",
339 redirect_uris: [this.redirectUrl],
340 }
341 }
342
343 // ... token, code verifier, and redirect methods
344 }
345 ```
346
347 Because the Medusa MCP server sets `client_id_metadata_document_supported` in its metadata, the SDK uses your document's URL as the client ID. If you don't set `clientMetadataUrl`, the SDK falls back to [Dynamic Client Registration](#option-2-dynamic-client-registration-for-local-agents), which only works with `localhost` redirect URIs.
348
349 Refer to the [MCP TypeScript SDK's OAuth documentation](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/clients/oauth.md) for the full provider implementation.
350
351 ---
352
353 ## Troubleshooting
354
355 ### invalid_client_id Error
356
357 If the authorization endpoint returns an `invalid_client_id` error for your Client ID Metadata Document, make sure that:
358
359 - Medusa [approved your document's host](#prerequisite-request-host-approval).
360 - The document's `client_id` exactly matches the URL that you host it at, including the path.
361 - The document includes `client_name` and a non-empty `redirect_uris` array.
362 - The URL returns the document with a `200` status, without redirecting, in under five seconds.
363
364 ### invalid_redirect_uri Error
365
366 If the authorization endpoint returns an `invalid_redirect_uri` error, the `redirect_uri` in your authorization request doesn't exactly match one of your registered redirect URIs. For a Client ID Metadata Document, add the URI to `redirect_uris` and wait for Cloud's cached copy of the document to expire.
367
368 If you use Dynamic Client Registration, only `localhost`, `127.0.0.1`, and `[::1]` redirect URIs are allowed.
369
370 ### Agent Gets 401 Errors After Authorization
371
372 If the Medusa MCP server returns a `401` error for requests with your access token, make sure that you sent `resource=https://cloud.medusajs.com/mcp` in the authorization request. Tokens issued without the `resource` parameter don't grant access to the Medusa MCP server.
373
374 For other errors, refer to the [Medusa MCP troubleshooting](../page.mdx#troubleshooting) section.