Connect a Custom Agent to Medusa MCP

In this guide, you'll learn how to connect an AI agent that you build to the Medusa MCP server using OAuth and a Client ID Metadata Document.

How Custom Agents Authenticate#

The Medusa MCP server follows the 2026-07-28 MCP specification and authenticates agents with OAuth 2.1. Your agent sends the user to Cloud to log in and approve the connection, then sends the access token it receives with every request.

Before the OAuth flow starts, your agent identifies 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:

Method

Use when

Redirect URIs

Client ID Metadata Document (CIMD)

Your agent is hosted, or you want the consent page to show your agent's name. Requires approval from Medusa.

The URIs listed in your document.

Dynamic Client Registration

Your agent runs on the user's machine, such as a CLI or desktop app. Doesn't require approval.

localhost, 127.0.0.1, or [::1] only.

Both methods then use the same authorization flow.

Tip: The official MCP SDKs discover the OAuth endpoints, register the client, and run the authorization flow for you. Refer to Use an MCP SDK.

Prerequisites#


Option 1: Client ID Metadata Document#

A Client ID Metadata Document (CIMD) is a JSON file that describes your agent, such as its name and the URLs Medusa can redirect the user to after approval. You host it at an HTTPS URL, which becomes your agent's client ID. When the authorization flow starts, Cloud fetches and validates the document, and shows the agent's name on the consent page.

Prerequisite: Request Host Approval#

Cloud only fetches metadata documents from approved hosts. Until Medusa approves your document's host, it rejects your agent's authorization requests with an invalid_client_id error.

Before you set up the document, email support@medusajs.com to request approval with:

  • The name of your Cloud organization.
  • The URL that you'll host your document at, for example, https://agent.example.com/oauth/client.json.
  • A short description of your agent.

Once Medusa approves your host, follow the steps below.

Step 1: Create the Document#

Create a JSON document with the following properties:

client.json
{
  "client_id": "https://agent.example.com/oauth/client.json",
  "client_name": "Example Agent",
  "client_uri": "https://agent.example.com",
  "redirect_uris": [
    "https://agent.example.com/oauth/callback"
  ]
}

Where:

  • client_id: The exact URL that you host the document at. Medusa rejects the document if it doesn't match the fetched URL.
  • client_name: The agent's name, shown on the consent page.
  • client_uri: (Optional) Your agent's website. Cloud only shows it on the consent page if it's an HTTPS URL.
  • redirect_uris: The URLs that Medusa can redirect the user to with the authorization code. Your agent's authorization request must use one of these URLs exactly.
Note: If your agent runs on the user's machine and listens on a random localhost port, add the redirect URI without a port, such as http://localhost/callback. Medusa ignores the port when it compares localhost, 127.0.0.1, and [::1] redirect URIs.

Step 2: Host the Document#

Host the document at the URL that you set in client_id. The URL must:

  • Use HTTPS.
  • Have a path, such as /oauth/client.json. A bare domain like https://agent.example.com isn't a valid client ID.
  • Return the document directly with a 200 status. Cloud doesn't follow redirects.
  • Return a document smaller than 64 KB within five seconds.

Medusa caches the document based on its Cache-Control response header, for between five minutes and one day, or one hour without the header. Changes to the document, such as new redirect URIs, take effect when the cache expires.

Then, use the document's URL as the client_id in the authorization flow.


Option 2: Dynamic Client Registration for Local Agents#

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 Medusa's approval. For example, Claude Code can use this method.

Warning: The MCP specification deprecates Dynamic Client Registration, and the Medusa MCP server only keeps it for backwards compatibility. Prefer a Client ID Metadata Document, which also works for local agents.

Send a POST request to the registration_endpoint from the authorization server metadata:

Code
curl -X POST "$REGISTRATION_ENDPOINT" \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "Example Agent",
    "redirect_uris": [
      "http://localhost:3334/callback"
    ]
  }'

Use the response's client_id in the authorization flow. Medusa returns the same shared client ID to every agent registered this way, so the consent page doesn't show your agent's client_name.

Registration fails with an invalid_redirect_uri error if any redirect URI isn't a localhost, 127.0.0.1, or [::1] URL. For other redirect URIs, use a Client ID Metadata Document instead.


Run the Authorization Flow#

With a client ID, your agent runs the OAuth authorization code flow with PKCE to get an access token.

PKCE (Proof Key for Code Exchange) protects the authorization code from interception. Your agent generates a random secret called the code verifier, sends its hash when it starts the flow, and sends the verifier itself when it exchanges the code for a token. The Medusa MCP server requires the S256 method.

Step 1: Discover the OAuth Endpoints#

Retrieve the authorization server metadata:

Code
curl \
  https://cloud.medusajs.com/.well-known/oauth-authorization-server

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.

Note: The Medusa MCP server also returns a 401 response with a WWW-Authenticate header to calls without a token. The header's resource_metadata parameter points to the protected resource metadata, which lists Medusa as the authorization server. MCP clients that follow the MCP authorization specification use this to discover the endpoints.

Step 2: Send the User to the Authorization Endpoint#

Generate a code verifier and its S256 code challenge, then open the following URL in the user's browser:

Code
{authorization_endpoint}
  ?response_type=code
  &client_id={client_id}
  &redirect_uri={redirect_uri}
  &scope=openid
  &code_challenge={code_challenge}
  &code_challenge_method=S256
  &state={state}
  &resource=https://cloud.medusajs.com/mcp

Where:

  • authorization_endpoint: The authorization_endpoint URL from the authorization server metadata.
  • client_id: Your document's URL, or the client ID returned by Dynamic Client Registration. URL-encode it.
  • redirect_uri: One of your registered redirect URIs.
  • scope: One or more of openid, email, and profile, separated by spaces. Medusa rejects other scopes with an unsupported_scope error.
  • code_challenge: The Base64URL-encoded SHA-256 hash of the code verifier.
  • state: A random value your agent checks on redirect, to prevent cross-site request forgery.
  • 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.
Warning: Use a new code verifier and state value for every authorization request, and never log or share the code verifier.

The user logs in and approves the connection, selecting the environments your agent can access. Medusa then redirects the user to your redirect_uri with the code and state query parameters.

Step 3: Exchange the Code for Tokens#

Send a POST request to the token_endpoint with the authorization code and code verifier:

Code
curl -X POST "$TOKEN_ENDPOINT" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=authorization_code" \
  --data-urlencode "code=$CODE" \
  --data-urlencode "redirect_uri=$REDIRECT_URI" \
  --data-urlencode "client_id=$CLIENT_ID" \
  --data-urlencode "code_verifier=$CODE_VERIFIER"

The redirect_uri must match the authorization request's value. Your agent doesn't send a client secret.

The response includes an access_token, its expires_in duration in seconds, and a refresh_token. Store both tokens securely.

Step 4: Call the Medusa MCP Server#

Connect your agent's MCP client to the Medusa MCP server, a Streamable HTTP server at https://cloud.medusajs.com/mcp, and send the access token in every request's Authorization header. For example, this request calls the list_connected_environments tool:

Code
curl -X POST https://cloud.medusajs.com/mcp \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "MCP-Protocol-Version: 2026-07-28" \
  -H "Mcp-Method: tools/call" \
  -H "Mcp-Name: list_connected_environments" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "list_connected_environments",
      "arguments": {},
      "_meta": {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientInfo": {
          "name": "example-agent",
          "version": "1.0.0"
        },
        "io.modelcontextprotocol/clientCapabilities": {}
      }
    }
  }'

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.

Refer to the Medusa MCP guide for the tools that your agent can call.

Step 5: Refresh the Access Token#

When the access token expires, send a POST request to the token_endpoint with the refresh token:

Code
curl -X POST "$TOKEN_ENDPOINT" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=refresh_token" \
  --data-urlencode "refresh_token=$REFRESH_TOKEN" \
  --data-urlencode "client_id=$CLIENT_ID"

The response includes a new access token and refresh token. Cloud rotates the refresh token on every refresh, so store the new one and discard the old one. A refresh token expires after seven days.

If the refresh fails with an invalid_grant error, start the authorization flow again.


Use an MCP SDK#

The official MCP SDKs implement this guide's authorization flow. You provide your client's details and token storage, and the SDK discovers the endpoints, registers the client, and refreshes tokens.

For example, with the MCP TypeScript SDK, set the clientMetadataUrl property of your OAuthClientProvider implementation to your document's URL:

medusa-auth-provider.ts
import type {
  OAuthClientProvider,
} from "@modelcontextprotocol/sdk/client/auth.js"

class MedusaAuthProvider implements OAuthClientProvider {
  clientMetadataUrl =
    "https://agent.example.com/oauth/client.json"

  get redirectUrl() {
    return "https://agent.example.com/oauth/callback"
  }

  get clientMetadata() {
    return {
      client_name: "Example Agent",
      redirect_uris: [this.redirectUrl],
    }
  }

  // ... token, code verifier, and redirect methods
}

Since the Medusa MCP server sets client_id_metadata_document_supported in its metadata, the SDK uses your document's URL as the client ID. Without clientMetadataUrl, the SDK falls back to Dynamic Client Registration, which only works with localhost redirect URIs.

Refer to the MCP TypeScript SDK's OAuth documentation for the full provider implementation.


Troubleshooting#

invalid_client_id Error#

If the authorization endpoint returns an invalid_client_id error for your Client ID Metadata Document, make sure that:

  • Medusa approved your document's host.
  • The document's client_id exactly matches the URL that you host it at, including the path.
  • The document includes client_name and a non-empty redirect_uris array.
  • The URL returns the document with a 200 status, without redirecting, in under five seconds.

invalid_redirect_uri Error#

The redirect_uri in your authorization request doesn't exactly match a registered redirect URI. For a Client ID Metadata Document, add the URI to redirect_uris and wait for Cloud's cached copy of the document to expire. With Dynamic Client Registration, only localhost, 127.0.0.1, and [::1] redirect URIs are allowed.

Agent Gets 401 Errors After Authorization#

Make sure that you sent resource=https://cloud.medusajs.com/mcp in the authorization request. Tokens issued without it don't grant access to the Medusa MCP server.

For other errors, refer to the Medusa MCP troubleshooting section.

Was this guide helpful?
Docs Assistant
For assistance in your development, use Claude Code Plugins or Docs MCP server in Cursor, VSCode, etc...FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break
⇧↵