diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index c84944435..62964ae13 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -2,6 +2,9 @@ name: Lint and Type Check on: [pull_request] +permissions: + contents: read + concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number }} cancel-in-progress: true @@ -73,6 +76,74 @@ jobs: - name: Build run: yarn build + unit: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --immutable + + - name: Run unit tests + run: yarn test:unit + + integration: + runs-on: ubuntu-latest + timeout-minutes: 20 + services: + postgres: + image: postgres:16 + env: + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres" + --health-interval 2s + --health-timeout 5s + --health-retries 30 + redis: + image: redis + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" + --health-interval 2s + --health-timeout 5s + --health-retries 30 + env: + DB_HOST: localhost + DB_USERNAME: postgres + DB_PASSWORD: postgres + # The Stripe payment provider refuses to load without a key; these tests never call Stripe. + STRIPE_API_KEY: sk_test_placeholder_for_integration_tests + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --immutable + + - name: Build workspace plugins + run: yarn workspace @lambdacurry/medusa-mcp build + + - name: Run HTTP integration tests + run: yarn workspace medusa test:integration:http + e2e: runs-on: ubuntu-latest timeout-minutes: 20 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..d9b89515b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,51 @@ +# Barrio (medusa2-starter) + +Medusa 2 backend (`apps/medusa`), React Router storefront (`apps/storefront`), Playwright e2e (`apps/e2e`), and +the `@lambdacurry/medusa-mcp` plugin (`packages/medusa-mcp`), in one Yarn 4 + Turbo monorepo. + +## Deploys + +Railway auto-deploys `main` to the live Barrio store. The MCP work lands on `feat/medusa-mcp`, not `main`, until +someone decides to take it live. + +## Commands + +- `yarn dev`: builds workspace plugins, then starts Medusa and the storefront. +- `yarn test:unit`: unit tests for the Medusa app and the MCP plugin, the two workspaces that have them. +- `yarn workspace @lambdacurry/medusa-mcp build`: rebuild the plugin. Restart Medusa afterwards, because the running + app does not reload plugin build output. +- `yarn e2e`: boots everything and runs Playwright. It runs `medusa:init`, which wipes the local database + (`docker compose down -v`). Set `E2E_SKIP_MEDUSA_INIT=true` to keep the existing data. + +## OpenAPI contracts for custom API routes + +Every `route.ts` under `apps/medusa/src/api/admin` or `apps/medusa/src/api/store` needs an `openapi.ts` next to it. +The MCP plugin indexes the published spec built from these contracts, and +`apps/medusa/src/__tests__/openapi-contracts.unit.spec.ts` fails when a contract is missing or disagrees with its +route. + +- The contract default-exports `{ tag, operations }` and documents exactly the methods the route exports. +- Each operation has a globally unique camelCase `operationId`, a `summary`, `responses`, and optional `query` and + `body` Zod schemas. Import Zod from `@medusajs/framework/zod`. +- Set `hidden: true` to keep an internal or unsafe route out of the spec. +- Type the export with `satisfies OpenApiRouteContract` from `@lambdacurry/medusa-mcp/openapi`. + +```ts +import type { OpenApiRouteContract } from '@lambdacurry/medusa-mcp/openapi'; +import { z } from '@medusajs/framework/zod'; + +export default { + tag: 'Widgets', + operations: { + GET: { + operationId: 'listAdminWidgets', + summary: 'List widgets', + query: z.object({ limit: z.coerce.number().optional() }), + responses: { 200: { description: 'Widgets', schema: z.object({ widgets: z.array(z.looseObject({ id: z.string() })) }) } }, + }, + }, +} satisfies OpenApiRouteContract; +``` + +The core Medusa spec is pinned per Medusa version in `packages/medusa-mcp/specs/`. After upgrading +`@medusajs/medusa`, run `yarn workspace @lambdacurry/medusa-mcp fetch-core-specs `. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/apps/e2e/scripts/run-e2e.ts b/apps/e2e/scripts/run-e2e.ts index f45af4e3f..801c58c1b 100644 --- a/apps/e2e/scripts/run-e2e.ts +++ b/apps/e2e/scripts/run-e2e.ts @@ -50,6 +50,7 @@ const baseEnv: NodeJS.ProcessEnv = { PUBLIC_MEDUSA_API_URL: process.env.PUBLIC_MEDUSA_API_URL ?? medusaUrl, INTERNAL_MEDUSA_API_URL: process.env.INTERNAL_MEDUSA_API_URL ?? medusaUrl, STOREFRONT_URL: process.env.STOREFRONT_URL ?? storefrontUrl, + STOREFRONT_REVALIDATE_SECRET: process.env.STOREFRONT_REVALIDATE_SECRET ?? 'e2e-revalidate-secret', STRIPE_PUBLIC_KEY: process.env.STRIPE_PUBLIC_KEY ?? 'pk_test_e2e', STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY ?? 'sk_test_e2e', }; @@ -271,6 +272,15 @@ async function main() { process.on('SIGTERM', () => onSignal(143)); try { + process.stdout.write('Building workspace Medusa plugins...\n'); + await runCommand({ + command: 'yarn', + args: ['workspace', '@lambdacurry/medusa-mcp', 'build'], + cwd: repoRoot, + env: baseEnv, + logLabel: 'yarn workspace @lambdacurry/medusa-mcp build', + }); + process.stdout.write('Preparing Medusa database for E2E...\n'); createdMedusaEnvFile = ensureMedusaEnvFile(); await seedMedusa(); diff --git a/apps/e2e/tests/mcp-demo.spec.ts b/apps/e2e/tests/mcp-demo.spec.ts new file mode 100644 index 000000000..d137c87b6 --- /dev/null +++ b/apps/e2e/tests/mcp-demo.spec.ts @@ -0,0 +1,136 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { expect, test } from '@playwright/test'; + +// The recorded demo, end to end: an agent connects over OAuth, finds the product update operation, previews and +// applies a new description through MCP, and the storefront shows it. +const medusaUrl = process.env.E2E_MEDUSA_URL ?? 'http://127.0.0.1:9000'; +const admin = { email: 'admin@medusa-test.com', password: 'supersecret' }; +const handle = 'barrio-decaf-medium-roast'; +const redirectUri = 'http://localhost:6274/oauth/callback'; + +const form = (data: Record | [string, string][]) => new URLSearchParams(data); +const hidden = (html: string, name: string) => { + const value = html.match(new RegExp(`name="${name}" value="([^"]+)"`))?.[1]; + if (!value) throw new Error(`No ${name} field on the authorize page`); + return value.replaceAll('"', '"').replaceAll('&', '&'); +}; + +/** Fails with the step name, status, and a body excerpt when a response is not one of the expected statuses. */ +async function checked(step: string, response: Response, expected: number[] = [200]): Promise { + if (!expected.includes(response.status)) { + throw new Error(`${step} returned HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`); + } + return response; +} + +async function connect(): Promise { + const scopes = ['mcp:read', 'mcp:write']; + const registration = await fetch(`${medusaUrl}/oauth/register`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ client_name: 'Demo agent', redirect_uris: [redirectUri] }), + }); + const { client_id } = (await (await checked('Client registration', registration, [201])).json()) as { + client_id: string; + }; + const verifier = randomBytes(32).toString('base64url'); + const challenge = createHash('sha256').update(verifier).digest('base64url'); + + const login = await fetch( + `${medusaUrl}/oauth/authorize?${form({ response_type: 'code', client_id, redirect_uri: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', scope: scopes.join(' ') })}`, + ); + const consent = await fetch(`${medusaUrl}/oauth/authorize/login`, { + method: 'POST', + body: form({ request: hidden(await (await checked('Authorize', login)).text(), 'request'), ...admin }), + }); + const approved = await fetch(`${medusaUrl}/oauth/authorize/consent`, { + method: 'POST', + redirect: 'manual', + body: form([ + ['grant', hidden(await (await checked('Sign-in', consent)).text(), 'grant')], + ['decision', 'approve'], + ...scopes.map((scope): [string, string] => ['scope', scope]), + ]), + }); + await checked('Consent', approved, [302]); + const code = new URL(approved.headers.get('location') as string).searchParams.get('code') as string; + const tokens = await fetch(`${medusaUrl}/oauth/token`, { + method: 'POST', + body: form({ + grant_type: 'authorization_code', + code, + client_id, + redirect_uri: redirectUri, + code_verifier: verifier, + }), + }); + return ((await (await checked('Token exchange', tokens)).json()) as { access_token: string }).access_token; +} + +async function tool(token: string, name: string, args: Record) { + const response = await fetch(`${medusaUrl}/mcp`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + 'mcp-protocol-version': '2025-06-18', + authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), + }); + const text = await response.text(); + const json = text.trimStart().startsWith('{') + ? text + : text + .split('\n') + .find((line) => line.startsWith('data:')) + ?.slice(5); + const result = JSON.parse(json ?? 'null')?.result; + if (!result || result.isError) throw new Error(`${name} failed: ${JSON.stringify(result ?? text).slice(0, 500)}`); + return result.structuredContent; +} + +test('an agent updates a product description through MCP and the storefront shows it', async ({ page }) => { + await page.goto(`/products/${handle}`); + await expect(page.getByRole('heading', { name: 'Barrio Decaf - Medium Roast' })).toBeVisible(); + + const token = await connect(); + const search = await tool(token, 'search_api', { query: 'update a product description' }); + expect(search.results[0].operation).toBe('POST /admin/products/{id}'); + + const found = await tool(token, 'read_api', { + operation: 'GET /admin/products', + query: { handle, fields: 'id,description', limit: 1 }, + }); + const { id, description: original } = found.body.products[0] as { id: string; description: string }; + await expect(page.getByText(original)).toBeVisible(); + + const updated = `Updated by an AI agent through MCP at ${new Date().toISOString()}.`; + const change = { operation: 'POST /admin/products/{id}', path_params: { id }, body: { description: updated } }; + let testFailed = false; + try { + const preview = await tool(token, 'write_api', { ...change, dry_run: true }); + expect(preview.changes).toEqual([{ field: 'description', current: original, proposed: updated }]); + + const applied = await tool(token, 'write_api', change); + expect(applied.status).toBe(200); + + // Medusa notifies the storefront asynchronously after the write. Keep this window under the storefront's + // 10-second cache TTL: a longer one would pass by waiting the cache out and hide a missing revalidation. + await expect(async () => { + await page.reload(); + await expect(page.getByText(updated)).toBeVisible({ timeout: 500 }); + }).toPass({ timeout: 5000 }); + } catch (error) { + testFailed = true; + throw error; + } finally { + // A failed restore fails a passing test, since the next run would read the test text as the original. After a + // test failure it is only logged, so the original failure stays the one reported. + await tool(token, 'write_api', { ...change, body: { description: original } }).catch((error: Error) => { + const message = `Could not restore the Barrio Decaf description (${error.message}). Run: yarn workspace medusa demo:reset`; + if (testFailed) console.error(message); + else throw new Error(message); + }); + } +}); diff --git a/apps/e2e/tests/mcp-oauth-browser.spec.ts b/apps/e2e/tests/mcp-oauth-browser.spec.ts new file mode 100644 index 000000000..af02b5942 --- /dev/null +++ b/apps/e2e/tests/mcp-oauth-browser.spec.ts @@ -0,0 +1,53 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { expect, test } from '@playwright/test'; + +// The consent flow in a real browser. HTTP clients cannot catch browser-only failures, such as a +// Content-Security-Policy that blocks the redirect back to the client after "Allow". +const medusaUrl = process.env.E2E_MEDUSA_URL ?? 'http://127.0.0.1:9000'; + +test('an admin signs in and approves in the browser, and the client receives the code', async ({ page }) => { + // A real callback server: Playwright's page.route does not intercept the request a redirect leads to. + let callback: URL | undefined; + const server = createServer((req, res) => { + callback = new URL(req.url ?? '/', 'http://127.0.0.1'); + res.writeHead(200, { 'content-type': 'text/html' }).end('

Connected

'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const redirectUri = `http://127.0.0.1:${(server.address() as AddressInfo).port}/oauth/callback`; + + try { + const registration = await fetch(`${medusaUrl}/oauth/register`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ client_name: 'Browser test', redirect_uris: [redirectUri] }), + }); + const { client_id } = (await registration.json()) as { client_id: string }; + const challenge = createHash('sha256').update(randomBytes(32).toString('base64url')).digest('base64url'); + + await page.goto( + `${medusaUrl}/oauth/authorize?${new URLSearchParams({ + response_type: 'code', + client_id, + redirect_uri: redirectUri, + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'browser-state', + scope: 'mcp:read', + })}`, + ); + await page.getByLabel('Admin email').fill('admin@medusa-test.com'); + await page.getByLabel('Password').fill('supersecret'); + await page.getByRole('button', { name: 'Sign in' }).click(); + + await expect(page.getByRole('heading', { name: 'Allow access?' })).toBeVisible(); + await page.getByRole('button', { name: 'Allow' }).click(); + + await expect(page.getByText('Connected')).toBeVisible(); + expect(callback?.searchParams.get('code')).toMatch(/^mcp_ac_/); + expect(callback?.searchParams.get('state')).toBe('browser-state'); + } finally { + server.close(); + } +}); diff --git a/apps/medusa/.env.template b/apps/medusa/.env.template index a575e07a7..c6b0d49f5 100644 --- a/apps/medusa/.env.template +++ b/apps/medusa/.env.template @@ -13,3 +13,11 @@ ADMIN_BACKEND_URL=http://localhost:9000 # Add your own Stripe secret key here STRIPE_API_KEY= + +# Public origin of this Medusa server for the MCP OAuth issuer, for example a Cloudflare tunnel URL. +# Defaults to http://localhost:9000. +MCP_ISSUER= + +# Storefront origin and shared secret, so product changes clear the storefront's cache (see src/subscribers). +STOREFRONT_URL=http://localhost:3000 +STOREFRONT_REVALIDATE_SECRET= diff --git a/apps/medusa/Dockerfile b/apps/medusa/Dockerfile index 4d33e6da1..5b8309bbd 100644 --- a/apps/medusa/Dockerfile +++ b/apps/medusa/Dockerfile @@ -22,7 +22,10 @@ RUN yarn install COPY --from=builder /app/out/full/ . +COPY --from=builder /app/scripts/docker-workspace-packages.mjs scripts/docker-workspace-packages.mjs + RUN yarn turbo build --filter=medusa && \ + node scripts/docker-workspace-packages.mjs pack /app/packs && \ rm -rf node_modules/.cache .yarn/cache @@ -34,7 +37,12 @@ COPY --chown=node:node --from=installer /app/.yarn .yarn COPY --chown=node:node --from=installer /app/apps/medusa/.medusa/server /app/server COPY --chown=node:node --from=installer /app/yarn.lock /app/server/yarn.lock -RUN cd /app/server && yarn workspaces focus --production +COPY --from=installer /app/packs /app/packs +COPY --from=installer /app/scripts/docker-workspace-packages.mjs /app/scripts/docker-workspace-packages.mjs + +# The app's workspace dependencies install from the tarballs packed above; see the script for why. +RUN node /app/scripts/docker-workspace-packages.mjs use /app/packs /app/server/package.json && \ + cd /app/server && YARN_ENABLE_IMMUTABLE_INSTALLS=false yarn workspaces focus --production USER 1000 diff --git a/apps/medusa/integration-tests/http/helpers/oauth.ts b/apps/medusa/integration-tests/http/helpers/oauth.ts new file mode 100644 index 000000000..00faacb3f --- /dev/null +++ b/apps/medusa/integration-tests/http/helpers/oauth.ts @@ -0,0 +1,99 @@ +import { createHash, randomBytes } from 'node:crypto'; +import type { MedusaContainer } from '@medusajs/framework/types'; +import { Modules } from '@medusajs/framework/utils'; + +export const ISSUER = 'http://localhost:9000'; +export const RESOURCE = `${ISSUER}/mcp`; +export const REDIRECT_URI = 'http://localhost:6274/oauth/callback'; +export const ADMIN = { email: 'mcp-admin@example.com', password: 'correct horse battery staple' }; + +// biome-ignore lint/suspicious/noExplicitAny: the test runner's axios instance is untyped. +export type Api = any; +export const noFollow = { maxRedirects: 0, validateStatus: () => true }; +export const formHeaders = { 'content-type': 'application/x-www-form-urlencoded' }; + +export function hiddenField(html: string, name: string): string { + const value = html.match(new RegExp(`name="${name}" value="([^"]+)"`))?.[1]; + if (!value) throw new Error(`No hidden ${name} field in:\n${html.slice(0, 500)}`); + return value.replaceAll('"', '"').replaceAll('&', '&'); +} + +export function pkce() { + const verifier = randomBytes(32).toString('base64url'); + return { verifier, challenge: createHash('sha256').update(verifier).digest('base64url') }; +} + +export async function createAdmin(api: Api, container: MedusaContainer) { + const { data } = await api.post('/auth/user/emailpass/register', ADMIN); + const { auth_identity_id } = JSON.parse(Buffer.from(data.token.split('.')[1], 'base64url').toString('utf8')); + const user = await container.resolve(Modules.USER).createUsers({ email: ADMIN.email }); + await container + .resolve(Modules.AUTH) + .updateAuthIdentities({ id: auth_identity_id, app_metadata: { user_id: user.id } }); + return { userId: user.id, authIdentityId: auth_identity_id as string }; +} + +export async function registerClient(api: Api): Promise { + const { data } = await api.post('/oauth/register', { client_name: 'Flow test', redirect_uris: [REDIRECT_URI] }); + return data.client_id; +} + +export function authorizeUrl(clientId: string, challenge: string, extra: Record = {}) { + return `/oauth/authorize?${new URLSearchParams({ + response_type: 'code', + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'state-123', + resource: RESOURCE, + ...extra, + })}`; +} + +export async function post(api: Api, url: string, body: [string, string][] | Record) { + return api.post(url, new URLSearchParams(body).toString(), { ...noFollow, headers: formHeaders }); +} + +/** Runs login and consent, returning the redirect the client would receive. */ +export async function authorize( + api: Api, + clientId: string, + challenge: string, + approve: string[] = ['mcp:read', 'mcp:write'], +) { + const login = await api.get(authorizeUrl(clientId, challenge, { scope: 'mcp:read mcp:write' }), noFollow); + const consent = await post(api, '/oauth/authorize/login', { request: hiddenField(login.data, 'request'), ...ADMIN }); + const grant = hiddenField(consent.data, 'grant'); + const redirect = await post(api, '/oauth/authorize/consent', [ + ['grant', grant], + ['decision', 'approve'], + ...approve.map((scope): [string, string] => ['scope', scope]), + ]); + return new URL(redirect.headers.location); +} + +export async function token(api: Api, body: Record) { + return post(api, '/oauth/token', body); +} + +/** Runs the whole OAuth flow for the given scopes and returns the token response. */ +export async function issueAccessToken(api: Api, scopes: string[] = ['mcp:read', 'mcp:write', 'mcp:delete']) { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const login = await api.get(authorizeUrl(clientId, challenge, { scope: scopes.join(' ') }), noFollow); + const consent = await post(api, '/oauth/authorize/login', { request: hiddenField(login.data, 'request'), ...ADMIN }); + const redirect = await post(api, '/oauth/authorize/consent', [ + ['grant', hiddenField(consent.data, 'grant')], + ['decision', 'approve'], + ...scopes.map((scope): [string, string] => ['scope', scope]), + ]); + const response = await token(api, { + grant_type: 'authorization_code', + code: new URL(redirect.headers.location).searchParams.get('code') as string, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }); + return response.data as { access_token: string; refresh_token: string; scope: string }; +} diff --git a/apps/medusa/integration-tests/http/mcp-oauth-flow.spec.ts b/apps/medusa/integration-tests/http/mcp-oauth-flow.spec.ts new file mode 100644 index 000000000..e59ea622c --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-oauth-flow.spec.ts @@ -0,0 +1,350 @@ +import { signPayload } from '@lambdacurry/medusa-mcp/modules/mcp_oauth/crypto'; +import type McpOAuthService from '@lambdacurry/medusa-mcp/modules/mcp_oauth/service'; +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; +import { + ADMIN, + authorize, + authorizeUrl, + createAdmin, + hiddenField, + ISSUER, + noFollow, + pkce, + post, + REDIRECT_URI, + RESOURCE, + registerClient, + token, +} from './helpers/oauth'; + +jest.setTimeout(60 * 1000); + +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api, getContainer }) => { + const oauth = () => getContainer().resolve('mcp_oauth'); + let admin: { userId: string; authIdentityId: string }; + + beforeEach(async () => { + admin = await createAdmin(api, getContainer()); + }); + + describe('authorize', () => { + it('shows the login form, rejects a wrong password, and shows consent after a correct one', async () => { + const clientId = await registerClient(api); + const login = await api.get(authorizeUrl(clientId, pkce().challenge), noFollow); + expect(login.status).toBe(200); + expect(login.headers['x-frame-options']).toBe('DENY'); + expect(login.data).toContain('action="/oauth/authorize/login"'); + expect(login.data).toContain('localhost:6274'); + + const request = hiddenField(login.data, 'request'); + const wrong = await post(api, '/oauth/authorize/login', { request, email: ADMIN.email, password: 'nope' }); + expect(wrong.status).toBe(401); + expect(wrong.data).toContain('did not match an admin account'); + + const consent = await post(api, '/oauth/authorize/login', { request, ...ADMIN }); + expect(consent.status).toBe(200); + expect(consent.data).toContain('Allow access?'); + expect([...consent.data.matchAll(/value="(mcp:[a-z]+)"/g)].map((match) => match[1])).toEqual([ + 'mcp:read', + 'mcp:write', + 'mcp:delete', + ]); + }); + + it('skips the login form for an admin with a Medusa session', async () => { + const clientId = await registerClient(api); + const { data } = await api.post('/auth/user/emailpass', ADMIN); + const session = await api.post('/auth/session', {}, { headers: { authorization: `Bearer ${data.token}` } }); + const cookie = String(session.headers['set-cookie']).split(';')[0]; + + const page = await api.get(authorizeUrl(clientId, pkce().challenge), { ...noFollow, headers: { cookie } }); + expect(page.data).toContain('Allow access?'); + expect(page.data).not.toContain('action="/oauth/authorize/login"'); + }); + + it('never redirects to an unregistered redirect URI, and redirects other errors back with state and iss', async () => { + const clientId = await registerClient(api); + const evil = await api.get( + authorizeUrl(clientId, pkce().challenge, { redirect_uri: 'https://evil.example/cb' }), + noFollow, + ); + expect(evil.status).toBe(400); + expect(evil.headers.location).toBeUndefined(); + + const badScope = await api.get(authorizeUrl(clientId, pkce().challenge, { scope: 'mcp:admin' }), noFollow); + const location = new URL(badScope.headers.location); + expect(badScope.status).toBe(302); + expect(Object.fromEntries(location.searchParams)).toMatchObject({ + error: 'invalid_scope', + state: 'state-123', + iss: ISSUER, + }); + + const badResource = await api.get( + authorizeUrl(clientId, pkce().challenge, { resource: 'https://other.example/mcp' }), + noFollow, + ); + expect(new URL(badResource.headers.location).searchParams.get('error')).toBe('invalid_target'); + }); + + it('redirects with access_denied when the admin denies, and rejects a forged form', async () => { + const clientId = await registerClient(api); + const login = await api.get(authorizeUrl(clientId, pkce().challenge), noFollow); + const consent = await post(api, '/oauth/authorize/login', { + request: hiddenField(login.data, 'request'), + ...ADMIN, + }); + const denied = await post(api, '/oauth/authorize/consent', { + grant: hiddenField(consent.data, 'grant'), + decision: 'deny', + }); + expect(new URL(denied.headers.location).searchParams.get('error')).toBe('access_denied'); + + const grant = hiddenField(consent.data, 'grant'); + const [body, signature] = grant.split('.'); + const tampered = Buffer.from( + Buffer.from(body, 'base64url').toString('utf8').replace(admin.userId, 'user_attacker'), + ).toString('base64url'); + const forged = await post(api, '/oauth/authorize/consent', { + grant: `${tampered}.${signature}`, + decision: 'approve', + scope: 'mcp:read', + }); + expect(forged.status).toBe(400); + expect(forged.data).toContain('expired or was changed'); + }); + }); + + describe('token', () => { + it('exchanges a code for tokens limited to the approved scopes and bound to the MCP resource', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const callback = await authorize(api, clientId, challenge, ['mcp:read']); + expect(callback.searchParams.get('state')).toBe('state-123'); + expect(callback.searchParams.get('iss')).toBe(ISSUER); + + const response = await token(api, { + grant_type: 'authorization_code', + code: callback.searchParams.get('code') as string, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + resource: RESOURCE, + }); + expect(response.status).toBe(200); + expect(response.headers['cache-control']).toBe('no-store'); + expect(response.data).toMatchObject({ token_type: 'Bearer', expires_in: 3600, scope: 'mcp:read' }); + + expect(await oauth().verifyAccessToken(response.data.access_token, RESOURCE)).toMatchObject({ + user_id: admin.userId, + auth_identity_id: admin.authIdentityId, + client_id: clientId, + scopes: ['mcp:read'], + }); + expect( + await oauth().verifyAccessToken(response.data.access_token, 'https://other.example/mcp'), + ).toBeUndefined(); + expect(await oauth().verifyAccessToken('mcp_at_unknown', RESOURCE)).toBeUndefined(); + }); + + it('rejects a wrong verifier, a different redirect_uri, or a different client', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const code = (await authorize(api, clientId, challenge)).searchParams.get('code') as string; + const exchange = { grant_type: 'authorization_code', code, client_id: clientId, redirect_uri: REDIRECT_URI }; + + const wrongVerifier = await token(api, { ...exchange, code_verifier: pkce().verifier }); + expect(wrongVerifier.data).toEqual({ error: 'invalid_grant', error_description: 'PKCE verification failed' }); + expect( + (await token(api, { ...exchange, code_verifier: verifier, redirect_uri: 'http://localhost:1/x' })).data.error, + ).toBe('invalid_grant'); + expect( + (await token(api, { ...exchange, code_verifier: verifier, client_id: await registerClient(api) })).data.error, + ).toBe('invalid_grant'); + expect((await token(api, { ...exchange, code_verifier: verifier })).status).toBe(200); + }); + + it('revokes the tokens issued from a code when that code is replayed', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const code = (await authorize(api, clientId, challenge)).searchParams.get('code') as string; + const exchange = { + grant_type: 'authorization_code', + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }; + + const first = await token(api, exchange); + const replay = await token(api, exchange); + expect(replay.status).toBe(400); + expect(replay.data.error).toBe('invalid_grant'); + expect(await oauth().verifyAccessToken(first.data.access_token, RESOURCE)).toBeUndefined(); + }); + + it('rotates refresh tokens, can only narrow scopes, and revokes the family when an old one is reused', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const code = (await authorize(api, clientId, challenge)).searchParams.get('code') as string; + const first = await token(api, { + grant_type: 'authorization_code', + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }); + + const widened = await token(api, { + grant_type: 'refresh_token', + refresh_token: first.data.refresh_token, + client_id: clientId, + scope: 'mcp:read mcp:delete', + }); + expect(widened.data.error).toBe('invalid_scope'); + + const second = await token(api, { + grant_type: 'refresh_token', + refresh_token: first.data.refresh_token, + client_id: clientId, + scope: 'mcp:read', + }); + expect(second.status).toBe(200); + expect(second.data.scope).toBe('mcp:read'); + expect(second.data.refresh_token).not.toBe(first.data.refresh_token); + + const reuse = await token(api, { + grant_type: 'refresh_token', + refresh_token: first.data.refresh_token, + client_id: clientId, + }); + expect(reuse.data.error).toBe('invalid_grant'); + expect(await oauth().verifyAccessToken(second.data.access_token, RESOURCE)).toBeUndefined(); + const afterTheft = await token(api, { + grant_type: 'refresh_token', + refresh_token: second.data.refresh_token, + client_id: clientId, + }); + expect(afterTheft.data.error).toBe('invalid_grant'); + }); + + it('rejects unsupported grant types', async () => { + const response = await token(api, { grant_type: 'password', username: ADMIN.email, password: ADMIN.password }); + expect(response.status).toBe(400); + expect(response.data.error).toBe('unsupported_grant_type'); + }); + + it('lets exactly one of two concurrent exchanges of a code win, then revokes what it issued', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const code = (await authorize(api, clientId, challenge)).searchParams.get('code') as string; + const exchange = { + grant_type: 'authorization_code', + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }; + + const results = await Promise.all([token(api, exchange), token(api, exchange)]); + const winners = results.filter((response) => response.status === 200); + expect(winners).toHaveLength(1); + expect(results.find((response) => response.status !== 200)?.data.error).toBe('invalid_grant'); + expect(await oauth().verifyAccessToken(winners[0].data.access_token, RESOURCE)).toBeUndefined(); + }); + + it('lets exactly one of two concurrent refreshes win, then revokes the family', async () => { + const clientId = await registerClient(api); + const { verifier, challenge } = pkce(); + const code = (await authorize(api, clientId, challenge)).searchParams.get('code') as string; + const first = await token(api, { + grant_type: 'authorization_code', + code, + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }); + const refresh = { grant_type: 'refresh_token', refresh_token: first.data.refresh_token, client_id: clientId }; + + const results = await Promise.all([token(api, refresh), token(api, refresh)]); + const winners = results.filter((response) => response.status === 200); + expect(winners).toHaveLength(1); + expect(results.find((response) => response.status !== 200)?.data.error).toBe('invalid_grant'); + expect(await oauth().verifyAccessToken(winners[0].data.access_token, RESOURCE)).toBeUndefined(); + }); + }); + + describe('form state and browsers', () => { + it("refuses an approval form forged with Medusa's cookie or JWT secret", async () => { + const clientId = await registerClient(api); + const request = await oauth().parseAuthorizationRequest({ + response_type: 'code', + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_challenge: pkce().challenge, + code_challenge_method: 'S256', + }); + const { http } = getContainer().resolve('configModule').projectConfig; + for (const secret of [http.cookieSecret, http.jwtSecret, 'supersecret']) { + const forged = signPayload( + 'consent', + { request, user_id: admin.userId, auth_identity_id: admin.authIdentityId }, + String(secret), + 600, + ); + const response = await post(api, '/oauth/authorize/consent', { + grant: forged, + decision: 'approve', + scope: 'mcp:read', + }); + expect(response.status).toBe(400); + expect(response.headers.location).toBeUndefined(); + } + }); + + it('refuses a sign-in form token submitted as the approval form', async () => { + const clientId = await registerClient(api); + const login = await api.get(authorizeUrl(clientId, pkce().challenge), noFollow); + const forged = await post(api, '/oauth/authorize/consent', { + grant: hiddenField(login.data, 'request'), + decision: 'approve', + scope: 'mcp:read', + }); + expect(forged.status).toBe(400); + expect(forged.data).toContain('expired or was changed'); + }); + + it('allows the consent page to redirect to the verified client origin', async () => { + const clientId = await registerClient(api); + const login = await api.get(authorizeUrl(clientId, pkce().challenge), noFollow); + const consent = await post(api, '/oauth/authorize/login', { + request: hiddenField(login.data, 'request'), + ...ADMIN, + }); + expect(consent.headers['content-security-policy']).toContain("form-action 'self' http://localhost:6274;"); + expect(login.headers['content-security-policy']).toContain("form-action 'self';"); + }); + + it('answers CORS preflight and sets CORS headers on token, registration, metadata, and MCP responses', async () => { + const preflight = await api.options('/oauth/token', { + validateStatus: () => true, + headers: { origin: 'https://inspector.example', 'access-control-request-method': 'POST' }, + }); + expect(preflight.status).toBe(204); + expect(preflight.headers['access-control-allow-origin']).toBe('*'); + expect(preflight.headers['access-control-allow-headers']).toContain('authorization'); + + for (const response of [ + await token(api, { grant_type: 'password' }), + await api.get('/.well-known/oauth-authorization-server'), + await api.get('/.well-known/oauth-protected-resource/mcp'), + await api.post('/oauth/register', {}, { validateStatus: () => true }), + ]) { + expect(response.headers['access-control-allow-origin']).toBe('*'); + } + }); + }); + }, +}); diff --git a/apps/medusa/integration-tests/http/mcp-oauth.spec.ts b/apps/medusa/integration-tests/http/mcp-oauth.spec.ts new file mode 100644 index 000000000..9bff1b6ca --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-oauth.spec.ts @@ -0,0 +1,147 @@ +import type McpOAuthService from '@lambdacurry/medusa-mcp/modules/mcp_oauth/service'; +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; + +jest.setTimeout(60 * 1000); + +const CHATGPT_CLIENT_ID = 'https://chatgpt.com/oauth/client.json'; +const chatgptDocument = { + client_id: CHATGPT_CLIENT_ID, + client_name: 'ChatGPT', + redirect_uris: ['https://chatgpt.com/connector_platform_oauth_redirect'], + token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'], +}; + +async function expectOAuthError(request: Promise, status: number, error: string) { + await expect(request).rejects.toMatchObject({ response: { status, data: { error } } }); +} + +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api, getContainer }) => { + const oauth = () => getContainer().resolve('mcp_oauth'); + + describe('OAuth discovery', () => { + it('publishes authorization server metadata with PKCE, CIMD, and iss support', async () => { + const { status, data } = await api.get('/.well-known/oauth-authorization-server'); + expect(status).toBe(200); + expect(data).toMatchObject({ + issuer: 'http://localhost:9000', + authorization_endpoint: 'http://localhost:9000/oauth/authorize', + token_endpoint: 'http://localhost:9000/oauth/token', + registration_endpoint: 'http://localhost:9000/oauth/register', + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + scopes_supported: ['mcp:read', 'mcp:write', 'mcp:delete'], + client_id_metadata_document_supported: true, + authorization_response_iss_parameter_supported: true, + }); + }); + + it('publishes protected resource metadata at the path-inserted and root well-known URLs', async () => { + const pathForm = await api.get('/.well-known/oauth-protected-resource/mcp'); + const rootForm = await api.get('/.well-known/oauth-protected-resource'); + expect(pathForm.data).toEqual({ + resource: 'http://localhost:9000/mcp', + authorization_servers: ['http://localhost:9000'], + scopes_supported: ['mcp:read', 'mcp:write', 'mcp:delete'], + bearer_methods_supported: ['header'], + resource_name: 'Medusa MCP', + }); + expect(rootForm.data).toEqual(pathForm.data); + }); + }); + + describe('Dynamic Client Registration', () => { + it('registers a public client and can resolve it afterwards', async () => { + const { status, data } = await api.post('/oauth/register', { + client_name: 'MCP Inspector', + redirect_uris: ['http://localhost:6274/oauth/callback'], + }); + expect(status).toBe(201); + expect(data).toMatchObject({ + client_id: expect.stringMatching(/^mcpdcr_/), + client_name: 'MCP Inspector', + token_endpoint_auth_method: 'none', + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + }); + + const client = await oauth().resolveClient(data.client_id); + expect(client).toMatchObject({ registration: 'dcr', redirect_uris: ['http://localhost:6274/oauth/callback'] }); + }); + + it('rejects non-loopback http redirects, confidential clients, and unsupported grants', async () => { + await expectOAuthError( + api.post('/oauth/register', { redirect_uris: ['http://evil.example/cb'] }), + 400, + 'invalid_redirect_uri', + ); + await expectOAuthError( + api.post('/oauth/register', { + redirect_uris: ['https://a.example/cb'], + token_endpoint_auth_method: 'client_secret_basic', + }), + 400, + 'invalid_client_metadata', + ); + await expectOAuthError( + api.post('/oauth/register', { redirect_uris: ['https://a.example/cb'], grant_types: ['password'] }), + 400, + 'invalid_client_metadata', + ); + }); + + it('does not resolve unknown opaque client ids', async () => { + await expect(oauth().resolveClient('mcpdcr_unknown')).rejects.toMatchObject({ code: 'invalid_client' }); + }); + }); + + describe('Client ID Metadata Documents', () => { + it('fetches, stores, and caches a valid document', async () => { + const fetched: string[] = []; + await oauth().setFetchJson(async (url) => { + fetched.push(url); + return chatgptDocument; + }); + + const client = await oauth().resolveClient(CHATGPT_CLIENT_ID); + expect(client).toMatchObject({ + client_id: CHATGPT_CLIENT_ID, + registration: 'cimd', + client_name: 'ChatGPT', + redirect_uris: chatgptDocument.redirect_uris, + }); + await oauth().resolveClient(CHATGPT_CLIENT_ID); + expect(fetched).toEqual([CHATGPT_CLIENT_ID]); + }); + + it('resolves concurrent first requests for a new client to one stored client', async () => { + const clientId = 'https://agent.example/oauth/client.json'; + await oauth().setFetchJson(async () => ({ ...chatgptDocument, client_id: clientId })); + const resolved = await Promise.all(Array.from({ length: 5 }, () => oauth().resolveClient(clientId))); + expect(new Set(resolved.map((client) => client.client_id))).toEqual(new Set([clientId])); + expect(await oauth().listMcpOAuthClients({ client_id: clientId })).toHaveLength(1); + }); + + it('rejects a document that names a different client_id', async () => { + await oauth().setFetchJson(async () => ({ ...chatgptDocument, client_id: 'https://evil.example/client.json' })); + await expect(oauth().resolveClient('https://evil.example/other.json')).rejects.toMatchObject({ + code: 'invalid_client', + message: expect.stringMatching(/does not match the URL/), + }); + }); + + it('never fetches http client ids', async () => { + const fetched: string[] = []; + await oauth().setFetchJson(async (url) => { + fetched.push(url); + return chatgptDocument; + }); + await expect(oauth().resolveClient('http://chatgpt.com/oauth/client.json')).rejects.toMatchObject({ + code: 'invalid_client', + }); + expect(fetched).toEqual([]); + }); + }); + }, +}); diff --git a/apps/medusa/integration-tests/http/mcp-public-strong-secrets.spec.ts b/apps/medusa/integration-tests/http/mcp-public-strong-secrets.spec.ts new file mode 100644 index 000000000..67ffb33e1 --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-public-strong-secrets.spec.ts @@ -0,0 +1,25 @@ +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; + +jest.setTimeout(60 * 1000); + +// Set before medusa-config is read. The runner's `env` option is applied too late for plugin options, and each +// HTTP integration file runs in its own process, so this does not leak into other suites. +Object.assign(process.env, { + MCP_ISSUER: 'https://mcp.example.test', + JWT_SECRET: 'a-strong-random-jwt-secret-for-tests', + COOKIE_SECRET: 'a-strong-random-cookie-secret-for-tests', +}); + +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api }) => { + it('serves discovery for a public issuer once the secrets are strong', async () => { + const { status, data } = await api.get('/.well-known/oauth-authorization-server'); + expect(status).toBe(200); + expect(data).toMatchObject({ + issuer: 'https://mcp.example.test', + token_endpoint: 'https://mcp.example.test/oauth/token', + }); + }); + }, +}); diff --git a/apps/medusa/integration-tests/http/mcp-public-weak-secrets.spec.ts b/apps/medusa/integration-tests/http/mcp-public-weak-secrets.spec.ts new file mode 100644 index 000000000..10d716d0f --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-public-weak-secrets.spec.ts @@ -0,0 +1,34 @@ +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; + +jest.setTimeout(60 * 1000); + +// Set before medusa-config is read. The runner's `env` option is applied too late for plugin options, and each +// HTTP integration file runs in its own process, so this does not leak into other suites. +Object.assign(process.env, { + MCP_ISSUER: 'https://mcp.example.test', + JWT_SECRET: 'supersecret', + COOKIE_SECRET: 'supersecret', +}); + +// A public issuer with Medusa's default signing secrets would let anyone forge admin tokens through the tunnel. +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api }) => { + it('refuses OAuth, MCP, and discovery while the secrets are weak, and leaves the rest of Medusa alone', async () => { + const options = { validateStatus: () => true }; + for (const response of [ + await api.get('/.well-known/oauth-authorization-server', options), + await api.get('/.well-known/oauth-protected-resource/mcp', options), + await api.post('/oauth/register', { redirect_uris: ['https://a.example/cb'] }, options), + await api.post('/mcp', { jsonrpc: '2.0', id: 1, method: 'tools/list' }, options), + ]) { + expect(response.status).toBe(503); + expect(response.data).toMatchObject({ + error: 'server_misconfigured', + error_description: expect.stringContaining('JWT_SECRET and COOKIE_SECRET'), + }); + } + expect((await api.get('/health')).status).toBe(200); + }); + }, +}); diff --git a/apps/medusa/integration-tests/http/mcp-tools.spec.ts b/apps/medusa/integration-tests/http/mcp-tools.spec.ts new file mode 100644 index 000000000..c1e520a6f --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-tools.spec.ts @@ -0,0 +1,204 @@ +import type McpOAuthService from '@lambdacurry/medusa-mcp/modules/mcp_oauth/service'; +import { Modules, ProductStatus } from '@medusajs/framework/utils'; +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; +import { type Api, createAdmin, issueAccessToken, RESOURCE } from './helpers/oauth'; + +jest.setTimeout(60 * 1000); + +const RESOURCE_METADATA = 'http://localhost:9000/.well-known/oauth-protected-resource/mcp'; + +/** One stateless MCP JSON-RPC call over Streamable HTTP, returning the HTTP status and the JSON-RPC message. */ +async function rpc(api: Api, method: string, params: Record, token?: string) { + const response = await api.post( + '/mcp', + { jsonrpc: '2.0', id: 1, method, params }, + { + validateStatus: () => true, + responseType: 'text', + headers: { + accept: 'application/json, text/event-stream', + 'mcp-protocol-version': '2025-06-18', + ...(token ? { authorization: `Bearer ${token}` } : {}), + }, + }, + ); + const text = String(response.data); + const json = text.trimStart().startsWith('{') + ? text + : text + .split('\n') + .find((line) => line.startsWith('data:')) + ?.slice(5); + return { status: response.status, headers: response.headers, message: json ? JSON.parse(json) : undefined }; +} + +async function callTool(api: Api, token: string, name: string, args: Record) { + const { status, message } = await rpc(api, 'tools/call', { name, arguments: args }, token); + expect(status).toBe(200); + return message.result as { isError?: boolean; structuredContent?: Record; content: { text: string }[] }; +} + +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api, getContainer }) => { + let admin: { userId: string; authIdentityId: string }; + let readToken: string; + let productId: string; + + beforeEach(async () => { + const container = getContainer(); + admin = await createAdmin(api, container); + readToken = (await issueAccessToken(api, ['mcp:read'])).access_token; + const [product] = await container.resolve(Modules.PRODUCT).createProducts([ + { + title: 'Barrio Decaf - Medium Roast', + handle: 'barrio-decaf-medium-roast', + description: 'Smooth and sweet.', + status: ProductStatus.PUBLISHED, + }, + ]); + productId = product.id; + await container.resolve(Modules.API_KEY).createApiKeys({ + title: 'Storefront', + type: 'publishable', + created_by: admin.userId, + }); + }); + + describe('authentication', () => { + it('challenges requests without a token so clients can discover the authorization server', async () => { + const { status, headers } = await rpc(api, 'tools/list', {}); + expect(status).toBe(401); + expect(headers['www-authenticate']).toBe(`Bearer resource_metadata="${RESOURCE_METADATA}"`); + }); + + it('rejects unknown tokens with invalid_token', async () => { + const { status, headers } = await rpc(api, 'tools/list', {}, 'mcp_at_not-a-token'); + expect(status).toBe(401); + expect(headers['www-authenticate']).toContain('error="invalid_token"'); + }); + + it('answers a token without mcp:read with a 403 insufficient_scope challenge', async () => { + const writeOnly = (await issueAccessToken(api, ['mcp:write'])).access_token; + const { status, headers } = await rpc( + api, + 'tools/call', + { name: 'search_api', arguments: { query: 'products' } }, + writeOnly, + ); + expect(status).toBe(403); + expect(headers['www-authenticate']).toContain('error="insufficient_scope"'); + expect(headers['www-authenticate']).toContain('scope="mcp:read"'); + expect(headers['www-authenticate']).toContain(`resource_metadata="${RESOURCE_METADATA}"`); + }); + + it('revokes tokens of an admin who no longer exists', async () => { + await getContainer().resolve(Modules.USER).deleteUsers([admin.userId]); + await getContainer() + .resolve(Modules.AUTH) + .updateAuthIdentities({ id: admin.authIdentityId, app_metadata: { user_id: null } }); + const { status, headers } = await rpc(api, 'tools/list', {}, readToken); + expect(status).toBe(401); + expect(headers['www-authenticate']).toContain('no longer exists'); + const oauth = getContainer().resolve('mcp_oauth'); + expect(await oauth.verifyAccessToken(readToken, RESOURCE)).toBeUndefined(); + }); + }); + + describe('deleted identities', () => { + it('revokes tokens whose auth identity was deleted outright', async () => { + await getContainer().resolve(Modules.AUTH).deleteAuthIdentities([admin.authIdentityId]); + const { status, headers } = await rpc(api, 'tools/list', {}, readToken); + expect(status).toBe(401); + expect(headers['www-authenticate']).toContain('no longer exists'); + const oauth = getContainer().resolve('mcp_oauth'); + expect(await oauth.verifyAccessToken(readToken, RESOURCE)).toBeUndefined(); + }); + }); + + describe('tools', () => { + it('lists the read tools with read-only annotations and their OAuth scope', async () => { + const { message } = await rpc(api, 'tools/list', {}, readToken); + const tools = message.result.tools as { name: string; annotations: Record; _meta: unknown }[]; + const readTools = tools.filter((tool) => ['search_api', 'describe_api', 'read_api'].includes(tool.name)); + expect(readTools.map((tool) => tool.name)).toEqual(['search_api', 'describe_api', 'read_api']); + for (const tool of readTools) { + expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + expect(tool._meta).toEqual({ securitySchemes: [{ type: 'oauth2', scopes: ['mcp:read'] }] }); + } + }); + + it('finds and describes the product update operation', async () => { + const search = await callTool(api, readToken, 'search_api', { query: 'update a product description' }); + expect(search.structuredContent?.results[0]).toMatchObject({ + operation: 'POST /admin/products/{id}', + operation_id: 'PostProductsId', + tool: 'write_api', + }); + expect(search.structuredContent?.index).toMatchObject({ + medusa_version: '2.22.1', + undocumented_operations: 10, + }); + + const describe = await callTool(api, readToken, 'describe_api', { operation: 'POST /admin/products/{id}' }); + expect(describe.structuredContent).toMatchObject({ path_params: [{ name: 'id' }], tool: 'write_api' }); + expect(JSON.stringify(describe.structuredContent?.request_body)).toContain('"description"'); + }); + + it('reads admin data as the signed-in admin and store data with a publishable key', async () => { + const products = await callTool(api, readToken, 'read_api', { + operation: 'GET /admin/products', + query: { q: 'Decaf', fields: 'id,title,description', limit: 1 }, + }); + expect(products.isError).toBeFalsy(); + expect(products.structuredContent).toMatchObject({ + status: 200, + body: { + products: [{ id: productId, title: 'Barrio Decaf - Medium Roast', description: 'Smooth and sweet.' }], + }, + }); + + const one = await callTool(api, readToken, 'read_api', { + operation: 'GET /admin/products/{id}', + path_params: { id: productId }, + query: { fields: 'id,handle' }, + }); + expect(one.structuredContent?.body).toEqual({ + product: { id: productId, handle: 'barrio-decaf-medium-roast' }, + }); + + const regions = await callTool(api, readToken, 'read_api', { operation: 'GET /store/regions' }); + expect(regions.structuredContent).toMatchObject({ status: 200, body: { regions: [] } }); + }); + + it('refuses blocked operations, writes, unknown parameters, and unknown operations', async () => { + const blocked = await callTool(api, readToken, 'read_api', { operation: 'GET /admin/api-keys' }); + expect(blocked).toMatchObject({ isError: true }); + expect(blocked.content[0].text).toContain('blocked for agents'); + + const write = await callTool(api, readToken, 'read_api', { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + }); + expect(write.content[0].text).toContain('Use write_api'); + + const unknownQuery = await callTool(api, readToken, 'read_api', { + operation: 'GET /admin/products', + query: { not_a_param: 1 }, + }); + expect(unknownQuery.content[0].text).toContain('Unknown query parameter'); + + const unknown = await callTool(api, readToken, 'describe_api', { operation: 'GET /admin/nothing' }); + expect(unknown).toMatchObject({ isError: true }); + }); + + it('reports Medusa errors without failing the tool call', async () => { + const missing = await callTool(api, readToken, 'read_api', { + operation: 'GET /admin/products/{id}', + path_params: { id: 'prod_missing' }, + }); + expect(missing).toMatchObject({ isError: true, structuredContent: { status: 404 } }); + }); + }); + }, +}); diff --git a/apps/medusa/integration-tests/http/mcp-write.spec.ts b/apps/medusa/integration-tests/http/mcp-write.spec.ts new file mode 100644 index 000000000..241d0afdc --- /dev/null +++ b/apps/medusa/integration-tests/http/mcp-write.spec.ts @@ -0,0 +1,238 @@ +import { Modules, ProductStatus } from '@medusajs/framework/utils'; +import { medusaIntegrationTestRunner } from '@medusajs/test-utils'; +import { type Api, createAdmin, issueAccessToken } from './helpers/oauth'; + +jest.setTimeout(90 * 1000); + +async function rpc(api: Api, method: string, params: Record, token: string) { + const response = await api.post( + '/mcp', + { jsonrpc: '2.0', id: 1, method, params }, + { + validateStatus: () => true, + responseType: 'text', + headers: { + accept: 'application/json, text/event-stream', + 'mcp-protocol-version': '2025-06-18', + authorization: `Bearer ${token}`, + }, + }, + ); + const text = String(response.data); + const json = text.trimStart().startsWith('{') + ? text + : text + .split('\n') + .find((line) => line.startsWith('data:')) + ?.slice(5); + return { status: response.status, headers: response.headers, message: json ? JSON.parse(json) : undefined }; +} + +async function callTool(api: Api, token: string, name: string, args: Record) { + const { status, message } = await rpc(api, 'tools/call', { name, arguments: args }, token); + expect(status).toBe(200); + return message.result as { isError?: boolean; structuredContent?: Record; content: { text: string }[] }; +} + +medusaIntegrationTestRunner({ + env: {}, + testSuite: ({ api, getContainer }) => { + let fullToken: string; + let productId: string; + const product = () => getContainer().resolve(Modules.PRODUCT).retrieveProduct(productId); + + beforeEach(async () => { + await createAdmin(api, getContainer()); + fullToken = (await issueAccessToken(api, ['mcp:read', 'mcp:write', 'mcp:delete'])).access_token; + const [created] = await getContainer() + .resolve(Modules.PRODUCT) + .createProducts([ + { + title: 'Barrio Decaf - Medium Roast', + handle: 'barrio-decaf-medium-roast', + description: 'Smooth and sweet.', + status: ProductStatus.PUBLISHED, + }, + ]); + productId = created.id; + }); + + it('lists write and delete tools with honest annotations and scopes', async () => { + const { message } = await rpc(api, 'tools/list', {}, fullToken); + const tools = Object.fromEntries( + (message.result.tools as { name: string; annotations: unknown; _meta: unknown }[]).map((tool) => [ + tool.name, + tool, + ]), + ); + expect(Object.keys(tools)).toEqual(['search_api', 'describe_api', 'read_api', 'write_api', 'delete_api']); + expect(tools.write_api).toMatchObject({ + annotations: { readOnlyHint: false, destructiveHint: false }, + _meta: { securitySchemes: [{ type: 'oauth2', scopes: ['mcp:write'] }] }, + }); + expect(tools.delete_api).toMatchObject({ + annotations: { readOnlyHint: false, destructiveHint: true }, + _meta: { securitySchemes: [{ type: 'oauth2', scopes: ['mcp:delete'] }] }, + }); + }); + + it('previews a description change without writing, then applies it', async () => { + const change = { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + body: { description: 'Rich, chocolatey, and caffeine-free.' }, + }; + + const preview = await callTool(api, fullToken, 'write_api', { ...change, dry_run: true }); + expect(preview.structuredContent).toEqual({ + operation: 'POST /admin/products/{id}', + dry_run: true, + changes: [ + { field: 'description', current: 'Smooth and sweet.', proposed: 'Rich, chocolatey, and caffeine-free.' }, + ], + }); + expect((await product()).description).toBe('Smooth and sweet.'); + + const applied = await callTool(api, fullToken, 'write_api', change); + expect(applied.isError).toBeFalsy(); + expect(applied.structuredContent).toMatchObject({ + status: 200, + body: { product: { id: productId, description: 'Rich, chocolatey, and caffeine-free.' } }, + }); + expect((await product()).description).toBe('Rich, chocolatey, and caffeine-free.'); + }); + + it('rejects a body that does not match the schema before calling Medusa', async () => { + const rejected = await callTool(api, fullToken, 'write_api', { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + body: { description: 42 }, + }); + expect(rejected.isError).toBe(true); + expect(rejected.content[0].text).toContain('/description must be string'); + expect((await product()).description).toBe('Smooth and sweet.'); + }); + + it('needs mcp:write to write and mcp:delete to delete', async () => { + const readOnly = (await issueAccessToken(api, ['mcp:read'])).access_token; + const write = await rpc( + api, + 'tools/call', + { name: 'write_api', arguments: { operation: 'POST /admin/products/{id}', path_params: { id: productId } } }, + readOnly, + ); + expect(write.status).toBe(403); + expect(write.headers['www-authenticate']).toContain('scope="mcp:write"'); + + const writer = (await issueAccessToken(api, ['mcp:read', 'mcp:write'])).access_token; + const remove = await rpc( + api, + 'tools/call', + { name: 'delete_api', arguments: { operation: 'DELETE /admin/products/{id}', path_params: { id: productId } } }, + writer, + ); + expect(remove.status).toBe(403); + expect(remove.headers['www-authenticate']).toContain('scope="mcp:delete"'); + expect((await product()).id).toBe(productId); + }); + + it('deletes with delete_api', async () => { + const deleted = await callTool(api, fullToken, 'delete_api', { + operation: 'DELETE /admin/products/{id}', + path_params: { id: productId }, + }); + expect(deleted.structuredContent).toMatchObject({ status: 200, body: { id: productId, deleted: true } }); + await expect(product()).rejects.toThrow(); + }); + + it('refuses blocked writes and the wrong tool for an operation', async () => { + const blocked = await callTool(api, fullToken, 'write_api', { + operation: 'POST /admin/api-keys', + body: { title: 'agent key', type: 'secret' }, + }); + expect(blocked.content[0].text).toContain('blocked for agents'); + + const wrongTool = await callTool(api, fullToken, 'write_api', { + operation: 'DELETE /admin/products/{id}', + path_params: { id: productId }, + }); + expect(wrongTool.content[0].text).toContain('Use delete_api'); + }); + + it('audits refused, executed, and previewed write attempts with their path parameters', async () => { + const logger = getContainer().resolve('logger') as { info: (message: string) => void }; + const info = jest.spyOn(logger, 'info'); + try { + await callTool(api, fullToken, 'write_api', { + operation: 'POST /admin/api-keys', + body: { title: 'x', type: 'secret' }, + }); + await callTool(api, fullToken, 'write_api', { operation: 'POST /admin/nothing', body: {} }); + await callTool(api, fullToken, 'write_api', { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + body: { description: 'Audited.' }, + }); + + const entries = info.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.startsWith('[medusa-mcp] ')) + .map((message) => JSON.parse(message.slice('[medusa-mcp] '.length))); + expect(entries).toEqual([ + expect.objectContaining({ + operation: 'POST /admin/api-keys', + outcome: 'refused', + reason: expect.stringContaining('blocked for agents'), + }), + expect.objectContaining({ + operation: 'POST /admin/nothing', + outcome: 'refused', + reason: expect.stringContaining('Unknown operation'), + }), + expect.objectContaining({ + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + outcome: 'executed', + status: 200, + spec_revision: expect.any(String), + }), + ]); + } finally { + info.mockRestore(); + } + }); + + it('does not show current values in a dry run for a token without mcp:read', async () => { + const writeOnly = (await issueAccessToken(api, ['mcp:write'])).access_token; + const preview = await callTool(api, writeOnly, 'write_api', { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + body: { description: 'Proposed.' }, + dry_run: true, + }); + expect(preview.structuredContent).toEqual({ + operation: 'POST /admin/products/{id}', + dry_run: true, + proposed: { description: 'Proposed.' }, + current: null, + note: 'Current values need the mcp:read scope.', + }); + expect(JSON.stringify(preview)).not.toContain('Smooth and sweet.'); + }); + + it('limits writes per token per minute', async () => { + const limiter = (await issueAccessToken(api, ['mcp:read', 'mcp:write'])).access_token; + const preview = { + operation: 'POST /admin/products/{id}', + path_params: { id: productId }, + body: { title: 'x' }, + dry_run: true, + }; + for (let attempt = 0; attempt < 30; attempt++) { + expect((await callTool(api, limiter, 'write_api', preview)).isError).toBeFalsy(); + } + const limited = await callTool(api, limiter, 'write_api', preview); + expect(limited.content[0].text).toContain('Rate limit reached'); + }); + }, +}); diff --git a/apps/medusa/integration-tests/run-http.mjs b/apps/medusa/integration-tests/run-http.mjs new file mode 100644 index 000000000..bc73233de --- /dev/null +++ b/apps/medusa/integration-tests/run-http.mjs @@ -0,0 +1,34 @@ +// Runs each HTTP integration test file in its own Jest process. Booting a second Medusa app inside one Jest +// process fails every module loader with "Map.prototype.set called on incompatible receiver", so files cannot +// share a process. Pass file name filters as arguments to run a subset. +import { spawnSync } from 'node:child_process'; +import { readdirSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const httpDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'http'); +const jestBin = createRequire(import.meta.url).resolve('jest/bin/jest'); +const filters = process.argv.slice(2); +const files = readdirSync(httpDir) + .filter((file) => file.endsWith('.spec.ts')) + .filter((file) => !filters.length || filters.some((filter) => file.includes(filter))) + .sort(); + +if (!files.length) { + console.error(`No HTTP integration tests match: ${filters.join(', ')}`); + process.exit(1); +} + +for (const file of files) { + const result = spawnSync(process.execPath, [jestBin, '--silent=false', '--runInBand', '--forceExit', path.join(httpDir, file)], { + stdio: 'inherit', + env: { ...process.env, TEST_TYPE: 'integration:http', NODE_OPTIONS: '--experimental-vm-modules' }, + }); + if (result.status !== 0) { + console.error(`HTTP integration tests failed in ${file}`); + process.exit(result.status ?? 1); + } +} + +console.log(`HTTP integration tests passed in ${files.length} files: ${files.join(', ')}`); diff --git a/apps/medusa/jest.config.js b/apps/medusa/jest.config.js index 02ea97efd..ed4f01207 100644 --- a/apps/medusa/jest.config.js +++ b/apps/medusa/jest.config.js @@ -14,7 +14,7 @@ module.exports = { }, testEnvironment: 'node', moduleFileExtensions: ['js', 'ts', 'json'], - modulePathIgnorePatterns: ['dist/'], + modulePathIgnorePatterns: ['dist/', '/.medusa/'], }; if (process.env.TEST_TYPE === 'integration:http') { diff --git a/apps/medusa/medusa-config.ts b/apps/medusa/medusa-config.ts index 2d870812e..01da6fa36 100644 --- a/apps/medusa/medusa-config.ts +++ b/apps/medusa/medusa-config.ts @@ -59,6 +59,12 @@ module.exports = defineConfig({ }, }, plugins: [ + { + resolve: '@lambdacurry/medusa-mcp', + options: { + issuer: process.env.MCP_ISSUER, + }, + }, { resolve: '@lambdacurry/medusa-product-reviews', options: {}, diff --git a/apps/medusa/package.json b/apps/medusa/package.json index a38150895..365706159 100644 --- a/apps/medusa/package.json +++ b/apps/medusa/package.json @@ -25,14 +25,16 @@ "seed:prod": "medusa exec ./src/scripts/seed.js && yarn add-user:prod", "add-user:prod": "medusa user --email admin@medusa-test.com --password supersecret && medusa user --email admin@lambdacurry.dev --password password", "migrate": "medusa db:migrate", - "test:integration:http": "TEST_TYPE=integration:http NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit", + "test:integration:http": "node ./integration-tests/run-http.mjs", "test:integration:modules": "TEST_TYPE=integration:modules NODE_OPTIONS=--experimental-vm-modules jest --silent --runInBand --forceExit", "test:unit": "TEST_TYPE=unit NODE_OPTIONS=--experimental-vm-modules jest --silent --runInBand --forceExit", "medusa:init": "yarn run nukedb && medusa db:create --db medusa2 && yarn run migrate && yarn run sync && yarn run seed && yarn run add-user", "add-user": "medusa user --email admin@medusa-test.com --password supersecret && medusa user --email admin@lambdacurry.dev --password password", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "demo:reset": "medusa exec ./src/scripts/reset-demo-products.ts" }, "dependencies": { + "@lambdacurry/medusa-mcp": "workspace:*", "@lambdacurry/medusa-product-reviews": "1.4.0", "@medusajs/admin-sdk": "2.22.1", "@medusajs/cli": "2.22.1", diff --git a/apps/medusa/src/__tests__/openapi-contracts.unit.spec.ts b/apps/medusa/src/__tests__/openapi-contracts.unit.spec.ts new file mode 100644 index 000000000..4cee2615e --- /dev/null +++ b/apps/medusa/src/__tests__/openapi-contracts.unit.spec.ts @@ -0,0 +1,38 @@ +import path from 'node:path'; +import { type ApiSpec, buildApiSpec, countOperations } from '@lambdacurry/medusa-mcp/openapi'; + +const projectRoot = path.resolve(__dirname, '../..'); +const config = require('../../medusa-config') as { plugins: (string | { resolve: string })[] }; +const plugins = config.plugins.map((plugin) => (typeof plugin === 'string' ? plugin : plugin.resolve)); + +// Fails when a route under src/api has no openapi.ts contract, or when a contract disagrees with its route. +describe('OpenAPI contracts', () => { + let spec: ApiSpec; + + beforeAll(() => { + spec = buildApiSpec({ projectRoot, plugins }); + }); + + it('publishes the core Medusa spec plus every documented custom route', () => { + expect(spec.medusaVersion).toBe('2.22.1'); + expect(countOperations(spec.documents.admin)).toBe(414); + expect(countOperations(spec.documents.store)).toBe(79); + }); + + it('reports the product-reviews plugin routes as gaps until the plugin ships contracts', () => { + expect(spec.unscannedPlugins).toEqual([]); + expect(spec.gaps.filter((gap) => gap.source === 'app')).toEqual([]); + expect(spec.gaps.map((gap) => `${gap.method} ${gap.path}`)).toEqual([ + 'GET /admin/product-review-stats', + 'GET /admin/product-reviews', + 'DELETE /admin/product-reviews/{id}/response', + 'POST /admin/product-reviews/{id}/response', + 'PUT /admin/product-reviews/{id}/response', + 'PUT /admin/product-reviews/{id}/status', + 'GET /store/product-review-stats', + 'GET /store/product-reviews', + 'POST /store/product-reviews', + 'POST /store/product-reviews/uploads', + ]); + }); +}); diff --git a/apps/medusa/src/api/admin/custom/route.ts b/apps/medusa/src/api/admin/custom/route.ts deleted file mode 100644 index 6abd32e29..000000000 --- a/apps/medusa/src/api/admin/custom/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { MedusaRequest, MedusaResponse } from '@medusajs/framework'; - -export async function GET(req: MedusaRequest, res: MedusaResponse): Promise { - res.sendStatus(200); -} diff --git a/apps/medusa/src/api/store/custom/route.ts b/apps/medusa/src/api/store/custom/route.ts deleted file mode 100644 index 50779cedd..000000000 --- a/apps/medusa/src/api/store/custom/route.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { MedusaRequest, MedusaResponse } from '@medusajs/framework'; -import { ContainerRegistrationKeys } from '@medusajs/framework/utils'; - -export async function GET(req: MedusaRequest, res: MedusaResponse): Promise { - const query = req.scope.resolve(ContainerRegistrationKeys.QUERY); - // const orderService = req.scope.resolve( - // ContainerRegistrationKeys.ORDER_SERVICE - // ); - //test - - res.json({ message: 'Hello' }); -} diff --git a/apps/medusa/src/scripts/reset-demo-products.ts b/apps/medusa/src/scripts/reset-demo-products.ts new file mode 100644 index 000000000..8880c7c05 --- /dev/null +++ b/apps/medusa/src/scripts/reset-demo-products.ts @@ -0,0 +1,37 @@ +import type { ExecArgs } from '@medusajs/framework/types'; +import { ContainerRegistrationKeys } from '@medusajs/framework/utils'; +import { updateProductsWorkflow } from '@medusajs/medusa/core-flows'; +import { seedProducts } from './seed/products'; + +/** + * Restores seeded product titles and descriptions, for retakes of the MCP demo. Runs through Medusa's product + * workflow, so the usual product events fire and the storefront drops its cache. + * + * yarn workspace medusa demo:reset + */ +export default async function resetDemoProducts({ container }: ExecArgs) { + const logger = container.resolve(ContainerRegistrationKeys.LOGGER); + const query = container.resolve(ContainerRegistrationKeys.QUERY); + const seeded = seedProducts({ + collections: [], + tags: [], + categories: [], + sales_channels: [], + shipping_profile_id: '', + }); + + const { data: products } = await query.graph({ + entity: 'product', + fields: ['id', 'handle', 'title', 'description'], + filters: { handle: seeded.map((product) => product.handle as string) }, + }); + + const updates = products.flatMap((product) => { + const original = seeded.find((candidate) => candidate.handle === product.handle); + if (!original || (product.title === original.title && product.description === original.description)) return []; + return [{ id: product.id, title: original.title, description: original.description }]; + }); + + if (updates.length) await updateProductsWorkflow(container).run({ input: { products: updates } }); + logger.info(`Reset ${updates.length} of ${products.length} seeded products to their seed title and description.`); +} diff --git a/apps/medusa/src/subscribers/storefront-revalidate.ts b/apps/medusa/src/subscribers/storefront-revalidate.ts new file mode 100644 index 000000000..f41c13228 --- /dev/null +++ b/apps/medusa/src/subscribers/storefront-revalidate.ts @@ -0,0 +1,40 @@ +import type { SubscriberArgs, SubscriberConfig } from '@medusajs/framework'; +import { + ContainerRegistrationKeys, + ProductCategoryWorkflowEvents, + ProductCollectionWorkflowEvents, + ProductVariantWorkflowEvents, + ProductWorkflowEvents, +} from '@medusajs/framework/utils'; + +/** + * Tells the storefront to drop its cached catalog when products change, so a change made in the admin or through + * MCP shows on the next page load instead of after the storefront's cache expires. Does nothing unless + * STOREFRONT_URL and STOREFRONT_REVALIDATE_SECRET are set. + */ +export default async function storefrontRevalidate({ event, container }: SubscriberArgs) { + const storefrontUrl = process.env.STOREFRONT_URL; + const secret = process.env.STOREFRONT_REVALIDATE_SECRET; + if (!storefrontUrl || !secret) return; + + const logger = container.resolve(ContainerRegistrationKeys.LOGGER); + try { + const response = await fetch(new URL('/api/revalidate', storefrontUrl), { + method: 'POST', + headers: { 'x-revalidate-secret': secret }, + signal: AbortSignal.timeout(5000), + }); + if (!response.ok) logger.warn(`Storefront revalidate after ${event.name} returned HTTP ${response.status}`); + } catch (error) { + logger.warn(`Storefront revalidate after ${event.name} failed: ${(error as Error).message}`); + } +} + +export const config: SubscriberConfig = { + event: [ + ...Object.values(ProductWorkflowEvents), + ...Object.values(ProductVariantWorkflowEvents), + ...Object.values(ProductCategoryWorkflowEvents), + ...Object.values(ProductCollectionWorkflowEvents), + ], +}; diff --git a/apps/storefront/.env.template b/apps/storefront/.env.template index 76b012c0d..041b2e71c 100644 --- a/apps/storefront/.env.template +++ b/apps/storefront/.env.template @@ -1,3 +1,5 @@ STRIPE_PUBLIC_KEY='pk_' STRIPE_SECRET_KEY='sk_' -MEDUSA_PUBLISHABLE_KEY='pk_' \ No newline at end of file +MEDUSA_PUBLISHABLE_KEY='pk_' +# Shared with Medusa's STOREFRONT_REVALIDATE_SECRET so product changes clear this server's cache. +STOREFRONT_REVALIDATE_SECRET= diff --git a/apps/storefront/app/routes/api.revalidate.ts b/apps/storefront/app/routes/api.revalidate.ts new file mode 100644 index 000000000..32a9d004f --- /dev/null +++ b/apps/storefront/app/routes/api.revalidate.ts @@ -0,0 +1,21 @@ +import { timingSafeEqual } from 'node:crypto'; +import { sdkCache } from '@libs/util/server/client.server'; +import type { ActionFunctionArgs } from 'react-router'; + +/** + * Clears this server's cached Medusa data, so the next page load shows current products. Medusa calls it when a + * product changes. Disabled unless STOREFRONT_REVALIDATE_SECRET is set, and the caller must send that secret. + */ +export const action = async ({ request }: ActionFunctionArgs) => { + const secret = process.env.STOREFRONT_REVALIDATE_SECRET; + if (request.method !== 'POST') return Response.json({ error: 'Method not allowed' }, { status: 405 }); + // Compare byte lengths, not string lengths: timingSafeEqual throws on buffers of different sizes. + const sent = Buffer.from(request.headers.get('x-revalidate-secret') ?? ''); + const expected = Buffer.from(secret ?? ''); + if (!secret || sent.length !== expected.length || !timingSafeEqual(sent, expected)) { + return Response.json({ error: 'Not found' }, { status: 404 }); + } + + sdkCache.clear(); + return Response.json({ revalidated: true }); +}; diff --git a/apps/storefront/libs/util/server/cache-builder.server.ts b/apps/storefront/libs/util/server/cache-builder.server.ts index 8f2d6f96c..7ce65d900 100644 --- a/apps/storefront/libs/util/server/cache-builder.server.ts +++ b/apps/storefront/libs/util/server/cache-builder.server.ts @@ -3,7 +3,10 @@ import { LRUCache } from 'lru-cache'; export const buildNewLRUCache = ({ max }: { max: number }) => { const lruInstance = new LRUCache({ max }); - const lru: Cache = { + const lru: Cache & { clear: () => void } = { + clear() { + lruInstance.clear(); + }, set(key, value) { const ttl = totalTtl(value?.metadata); return lruInstance.set(key, value, { diff --git a/biome.json b/biome.json index 248a0da6e..0910d784d 100644 --- a/biome.json +++ b/biome.json @@ -16,6 +16,7 @@ "!**/yarn.lock", "!**/node_modules", "!**/apps/medusa/.medusa", + "!**/packages/*/.medusa", "!**/apps/storefront/.react-router", "!**/build", "!**/dist", diff --git a/package.json b/package.json index c330d53e1..337858cfb 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "format": "turbo run format", "clean": "find . -name \"node_modules\" -type d -prune -exec rm -rf '{}'", "typecheck": "turbo run typecheck", + "test:unit": "turbo run test:unit", "e2e": "yarn workspace e2e test", "e2e:ui": "yarn workspace e2e test:ui", "e2e:debug": "yarn workspace e2e test:debug", diff --git a/packages/medusa-mcp/.gitignore b/packages/medusa-mcp/.gitignore new file mode 100644 index 000000000..567268cd7 --- /dev/null +++ b/packages/medusa-mcp/.gitignore @@ -0,0 +1,3 @@ +/.medusa +.env +node_modules diff --git a/packages/medusa-mcp/README.md b/packages/medusa-mcp/README.md new file mode 100644 index 000000000..9dc17ffa8 --- /dev/null +++ b/packages/medusa-mcp/README.md @@ -0,0 +1,114 @@ +# @lambdacurry/medusa-mcp + +A Medusa plugin that serves an MCP endpoint for AI agents. The tools are generated from the store's +OpenAPI spec, and agents sign in through OAuth issued by Medusa itself, so every call runs as a real +Medusa admin. + +Status: in development on `feat/medusa-mcp`. Design and plan: Arbor thread DEM-17. + +## What it serves + +| Route | Purpose | +| --- | --- | +| `/mcp` | The MCP endpoint (Streamable HTTP). Requires a bearer token this server issued. | +| `/.well-known/oauth-authorization-server` | OAuth 2.1 metadata (PKCE S256, CIMD, DCR, `iss`). | +| `/.well-known/oauth-protected-resource/mcp` | Protected resource metadata for `/mcp`. | +| `/oauth/authorize`, `/oauth/token`, `/oauth/register` | Sign-in with a Medusa admin account, consent, tokens, and client registration. | + +## Tools + +| Tool | Scope | Does | +| --- | --- | --- | +| `search_api` | `mcp:read` | Ranked operations for a task, keyed `METHOD /path`. | +| `describe_api` | `mcp:read` | Parameters, request body, and response shape for one operation. | +| `read_api` | `mcp:read` | Calls a GET as the signed-in admin. | +| `write_api` | `mcp:write` | Calls a POST, PUT, or PATCH after validating the body. `dry_run` previews current vs proposed values. | +| `delete_api` | `mcp:delete` | Calls a DELETE. Marked destructive. | + +Calls run against Medusa's own API as the admin who connected, with a short-lived admin JWT, so Medusa's +permissions and validators apply. A built-in blocklist (`src/mcp/policy.ts`) keeps agents away from auth, +API keys, invites, admin user changes, and arbitrary workflow runs. Writes and deletes are logged with the admin, +client, operation, and spec revision, and each token is limited to 120 calls and 30 changes per minute. + +## Options + +```ts +{ + resolve: '@lambdacurry/medusa-mcp', + options: { + issuer: process.env.MCP_ISSUER, // public origin, for example a tunnel URL; defaults to http://localhost:9000 + blockedOperations: ['DELETE /admin/products/{id}', '* /admin/gift-cards/**'], // added to the built-in list + }, +} +``` + +## Recording the demo locally + +The demo: an agent in ChatGPT connects to a local Barrio, finds the product update operation, previews and applies a +new description for Barrio Decaf, and the storefront shows it. `apps/e2e/tests/mcp-demo.spec.ts` runs the same +script without ChatGPT. + +1. **Pick a hostname** on a domain in your Cloudflare account and set it for the shell commands below: + ```sh + export HOST=mcp.example.com + ``` +2. **Configure the environment, with strong secrets.** `yarn generate-env` copies `JWT_SECRET=supersecret` and + `COOKIE_SECRET=supersecret` from the public template, and Medusa also falls back to `supersecret` when they are + unset. With a known JWT secret anyone can forge an admin token, so set both to new random values in + `apps/medusa/.env`, for example from `openssl rand -base64 48`. While `MCP_ISSUER` is public, the plugin refuses + OAuth and MCP requests with a 503 if either secret is unset, `supersecret`, or shorter than 16 characters. + Also in `apps/medusa/.env`: + - `MCP_ISSUER` set to your hostname written out, for example `MCP_ISSUER=https://mcp.example.com`. `.env` files + do not expand `$HOST`. + - `STOREFRONT_URL=http://localhost:3000` and a random `STOREFRONT_REVALIDATE_SECRET`. Put the same secret in + `apps/storefront/.env`. + + Then run `yarn dev`. If Medusa was already running, restart it so the new secrets take effect. +3. **Replace the seeded admins. This step is required before opening the tunnel.** `yarn medusa:init` creates + `admin@medusa-test.com` and `admin@lambdacurry.dev` with the passwords in `apps/medusa/package.json`, which is + public. The tunnel puts the Medusa admin and this plugin's sign-in page on the internet, so anyone could use those + accounts. With Medusa running, create your own admin with a long random password: + ```sh + yarn workspace medusa medusa user -e you@example.com -p '' + ``` + Then sign in as that admin at http://localhost:9000/app, open Settings → Users, and delete both seeded accounts. +4. **Open the tunnel** to Medusa: + ```sh + cloudflared tunnel create barrio-mcp + cloudflared tunnel route dns barrio-mcp $HOST + cloudflared tunnel run --url http://localhost:9000 barrio-mcp + ``` +5. **Check it from outside.** `curl https://$HOST/.well-known/oauth-authorization-server` should show + `"issuer":"https://$HOST"`, and `curl -i -X POST https://$HOST/mcp` should answer `401` with a + `resource_metadata` challenge. +6. **Connect ChatGPT.** At chatgpt.com/plugins, add a custom MCP server with URL `https://$HOST/mcp` and OAuth. + Connecting opens the Medusa sign-in page. Sign in with the admin you created in step 3 and approve. +7. **Between takes**, run `yarn workspace medusa demo:reset` to restore the seeded titles and descriptions. + +The tunnel exposes the local Medusa admin API to the internet while it runs. Stop it when you finish recording. + +## Local development + +The plugin is a Yarn workspace linked into `apps/medusa`, not installed through yalc, so +`medusa plugin:develop` is not used. + +- `yarn dev` at the repo root builds the plugin first (Turbo `dependsOn: ["^build"]`), then starts the apps. +- After changing plugin code, run `yarn workspace @lambdacurry/medusa-mcp build` and restart Medusa. The + running app does not reload when the plugin's build output changes. + +## Notes + +- Sign-in and consent pages are signed with a random key made when Medusa starts, not with Medusa's secrets, so + they cannot be forged from a known default secret. A restart, or a request reaching a different Medusa instance, + expires an open page; the user starts the connection again. + +- `tsconfig.json` lists `src/api/.well-known/**/*` explicitly. TypeScript's `src/**/*` skips dot + directories, and OAuth discovery needs routes under `/.well-known/`. +- `files` lists `.medusa/server/**`, not `.medusa/server`. Yarn's pack drops the plain form without an error, and + the production image installs the plugin from a packed tarball (`scripts/docker-workspace-packages.mjs`), so the + image would build and then fail at boot. The script refuses a tarball that lacks the files `exports` names. +- `src/admin/` must exist even before the plugin has admin extensions. Without it, the app's admin build + cannot resolve `@lambdacurry/medusa-mcp/admin`. +- The plugin resolves its own copy of `@medusajs/framework` from the root `node_modules`, while the app + uses `apps/medusa/node_modules`. Routes, `MedusaError` handling, and modules with models and migrations + all work across the two copies. Watch for it if something compares framework classes by identity. diff --git a/packages/medusa-mcp/jest.config.js b/packages/medusa-mcp/jest.config.js new file mode 100644 index 000000000..6b1dacd6c --- /dev/null +++ b/packages/medusa-mcp/jest.config.js @@ -0,0 +1,9 @@ +module.exports = { + transform: { + '^.+\\.[jt]s$': ['@swc/jest', { jsc: { parser: { syntax: 'typescript', decorators: true } } }], + }, + testEnvironment: 'node', + moduleFileExtensions: ['js', 'ts', 'json'], + modulePathIgnorePatterns: ['/.medusa/'], + testMatch: ['/src/**/__tests__/**/*.unit.spec.ts'], +}; diff --git a/packages/medusa-mcp/package.json b/packages/medusa-mcp/package.json new file mode 100644 index 000000000..b0b77a2ca --- /dev/null +++ b/packages/medusa-mcp/package.json @@ -0,0 +1,59 @@ +{ + "name": "@lambdacurry/medusa-mcp", + "version": "0.0.1", + "description": "MCP server for Medusa: OpenAPI-driven tools behind Medusa-issued OAuth", + "author": "Lambda Curry (https://lambdacurry.dev)", + "license": "MIT", + "files": [ + ".medusa/server/**", + "specs" + ], + "exports": { + "./package.json": "./package.json", + "./openapi": "./.medusa/server/src/openapi/index.js", + "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js", + "./*": "./.medusa/server/src/*.js", + "./admin": { + "import": "./.medusa/server/src/admin/index.mjs", + "require": "./.medusa/server/src/admin/index.js", + "default": "./.medusa/server/src/admin/index.js" + } + }, + "keywords": [ + "medusa", + "medusa-v2", + "medusa-plugin", + "mcp" + ], + "scripts": { + "build": "medusa plugin:build", + "typecheck": "tsc --noEmit", + "test:unit": "TEST_TYPE=unit jest --runInBand", + "fetch-core-specs": "node scripts/fetch-core-specs.mjs" + }, + "dependencies": { + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", + "ajv": "^8.13.0", + "ajv-formats": "^3.0.1" + }, + "devDependencies": { + "@medusajs/cli": "2.22.1", + "@medusajs/framework": "2.22.1", + "@medusajs/medusa": "2.22.1", + "@swc/core": "^1.16.20", + "@swc/jest": "^0.2.39", + "@types/jest": "^30.0.0", + "@types/node": "26.6.5", + "jest": "^30.5.2", + "ts-node": "^10.9.2", + "typescript": "^6.0.3" + }, + "peerDependencies": { + "@medusajs/framework": "^2.22.1", + "@medusajs/medusa": "^2.22.1" + }, + "engines": { + "node": ">=26" + } +} diff --git a/packages/medusa-mcp/scripts/fetch-core-specs.mjs b/packages/medusa-mcp/scripts/fetch-core-specs.mjs new file mode 100644 index 000000000..68a776767 --- /dev/null +++ b/packages/medusa-mcp/scripts/fetch-core-specs.mjs @@ -0,0 +1,35 @@ +// Pins Medusa's published core OpenAPI specs for one version into specs//. +// Usage: node scripts/fetch-core-specs.mjs 2.22.1 +import { createHash } from 'node:crypto'; +import { mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { gzipSync } from 'node:zlib'; + +const version = process.argv[2]; +if (!/^\d+\.\d+\.\d+$/.test(version ?? '')) { + throw new Error('Pass an exact Medusa version, for example: node scripts/fetch-core-specs.mjs 2.22.1'); +} + +const specsDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../specs', version); +const manifest = { medusaVersion: version, source: 'https://docs.medusajs.com/api/versions', specs: {} }; + +for (const area of ['admin', 'store']) { + const url = `https://assets.docs.medusajs.com/api-reference/specs/versions/${version}/${area}/openapi.full.json`; + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + if (!response.ok) throw new Error(`GET ${url} returned HTTP ${response.status}`); + + const text = await response.text(); + const document = JSON.parse(text); + if (document.info?.version !== version) { + throw new Error(`${url} describes version ${document.info?.version}, expected ${version}`); + } + + const file = `${area}.openapi.json.gz`; + await mkdir(specsDir, { recursive: true }); + await writeFile(path.join(specsDir, file), gzipSync(text, { level: 9 })); + manifest.specs[area] = { file, url, sha256: createHash('sha256').update(text).digest('hex') }; + console.log(`${area}: ${Object.keys(document.paths).length} paths, sha256 ${manifest.specs[area].sha256}`); +} + +await writeFile(path.join(specsDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`); diff --git a/packages/medusa-mcp/specs/2.22.1/admin.openapi.json.gz b/packages/medusa-mcp/specs/2.22.1/admin.openapi.json.gz new file mode 100644 index 000000000..2eee3773e Binary files /dev/null and b/packages/medusa-mcp/specs/2.22.1/admin.openapi.json.gz differ diff --git a/packages/medusa-mcp/specs/2.22.1/manifest.json b/packages/medusa-mcp/specs/2.22.1/manifest.json new file mode 100644 index 000000000..265ed2e2e --- /dev/null +++ b/packages/medusa-mcp/specs/2.22.1/manifest.json @@ -0,0 +1,16 @@ +{ + "medusaVersion": "2.22.1", + "source": "https://docs.medusajs.com/api/versions", + "specs": { + "admin": { + "file": "admin.openapi.json.gz", + "url": "https://assets.docs.medusajs.com/api-reference/specs/versions/2.22.1/admin/openapi.full.json", + "sha256": "ee624f60aa5b7a95ef69343f74bea19df9e849d1d1a1da0cd9ad1891d0e1e7a0" + }, + "store": { + "file": "store.openapi.json.gz", + "url": "https://assets.docs.medusajs.com/api-reference/specs/versions/2.22.1/store/openapi.full.json", + "sha256": "463b5acb0b322e82086d4701e4588badb6095d8d3f40263948f07b827588723b" + } + } +} diff --git a/packages/medusa-mcp/specs/2.22.1/store.openapi.json.gz b/packages/medusa-mcp/specs/2.22.1/store.openapi.json.gz new file mode 100644 index 000000000..f91726307 Binary files /dev/null and b/packages/medusa-mcp/specs/2.22.1/store.openapi.json.gz differ diff --git a/packages/medusa-mcp/src/admin/tsconfig.json b/packages/medusa-mcp/src/admin/tsconfig.json new file mode 100644 index 000000000..76cc58ae3 --- /dev/null +++ b/packages/medusa-mcp/src/admin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "esnext" + }, + "include": ["."], + "exclude": ["**/*.spec.js"] +} diff --git a/packages/medusa-mcp/src/api/.well-known/oauth-authorization-server/route.ts b/packages/medusa-mcp/src/api/.well-known/oauth-authorization-server/route.ts new file mode 100644 index 000000000..d51082dd7 --- /dev/null +++ b/packages/medusa-mcp/src/api/.well-known/oauth-authorization-server/route.ts @@ -0,0 +1,7 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { oauthService } from '../../../lib/oauth-http'; +import { authorizationServerMetadata } from '../../../modules/mcp_oauth/config'; + +export const GET = (req: MedusaRequest, res: MedusaResponse) => { + res.json(authorizationServerMetadata(oauthService(req).config)); +}; diff --git a/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/mcp/route.ts b/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/mcp/route.ts new file mode 100644 index 000000000..1ae017b82 --- /dev/null +++ b/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/mcp/route.ts @@ -0,0 +1,7 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { oauthService } from '../../../../lib/oauth-http'; +import { protectedResourceMetadata } from '../../../../modules/mcp_oauth/config'; + +export const GET = (req: MedusaRequest, res: MedusaResponse) => { + res.json(protectedResourceMetadata(oauthService(req).config)); +}; diff --git a/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/route.ts b/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/route.ts new file mode 100644 index 000000000..9f4df7ab6 --- /dev/null +++ b/packages/medusa-mcp/src/api/.well-known/oauth-protected-resource/route.ts @@ -0,0 +1,7 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { oauthService } from '../../../lib/oauth-http'; +import { protectedResourceMetadata } from '../../../modules/mcp_oauth/config'; + +export const GET = (req: MedusaRequest, res: MedusaResponse) => { + res.json(protectedResourceMetadata(oauthService(req).config)); +}; diff --git a/packages/medusa-mcp/src/api/mcp/route.ts b/packages/medusa-mcp/src/api/mcp/route.ts new file mode 100644 index 000000000..009b4bdda --- /dev/null +++ b/packages/medusa-mcp/src/api/mcp/route.ts @@ -0,0 +1,136 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import type { IApiKeyModuleService, IAuthModuleService } from '@medusajs/framework/types'; +import { ContainerRegistrationKeys, MedusaError, Modules } from '@medusajs/framework/utils'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import { type AuthInfo, createMcpHandler } from '@modelcontextprotocol/server'; +import { oauthService } from '../../lib/oauth-http'; +import type { ExecutionTarget } from '../../mcp/execute'; +import { getApiRegistry } from '../../mcp/registry'; +import { buildMcpServer } from '../../mcp/server'; +import type { VerifiedAccessToken } from '../../modules/mcp_oauth/service'; + +const ADMIN_TOKEN_TTL = '5m'; + +/** This server's own origin as the incoming request reached it, for loopback API calls. */ +function localBaseUrl(req: MedusaRequest): string { + let host = req.socket.localAddress ?? '127.0.0.1'; + if (host.startsWith('::ffff:')) host = host.slice('::ffff:'.length); + if (host.includes(':')) host = `[${host}]`; + return `http://${host}:${req.socket.localPort}`; +} + +function executionTarget( + req: MedusaRequest, + authIdentity: Parameters[1], + verified: VerifiedAccessToken, + revision: string, +): ExecutionTarget { + let adminToken: Promise | undefined; + let publishableKey: Promise | undefined; + const logger = req.scope.resolve(ContainerRegistrationKeys.LOGGER); + return { + tokenId: verified.token_id, + scopes: verified.scopes, + audit: async (entry) => { + logger.info( + `[medusa-mcp] ${JSON.stringify({ ...entry, user_id: verified.user_id, client_id: verified.client_id, spec_revision: revision.slice(0, 12) })}`, + ); + }, + baseUrl: localBaseUrl(req), + adminToken: () => (adminToken ??= generateAdminJwt(req, authIdentity)), + publishableKey: () => + (publishableKey ??= req.scope + .resolve(Modules.API_KEY) + .listApiKeys({ type: 'publishable' }, { order: { created_at: 'ASC' } }) + .then((keys) => keys.find((key) => !key.revoked_at)?.token)), + }; +} + +/** Mints a short-lived Medusa admin JWT with Medusa's own helper, so roles and MFA claims match its login. */ +async function generateAdminJwt( + req: MedusaRequest, + authIdentity: Awaited>, +): Promise { + const { http } = req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE).projectConfig; + const { generateJwtTokenForAuthIdentity } = require( + require.resolve('@medusajs/medusa/api/auth/utils/generate-jwt-token', { paths: [process.cwd()] }), + ) as typeof import('@medusajs/medusa/api/auth/utils/generate-jwt-token'); + return generateJwtTokenForAuthIdentity( + { + authIdentity, + actorType: 'user', + authProvider: authIdentity.provider_identities?.[0]?.provider ?? 'emailpass', + container: req.scope, + }, + { secret: http.jwtSecret as string, expiresIn: ADMIN_TOKEN_TTL, options: http.jwtOptions }, + ); +} + +function challenge(res: MedusaResponse, resourceMetadataUrl: string, error?: string) { + const parts = [`resource_metadata="${resourceMetadataUrl}"`]; + if (error) parts.push('error="invalid_token"', `error_description="${error}"`); + res + .status(401) + .set('WWW-Authenticate', `Bearer ${parts.join(', ')}`) + .json({ + error: error ? 'invalid_token' : 'unauthorized', + error_description: error ?? 'Sign in to use this MCP server', + }); +} + +/** The MCP endpoint. Requires an access token this server issued for this resource, for a still-linked admin. */ +async function serve(req: MedusaRequest, res: MedusaResponse) { + const service = oauthService(req); + const resourceMetadataUrl = `${service.config.issuer}/.well-known/oauth-protected-resource/mcp`; + + const bearer = /^Bearer\s+(\S+)$/i.exec(req.headers.authorization ?? '')?.[1]; + if (!bearer) return challenge(res, resourceMetadataUrl); + const verified: VerifiedAccessToken | undefined = await service.verifyAccessToken(bearer, service.config.resource); + if (!verified) return challenge(res, resourceMetadataUrl, 'The access token is invalid, expired, or revoked'); + + const authIdentity = await req.scope + .resolve(Modules.AUTH) + .retrieveAuthIdentity(verified.auth_identity_id, { relations: ['provider_identities'] }) + .catch((error: { type?: string }) => { + // Only a missing identity means the admin is gone. Anything else, such as a database timeout, must not + // revoke a valid grant. + if (error?.type === MedusaError.Types.NOT_FOUND) return undefined; + throw error; + }); + if (authIdentity?.app_metadata?.user_id !== verified.user_id) { + const [token] = await service.listMcpOAuthTokens({ id: verified.token_id }); + if (token) await service.revokeFamily(token.family_id); + return challenge(res, resourceMetadataUrl, 'The admin account behind this token no longer exists'); + } + + const { plugins = [] } = req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE); + const registry = getApiRegistry({ + projectRoot: process.cwd(), + plugins: plugins.map((plugin: string | { resolve: string }) => + typeof plugin === 'string' ? plugin : plugin.resolve, + ), + blockedOperations: service.options.blockedOperations, + }); + + const auth: AuthInfo = { + token: bearer, + clientId: verified.client_id, + scopes: verified.scopes, + expiresAt: Math.floor(verified.expires_at.getTime() / 1000), + resource: new URL(verified.resource), + resourceMetadataUrl, + extra: { user_id: verified.user_id }, + }; + (req as MedusaRequest & { auth: AuthInfo }).auth = auth; + + const handler = toNodeHandler( + createMcpHandler(() => + buildMcpServer(registry, executionTarget(req, authIdentity, verified, registry.catalog.spec.revision)), + ), + ); + await handler(req, res, req.body); +} + +export const GET = serve; +export const POST = serve; +export const DELETE = serve; diff --git a/packages/medusa-mcp/src/api/middlewares.ts b/packages/medusa-mcp/src/api/middlewares.ts new file mode 100644 index 000000000..13e2a61fb --- /dev/null +++ b/packages/medusa-mcp/src/api/middlewares.ts @@ -0,0 +1,87 @@ +import { + authenticate, + defineMiddlewares, + type MedusaNextFunction, + type MedusaRequest, + type MedusaResponse, +} from '@medusajs/framework/http'; +import { ContainerRegistrationKeys } from '@medusajs/framework/utils'; +import { oauthService } from '../lib/oauth-http'; +import { isLoopbackHost } from '../modules/mcp_oauth/config'; + +/** Medusa falls back to this for both secrets when they are unset outside production. */ +const MEDUSA_DEFAULT_SECRET = 'supersecret'; +const MIN_PUBLIC_SECRET_LENGTH = 16; + +/** Which of Medusa's signing secrets are too weak to expose this server publicly. */ +export function weakSecrets(http: { jwtSecret?: unknown; cookieSecret?: unknown }): string[] { + return ( + [ + ['JWT_SECRET', http.jwtSecret], + ['COOKIE_SECRET', http.cookieSecret], + ] as const + ) + .filter( + ([, value]) => + value === undefined || + value === null || + (typeof value === 'string' && (value === MEDUSA_DEFAULT_SECRET || value.length < MIN_PUBLIC_SECRET_LENGTH)), + ) + .map(([name]) => name); +} + +/** + * Refuses OAuth and MCP traffic when the issuer is public but Medusa still signs with a default or short secret. + * Anyone could forge an admin token with a known JWT secret, so a public tunnel over one must fail closed. + */ +function requireStrongSecretsWhenPublic(req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) { + const issuer = new URL(oauthService(req).config.issuer); + if (isLoopbackHost(issuer.hostname)) return next(); + const weak = weakSecrets(req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE).projectConfig.http); + if (!weak.length) return next(); + res.status(503).json({ + error: 'server_misconfigured', + error_description: `${issuer.origin} is public, but ${weak.join(' and ')} ${weak.length > 1 ? 'are' : 'is'} unset, Medusa's default, or shorter than ${MIN_PUBLIC_SECRET_LENGTH} characters. Set strong random values and restart Medusa.`, + }); +} + +/** + * CORS for endpoints that browser-based MCP clients call directly. They are public or bearer-only and never read + * cookies, so any origin may call them without credentials. Preflight requests are answered here. + */ +function allowCrossOrigin(req: MedusaRequest, res: MedusaResponse, next: MedusaNextFunction) { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS'); + res.setHeader( + 'Access-Control-Allow-Headers', + 'authorization, content-type, accept, mcp-protocol-version, mcp-session-id, last-event-id', + ); + res.setHeader('Access-Control-Expose-Headers', 'WWW-Authenticate, mcp-session-id, mcp-protocol-version'); + res.setHeader('Access-Control-Max-Age', '86400'); + if (req.method === 'OPTIONS') { + res.status(204).end(); + return; + } + next(); +} + +export default defineMiddlewares({ + routes: [ + { + // Lets an admin already signed in to the Medusa admin skip the login form. + matcher: '/oauth/authorize', + method: ['GET'], + middlewares: [authenticate('user', ['session'], { allowUnauthenticated: true })], + }, + ...[ + '/oauth/token', + '/oauth/register', + '/.well-known/oauth-authorization-server', + '/.well-known/oauth-protected-resource*', + '/mcp', + ].map((matcher) => ({ matcher, middlewares: [allowCrossOrigin] })), + ...['/oauth*', '/mcp', '/.well-known/oauth-authorization-server', '/.well-known/oauth-protected-resource*'].map( + (matcher) => ({ matcher, middlewares: [requireStrongSecretsWhenPublic] }), + ), + ], +}); diff --git a/packages/medusa-mcp/src/api/oauth/authorize/consent/route.ts b/packages/medusa-mcp/src/api/oauth/authorize/consent/route.ts new file mode 100644 index 000000000..a8202d228 --- /dev/null +++ b/packages/medusa-mcp/src/api/oauth/authorize/consent/route.ts @@ -0,0 +1,45 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { formSecret, oauthService, redirectToClient } from '../../../../lib/oauth-http'; +import { errorPage, sendPage } from '../../../../lib/oauth-pages'; +import type { McpScope } from '../../../../modules/mcp_oauth/config'; +import { verifyPayload } from '../../../../modules/mcp_oauth/crypto'; +import type { AuthorizationRequest, AuthorizingUser } from '../../../../modules/mcp_oauth/service'; + +/** Records the admin's decision. Approving issues a single-use code for the scopes they left checked. */ +export const POST = async (req: MedusaRequest, res: MedusaResponse) => { + const body = (req.body ?? {}) as Record; + const grant = verifyPayload<{ request: AuthorizationRequest } & AuthorizingUser>( + 'consent', + body.grant, + formSecret(req), + ); + if (!grant || typeof grant.user_id !== 'string' || typeof grant.auth_identity_id !== 'string') { + sendPage( + res, + 400, + errorPage('This approval form expired or was changed. Start the connection again from your app.'), + ); + return; + } + + const service = oauthService(req); + const { request } = grant; + const checked = new Set([body.scope].flat().filter((scope): scope is string => typeof scope === 'string')); + const scopes = request.scopes.filter((scope): scope is McpScope => checked.has(scope)); + + if (body.decision !== 'approve' || !scopes.length) { + redirectToClient(res, service.config.issuer, request.redirect_uri, { + error: 'access_denied', + error_description: body.decision === 'approve' ? 'No permissions were granted' : 'The admin denied access', + state: request.state, + }); + return; + } + + const code = await service.issueAuthorizationCode( + request, + { user_id: grant.user_id, auth_identity_id: grant.auth_identity_id }, + scopes, + ); + redirectToClient(res, service.config.issuer, request.redirect_uri, { code, state: request.state }); +}; diff --git a/packages/medusa-mcp/src/api/oauth/authorize/login/route.ts b/packages/medusa-mcp/src/api/oauth/authorize/login/route.ts new file mode 100644 index 000000000..2c77440f6 --- /dev/null +++ b/packages/medusa-mcp/src/api/oauth/authorize/login/route.ts @@ -0,0 +1,72 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import type { IAuthModuleService } from '@medusajs/framework/types'; +import { Modules } from '@medusajs/framework/utils'; +import { AUTHORIZE_FORM_TTL_SECONDS, formSecret } from '../../../../lib/oauth-http'; +import { consentPage, errorPage, loginPage, sendPage } from '../../../../lib/oauth-pages'; +import { signPayload, verifyPayload } from '../../../../modules/mcp_oauth/crypto'; +import type { AuthorizationRequest } from '../../../../modules/mcp_oauth/service'; + +const EXPIRED = 'This sign-in form expired or was changed. Start the connection again from your app.'; + +/** Signs in with a Medusa admin email and password through Medusa's own auth module, then shows consent. */ +export const POST = async (req: MedusaRequest, res: MedusaResponse) => { + const body = (req.body ?? {}) as Record; + const secret = formSecret(req); + const signed = verifyPayload<{ request: AuthorizationRequest }>('login', body.request, secret); + if (!signed) { + sendPage(res, 400, errorPage(EXPIRED)); + return; + } + const { request } = signed; + const retry = (status: number, error: string) => + sendPage( + res, + status, + loginPage({ + clientName: request.client_name, + redirectUri: request.redirect_uri, + request: String(body.request), + error, + }), + ); + + if (typeof body.email !== 'string' || typeof body.password !== 'string') { + retry(400, 'Enter your admin email and password.'); + return; + } + + const auth = req.scope.resolve(Modules.AUTH); + const { success, authIdentity, mfaChallenge } = await auth.authenticate('emailpass', { + url: req.url, + headers: req.headers as Record, + query: {}, + body: { email: body.email, password: body.password }, + protocol: req.protocol, + }); + + const userId = authIdentity?.app_metadata?.user_id; + if (!success || !authIdentity || typeof userId !== 'string') { + retry(401, 'That email and password did not match an admin account.'); + return; + } + if (mfaChallenge) { + retry( + 403, + 'This account uses two-factor authentication. Sign in to the Medusa admin in this browser first, then start the connection again.', + ); + return; + } + + const grant = signPayload( + 'consent', + { request, user_id: userId, auth_identity_id: authIdentity.id }, + secret, + AUTHORIZE_FORM_TTL_SECONDS, + ); + sendPage( + res, + 200, + consentPage({ clientName: request.client_name, redirectUri: request.redirect_uri, scopes: request.scopes, grant }), + [request.redirect_uri], + ); +}; diff --git a/packages/medusa-mcp/src/api/oauth/authorize/route.ts b/packages/medusa-mcp/src/api/oauth/authorize/route.ts new file mode 100644 index 000000000..736e1bd78 --- /dev/null +++ b/packages/medusa-mcp/src/api/oauth/authorize/route.ts @@ -0,0 +1,53 @@ +import type { AuthenticatedMedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { AUTHORIZE_FORM_TTL_SECONDS, formSecret, oauthService, sendAuthorizeError } from '../../../lib/oauth-http'; +import { consentPage, loginPage, sendPage } from '../../../lib/oauth-pages'; +import { signPayload } from '../../../modules/mcp_oauth/crypto'; +import type { AuthorizationRequest } from '../../../modules/mcp_oauth/service'; + +/** + * Starts an authorization. An admin already signed in to Medusa (by session cookie) goes straight to consent; + * anyone else signs in with their Medusa admin email and password first. + */ +export const GET = async (req: AuthenticatedMedusaRequest, res: MedusaResponse) => { + const service = oauthService(req); + let request: AuthorizationRequest; + try { + request = await service.parseAuthorizationRequest(req.query as Record); + } catch (error) { + sendAuthorizeError(res, service.config.issuer, error); + return; + } + + const secret = formSecret(req); + const auth = req.auth_context; + if (auth?.actor_type === 'user' && auth.actor_id && auth.auth_identity_id) { + const grant = signPayload( + 'consent', + { request, user_id: auth.actor_id, auth_identity_id: auth.auth_identity_id }, + secret, + AUTHORIZE_FORM_TTL_SECONDS, + ); + sendPage( + res, + 200, + consentPage({ + clientName: request.client_name, + redirectUri: request.redirect_uri, + scopes: request.scopes, + grant, + }), + [request.redirect_uri], + ); + return; + } + + sendPage( + res, + 200, + loginPage({ + clientName: request.client_name, + redirectUri: request.redirect_uri, + request: signPayload('login', { request }, secret, AUTHORIZE_FORM_TTL_SECONDS), + }), + ); +}; diff --git a/packages/medusa-mcp/src/api/oauth/register/route.ts b/packages/medusa-mcp/src/api/oauth/register/route.ts new file mode 100644 index 000000000..d817bc791 --- /dev/null +++ b/packages/medusa-mcp/src/api/oauth/register/route.ts @@ -0,0 +1,11 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { oauthService, sendOAuthError } from '../../../lib/oauth-http'; + +export const POST = async (req: MedusaRequest, res: MedusaResponse) => { + try { + const client = await oauthService(req).registerDynamicClient(req.body); + res.status(201).set('Cache-Control', 'no-store').json(client); + } catch (error) { + sendOAuthError(res, error); + } +}; diff --git a/packages/medusa-mcp/src/api/oauth/token/route.ts b/packages/medusa-mcp/src/api/oauth/token/route.ts new file mode 100644 index 000000000..0f2ec92e8 --- /dev/null +++ b/packages/medusa-mcp/src/api/oauth/token/route.ts @@ -0,0 +1,22 @@ +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { oauthService, sendOAuthError } from '../../../lib/oauth-http'; +import { OAuthError } from '../../../modules/mcp_oauth/errors'; + +/** The token endpoint for public clients: the `authorization_code` and `refresh_token` grants. */ +export const POST = async (req: MedusaRequest, res: MedusaResponse) => { + const params = (req.body ?? {}) as Record; + const service = oauthService(req); + try { + const tokens = + params.grant_type === 'authorization_code' + ? await service.exchangeAuthorizationCode(params) + : params.grant_type === 'refresh_token' + ? await service.refreshAccessToken(params) + : (() => { + throw new OAuthError('unsupported_grant_type', 'grant_type must be authorization_code or refresh_token'); + })(); + res.set({ 'Cache-Control': 'no-store', Pragma: 'no-cache' }).json(tokens); + } catch (error) { + sendOAuthError(res, error); + } +}; diff --git a/packages/medusa-mcp/src/lib/oauth-http.ts b/packages/medusa-mcp/src/lib/oauth-http.ts new file mode 100644 index 000000000..504d4179f --- /dev/null +++ b/packages/medusa-mcp/src/lib/oauth-http.ts @@ -0,0 +1,62 @@ +import { randomBytes } from 'node:crypto'; +import type { MedusaRequest, MedusaResponse } from '@medusajs/framework/http'; +import { MCP_OAUTH_MODULE } from '../modules/mcp_oauth'; +import { OAuthError, RedirectableOAuthError } from '../modules/mcp_oauth/errors'; +import type McpOAuthService from '../modules/mcp_oauth/service'; +import { errorPage, sendPage } from './oauth-pages'; + +/** How long a login or consent form stays valid. */ +export const AUTHORIZE_FORM_TTL_SECONDS = 10 * 60; + +export function oauthService(req: MedusaRequest): McpOAuthService { + return req.scope.resolve(MCP_OAUTH_MODULE); +} + +/** + * Signs authorize form state with a random key made when this process starts. Form state only has to survive the + * few minutes between showing a page and its submission, so it needs no shared secret. Keying it to Medusa's cookie + * or JWT secret instead would let anyone who knows a default secret forge a consent grant. A Medusa restart expires + * open sign-in and consent pages; the user starts the connection again. + */ +const FORM_SIGNING_KEY = randomBytes(32).toString('base64url'); + +export function formSecret(_req: MedusaRequest): string { + return FORM_SIGNING_KEY; +} + +/** Redirects back to the client with an authorization response, always naming the issuer (RFC 9207). */ +export function redirectToClient( + res: MedusaResponse, + issuer: string, + redirectUri: string, + params: Record, +): void { + const url = new URL(redirectUri); + for (const [key, value] of Object.entries({ ...params, iss: issuer })) { + if (value !== undefined) url.searchParams.set(key, value); + } + res.set('Cache-Control', 'no-store').redirect(302, url.toString()); +} + +/** Reports an authorize-endpoint error: by redirect once the redirect URI is trusted, otherwise on a page. */ +export function sendAuthorizeError(res: MedusaResponse, issuer: string, error: unknown): void { + if (error instanceof RedirectableOAuthError) { + redirectToClient(res, issuer, error.redirectUri, { + error: error.code, + error_description: error.message, + state: error.state, + }); + return; + } + if (error instanceof OAuthError) { + sendPage(res, error.status, errorPage(error.message)); + return; + } + throw error; +} + +/** Sends an OAuthError as `{ error, error_description }`; rethrows anything else for Medusa's error handler. */ +export function sendOAuthError(res: MedusaResponse, error: unknown): void { + if (!(error instanceof OAuthError)) throw error; + res.status(error.status).set('Cache-Control', 'no-store').json(error.toJSON()); +} diff --git a/packages/medusa-mcp/src/lib/oauth-pages.ts b/packages/medusa-mcp/src/lib/oauth-pages.ts new file mode 100644 index 000000000..1467e46ff --- /dev/null +++ b/packages/medusa-mcp/src/lib/oauth-pages.ts @@ -0,0 +1,120 @@ +import type { MedusaResponse } from '@medusajs/framework/http'; +import type { McpScope } from '../modules/mcp_oauth/config'; + +const SCOPE_DESCRIPTIONS: Record = { + 'mcp:read': 'Read store data through the Admin and Store APIs', + 'mcp:write': 'Create and update store data', + 'mcp:delete': 'Delete store data', +}; + +export function escapeHtml(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); +} + +function layout(title: string, body: string): string { + return ` + + + + +${escapeHtml(title)} + + +
${body}
+`; +} + +/** + * Sends an authorize page that cannot be framed or cached. `formTargets` lists origins a form on the page may end + * up at: Chrome and Safari apply `form-action` to the redirect that follows a submission, so the consent page must + * allow the client's (already verified) redirect URI origin. + */ +export function sendPage(res: MedusaResponse, status: number, html: string, formTargets: string[] = []): void { + const formAction = ["'self'", ...formTargets.map((uri) => new URL(uri).origin)].join(' '); + res + .status(status) + .set({ + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Frame-Options': 'DENY', + 'Content-Security-Policy': `default-src 'none'; style-src 'unsafe-inline'; form-action ${formAction}; frame-ancestors 'none'`, + 'Referrer-Policy': 'no-referrer', + }) + .send(html); +} + +function clientLine(clientName: string, redirectUri: string): string { + return `

${escapeHtml(clientName)} wants to use this store's Medusa API as you. After you approve, you return to ${escapeHtml(new URL(redirectUri).host)}.

`; +} + +export function loginPage(input: { clientName: string; redirectUri: string; request: string; error?: string }): string { + return layout( + 'Sign in to connect', + `

Sign in to connect

+${clientLine(input.clientName, input.redirectUri)} +${input.error ? `

${escapeHtml(input.error)}

` : ''} +
+ + + + + +
+
`, + ); +} + +export function consentPage(input: { + clientName: string; + redirectUri: string; + scopes: McpScope[]; + grant: string; +}): string { + const scopes = input.scopes + .map( + (scope) => ``, + ) + .join('\n'); + + return layout( + 'Allow access', + `

Allow access?

+${clientLine(input.clientName, input.redirectUri)} +
+ + ${scopes} +

Every call runs with your Medusa admin permissions. Clear a box to withhold that permission.

+
+ + +
+
`, + ); +} + +export function errorPage(message: string): string { + return layout('Cannot connect', `

Cannot connect

${escapeHtml(message)}

`); +} diff --git a/packages/medusa-mcp/src/mcp/__tests__/mcp.unit.spec.ts b/packages/medusa-mcp/src/mcp/__tests__/mcp.unit.spec.ts new file mode 100644 index 000000000..cf72c5326 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/__tests__/mcp.unit.spec.ts @@ -0,0 +1,226 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import path from 'node:path'; +import { buildApiSpec } from '../../openapi/build-spec'; +import { buildCatalog } from '../catalog'; +import { describeOperation } from '../describe'; +import { appendQuery, buildRequestUrl, declaredParameters, ExecutionError, executeOperation } from '../execute'; +import { BUILT_IN_BLOCKLIST, createPolicy } from '../policy'; +import { buildSearchIndex, queryIntent, tokenize } from '../search'; + +const spec = buildApiSpec({ projectRoot: path.join(__dirname, '../../openapi/__tests__/fixtures/valid') }); +const catalog = buildCatalog(spec, createPolicy()); +const operation = (key: string) => { + const found = catalog.byKey.get(key); + if (!found) throw new Error(`${key} is not in the catalog`); + return found; +}; + +describe('policy', () => { + const policy = createPolicy(['DELETE /admin/products/{id}', '* /admin/gift-cards/**']); + + it.each([ + ['POST', '/auth/user/{auth_provider}', '* /auth/**'], + ['GET', '/admin/api-keys', '* /admin/api-keys'], + ['GET', '/admin/api-keys/{id}', '* /admin/api-keys/**'], + ['POST', '/admin/invites/accept', '* /admin/invites/**'], + ['POST', '/admin/users/{id}', 'POST /admin/users/{id}'], + ['POST', '/admin/workflows-executions/{workflow_id}/run', '* /admin/workflows-executions/{workflow_id}/run'], + ['DELETE', '/admin/products/{id}', 'DELETE /admin/products/{id}'], + ['GET', '/admin/gift-cards/{id}', '* /admin/gift-cards/**'], + ] as const)('blocks %s %s', (method, route, rule) => { + expect(policy.blockedBy(method, route)).toBe(rule); + }); + + it.each([ + ['GET', '/admin/users/{id}'], + ['GET', '/admin/products/{id}'], + ['POST', '/admin/products/{id}'], + ['GET', '/admin/workflows-executions'], + ['GET', '/admin/api-keysmith'], + ] as const)('allows %s %s', (method, route) => { + expect(policy.blockedBy(method, route)).toBeUndefined(); + }); + + it('rejects malformed entries', () => { + expect(() => createPolicy(['/admin/products'])).toThrow(/Invalid medusa-mcp blocked operation/); + expect(() => createPolicy(['FETCH /admin/products'])).toThrow(/Invalid medusa-mcp blocked operation/); + }); + + it('only lists valid built-in entries', () => { + expect(() => createPolicy(BUILT_IN_BLOCKLIST)).not.toThrow(); + }); +}); + +describe('catalog', () => { + it('keys every operation by METHOD /path, once, even where Medusa reuses operationIds', () => { + expect(catalog.byKey.size).toBe(catalog.operations.length); + expect(operation('GET /admin/collections').operation_id).toBe('GetCollections'); + expect(operation('GET /store/collections').operation_id).toBe('GetCollections'); + expect(catalog.operations.filter((entry) => entry.operation === 'POST /auth/session')).toHaveLength(1); + }); + + it('maps methods to tools, marks blocked operations, and keeps custom routes', () => { + expect(operation('GET /admin/products').tool).toBe('read_api'); + expect(operation('POST /admin/products/{id}').tool).toBe('write_api'); + expect(operation('DELETE /admin/products/{id}').tool).toBe('delete_api'); + expect(operation('GET /admin/api-keys').blocked_by).toBe('* /admin/api-keys'); + expect(operation('GET /admin/widgets')).toMatchObject({ source: 'custom', tool: 'read_api' }); + }); +}); + +describe('describeOperation', () => { + it('keeps every operation under 25 KB', () => { + const largest = catalog.operations + .map((entry) => ({ + key: entry.operation, + bytes: JSON.stringify(describeOperation(spec.documents[entry.area], entry)).length, + })) + .sort((left, right) => right.bytes - left.bytes)[0]; + expect(largest.bytes).toBeLessThan(25 * 1024); + }); + + it('shows the product update body, including description, and the path parameter', () => { + const description = describeOperation(spec.documents.admin, operation('POST /admin/products/{id}')); + expect(description).toMatchObject({ + operation: 'POST /admin/products/{id}', + tool: 'write_api', + path_params: [{ name: 'id', in: 'path', required: true }], + }); + expect(JSON.stringify(description.request_body)).toContain('"description"'); + }); +}); + +describe('request URLs', () => { + const products = operation('GET /admin/products/{id}'); + const declared = declaredParameters(products); + + it('encodes path parameters and serializes queries the way Medusa parses them', () => { + expect( + buildRequestUrl('http://127.0.0.1:9000', products, declared, { + path_params: { id: 'prod/1 x' }, + query: { fields: 'id,title' }, + }), + ).toBe('http://127.0.0.1:9000/admin/products/prod%2F1%20x?fields=id%2Ctitle'); + + const params = new URLSearchParams(); + appendQuery(params, 'id', ['a', 'b']); + appendQuery(params, 'created_at', { $gte: '2026-01-01' }); + expect(decodeURIComponent(params.toString())).toBe('id[]=a&id[]=b&created_at[$gte]=2026-01-01'); + }); + + it('refuses dot-segment path parameters that would resolve to a different, unchecked path', () => { + const nested = operation('GET /admin/workflows-executions/{workflow_id}/{transaction_id}'); + const nestedDeclared = declaredParameters(nested); + expect(() => + buildRequestUrl('http://x', nested, nestedDeclared, { + path_params: { workflow_id: '..', transaction_id: 'api-keys' }, + }), + ).toThrow(/cannot be "\.\."/); + expect(() => buildRequestUrl('http://x', products, declared, { path_params: { id: '.' } })).toThrow(ExecutionError); + expect(() => buildRequestUrl('http://x', products, declared, { path_params: { id: '..' } })).toThrow( + ExecutionError, + ); + expect(buildRequestUrl('http://x', products, declared, { path_params: { id: '%2e%2e' } })).toBe( + 'http://x/admin/products/%252e%252e', + ); + }); + + it('refuses missing or unknown parameters instead of guessing', () => { + expect(() => buildRequestUrl('http://x', products, declared, {})).toThrow(ExecutionError); + expect(() => buildRequestUrl('http://x', products, declared, { path_params: { id: 'p', other: 'x' } })).toThrow( + /Unknown path parameter/, + ); + expect(() => + buildRequestUrl('http://x', products, declared, { path_params: { id: 'p' }, query: { nope: 1 } }), + ).toThrow(/Unknown query parameter/); + }); +}); + +describe('executeOperation', () => { + it('caps responses at 64 KB by bytes, without leaving a broken multi-byte character', async () => { + // One ASCII byte first, so the 64 KiB cut lands inside a two-byte character. + const body = `a${'é'.repeat(75_000)}`; + const server = createServer((_req, res) => res.writeHead(200, { 'content-type': 'text/plain' }).end(body)); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const target = { + baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, + adminToken: async () => 'jwt', + publishableKey: async () => undefined, + }; + const products = operation('GET /admin/products'); + const result = await executeOperation(target as never, products, declaredParameters(products), {}); + expect(result.truncated?.bytes).toBe(150_001); + const text = String(result.body); + expect(Buffer.byteLength(text)).toBeLessThanOrEqual(64 * 1024 + Buffer.byteLength('…')); + expect(text).not.toContain('\uFFFD'); + expect(text.endsWith('é…')).toBe(true); + } finally { + server.close(); + } + }); +}); + +describe('search', () => { + const index = buildSearchIndex(catalog.operations); + + it('tokenizes camelCase, paths, plurals, and verb forms', () => { + expect(tokenize('PostProductsId /admin/product-categories')).toEqual([ + 'post', + 'product', + 'id', + 'admin', + 'product', + 'category', + ]); + expect(tokenize('shipped shipping orders')).toEqual(['ship', 'ship', 'order']); + }); + + it('reads one method intent from the query verbs', () => { + expect(queryIntent('update a product')).toBe('POST'); + expect(queryIntent('list customers')).toBe('GET'); + expect(queryIntent('remove a tag')).toBe('DELETE'); + expect(queryIntent('list and delete')).toBeUndefined(); + }); + + it('returns the same ranking for the same query', () => { + const ranking = () => index.search('update product', {}, 10).map((result) => result.operation.operation); + expect(ranking()).toEqual(ranking()); + }); + + // Baseline measured on the pinned 2.22.1 spec: hit@1 11/15, hit@3 14/15. This guards against regressions. + it('finds the expected operation for common agent tasks', () => { + const cases: [string, string, { area?: 'admin' | 'store' }?][] = [ + ['update a product description', 'POST /admin/products/{id}'], + ['list products', 'GET /admin/products', { area: 'admin' }], + ['get a single order', 'GET /admin/orders/{id}'], + ['create a promotion', 'POST /admin/promotions'], + ['delete a product category', 'DELETE /admin/product-categories/{id}'], + ['add an item to the cart', 'POST /store/carts/{id}/line-items'], + ['list customers', 'GET /admin/customers'], + [ + 'set stock quantity for an inventory item at a location', + 'POST /admin/inventory-items/{id}/location-levels/{location_id}', + ], + ['refund a payment', 'POST /admin/payments/{id}/refund'], + ['cancel an order', 'POST /admin/orders/{id}/cancel'], + ['list regions', 'GET /store/regions', { area: 'store' }], + ['complete cart checkout', 'POST /store/carts/{id}/complete'], + ['change a product variant price', 'POST /admin/products/{id}/variants/{variant_id}'], + ['mark an order fulfillment as shipped', 'POST /admin/orders/{id}/fulfillments/{fulfillment_id}/shipments'], + ['find a product by handle in the storefront', 'GET /store/products', { area: 'store' }], + ]; + const ranks = cases.map(([query, expected, filters]) => ({ + query, + rank: index.search(query, filters ?? {}, 5).findIndex((result) => result.operation.operation === expected) + 1, + })); + const report = ranks.map(({ query, rank }) => `${rank || 'miss'}: ${query}`).join('\n'); + + const hitAt1 = ranks.filter(({ rank }) => rank === 1).length; + const hitAt3 = ranks.filter(({ rank }) => rank > 0 && rank <= 3).length; + if (hitAt1 < 11 || hitAt3 < 14) + throw new Error(`Search regressed: hit@1 ${hitAt1}/15, hit@3 ${hitAt3}/15\n${report}`); + expect(ranks.find(({ query }) => query === 'update a product description')?.rank).toBe(1); + }); +}); diff --git a/packages/medusa-mcp/src/mcp/__tests__/validate.unit.spec.ts b/packages/medusa-mcp/src/mcp/__tests__/validate.unit.spec.ts new file mode 100644 index 000000000..8be17c3fa --- /dev/null +++ b/packages/medusa-mcp/src/mcp/__tests__/validate.unit.spec.ts @@ -0,0 +1,70 @@ +import path from 'node:path'; +import { buildApiSpec } from '../../openapi/build-spec'; +import { buildCatalog } from '../catalog'; +import { createPolicy } from '../policy'; +import { RATE_LIMITS, takeRateLimit } from '../rate-limit'; +import { validateBody, withoutNulls } from '../validate'; + +const spec = buildApiSpec({ projectRoot: path.join(__dirname, '../../openapi/__tests__/fixtures/valid') }); +const catalog = buildCatalog(spec, createPolicy()); +const jsonBodySchema = (key: string) => { + const operation = catalog.byKey.get(key); + const content = (operation?.raw.requestBody as { content?: Record } | undefined) + ?.content; + return { operation, schema: content?.['application/json']?.schema }; +}; + +describe('validateBody', () => { + it('compiles the request schema of every JSON write operation in the spec', () => { + const failures = catalog.operations + .filter((operation) => operation.tool === 'write_api') + .flatMap((operation) => { + const { schema } = jsonBodySchema(operation.operation); + if (!schema) return []; + try { + validateBody(spec, operation.area, schema, {}); + return []; + } catch (error) { + return [`${operation.operation}: ${(error as Error).message}`]; + } + }); + expect(failures).toEqual([]); + }); + + const { schema } = jsonBodySchema('POST /admin/products/{id}'); + + it('accepts a valid product update, including null to clear a field', () => { + expect(validateBody(spec, 'admin', schema as object, { description: 'New copy' })).toEqual([]); + expect(validateBody(spec, 'admin', schema as object, { description: null, title: 'Decaf' })).toEqual([]); + }); + + it('reports type and shape problems with their location', () => { + expect(validateBody(spec, 'admin', schema as object, { description: 42 })).toContainEqual( + '/description must be string', + ); + expect(validateBody(spec, 'admin', schema as object, { status: 'not-a-status' }).join('\n')).toContain('/status'); + }); + + it('validates custom contract bodies too', () => { + const custom = jsonBodySchema('POST /admin/widgets').schema as object; + expect(validateBody(spec, 'admin', custom, { name: 'Widget' })).toEqual([]); + expect(validateBody(spec, 'admin', custom, {})).toEqual(["body must have required property 'name'"]); + }); + + it('drops nulls recursively before validation', () => { + expect(withoutNulls({ a: null, b: { c: null, d: 1 }, e: [{ f: null }] })).toEqual({ b: { d: 1 }, e: [{}] }); + }); +}); + +describe('takeRateLimit', () => { + it('allows calls up to the limit within a minute, then refuses, then recovers', () => { + const token = `token-${Math.random()}`; + const start = 1_000_000; + for (let index = 0; index < RATE_LIMITS.change; index++) { + expect(takeRateLimit(token, 'change', start + index)).toBeUndefined(); + } + expect(takeRateLimit(token, 'change', start + 100)).toMatch(/at most 30 writes and deletes per minute/); + expect(takeRateLimit(token, 'change', start + 61_000)).toBeUndefined(); + expect(takeRateLimit(`other-${token}`, 'change', start + 100)).toBeUndefined(); + }); +}); diff --git a/packages/medusa-mcp/src/mcp/catalog.ts b/packages/medusa-mcp/src/mcp/catalog.ts new file mode 100644 index 000000000..99c1e2311 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/catalog.ts @@ -0,0 +1,73 @@ +import type { ApiSpec } from '../openapi/build-spec'; +import { API_AREAS, type ApiArea, HTTP_METHODS, type HttpMethod, type OpenApiDocument } from '../openapi/types'; +import type { OperationPolicy } from './policy'; + +export type ExecutionTool = 'read_api' | 'write_api' | 'delete_api'; + +/** One callable operation from the published spec. */ +export interface CatalogOperation { + /** Canonical, unique key: `METHOD /path`. Medusa reuses operationIds across the admin and store documents. */ + operation: string; + operation_id: string; + area: ApiArea; + method: HttpMethod; + path: string; + summary: string; + description: string; + tags: string[]; + /** The MCP tool that executes it, or undefined for methods no tool runs (OPTIONS, HEAD). */ + tool?: ExecutionTool; + /** Set when the policy forbids this operation; the agent can still find and read about it. */ + blocked_by?: string; + source: 'core' | 'custom'; + raw: Record; +} + +export interface Catalog { + spec: ApiSpec; + operations: CatalogOperation[]; + byKey: Map; +} + +const OPERATION_KEYS = new Set(HTTP_METHODS.map((method) => method.toLowerCase())); + +export function toolFor(method: HttpMethod): ExecutionTool | undefined { + if (method === 'GET') return 'read_api'; + if (method === 'POST' || method === 'PUT' || method === 'PATCH') return 'write_api'; + if (method === 'DELETE') return 'delete_api'; + return undefined; +} + +function operationsOf(area: ApiArea, document: OpenApiDocument, policy: OperationPolicy): CatalogOperation[] { + return Object.entries(document.paths).flatMap(([path, item]) => + Object.entries(item) + .filter(([key]) => OPERATION_KEYS.has(key)) + .map(([key, value]): CatalogOperation => { + const raw = value as Record; + const method = key.toUpperCase() as HttpMethod; + return { + operation: `${method} ${path}`, + operation_id: String(raw.operationId), + area, + method, + path, + summary: String(raw.summary ?? ''), + description: String(raw.description ?? ''), + tags: (raw.tags as string[] | undefined) ?? [], + tool: toolFor(method), + blocked_by: policy.blockedBy(method, path), + source: raw['x-medusa-mcp-source'] === 'custom' ? 'custom' : 'core', + raw, + }; + }), + ); +} + +/** Builds the operation catalog. Routes both documents define, such as /auth, are listed once. */ +export function buildCatalog(spec: ApiSpec, policy: OperationPolicy): Catalog { + const byKey = new Map(); + for (const operation of API_AREAS.flatMap((area) => operationsOf(area, spec.documents[area], policy))) { + if (!byKey.has(operation.operation)) byKey.set(operation.operation, operation); + } + return { spec, operations: [...byKey.values()], byKey }; +} diff --git a/packages/medusa-mcp/src/mcp/describe.ts b/packages/medusa-mcp/src/mcp/describe.ts new file mode 100644 index 000000000..e33b769c2 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/describe.ts @@ -0,0 +1,155 @@ +import type { OpenApiDocument } from '../openapi/types'; +import type { CatalogOperation } from './catalog'; + +const DROPPED_KEYS = new Set(['example', 'examples', 'externalDocs', 'xml']); +const MAX_DESCRIPTION = 400; + +export interface DescribeLimits { + /** How many nested `$ref`s to inline before stopping. */ + maxRefDepth: number; + /** How many levels of properties, items, and oneOf/anyOf/allOf to expand before summarizing. */ + maxNesting: number; +} + +const NESTING_KEYS = new Set(['properties', 'items', 'oneOf', 'anyOf', 'allOf', 'additionalProperties', 'not']); + +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; + +function refTarget(document: OpenApiDocument, ref: string): Json | undefined { + if (!ref.startsWith('#/')) return undefined; + return ref + .slice(2) + .split('/') + .reduce( + (node, key) => (node && typeof node === 'object' && !Array.isArray(node) ? node[key] : undefined), + document as unknown as Json, + ); +} + +/** + * Copies a schema with `$ref`s inlined, stopping at cycles and at `maxRefDepth` (where the ref is kept as a name), + * and dropping examples and `x-` extensions so the result stays small enough for a model to read. + */ +export function inlineSchema( + document: OpenApiDocument, + node: Json, + limits: DescribeLimits, + seen: string[] = [], + nesting = 0, +): Json { + if (Array.isArray(node)) return node.map((item) => inlineSchema(document, item, limits, seen, nesting)); + if (!node || typeof node !== 'object') return node; + if (nesting > limits.maxNesting) { + const types = [ + node.type, + ...(['oneOf', 'anyOf'] as const).flatMap((key) => + Array.isArray(node[key]) ? (node[key] as Json[]).map((variant) => (variant as Record)?.type) : [], + ), + ].filter(Boolean); + return { ...(types.length ? { type: [...new Set(types)] as Json } : {}), note: 'nested schema not expanded' }; + } + + if (typeof node.$ref === 'string') { + const name = node.$ref.split('/').pop() ?? node.$ref; + if (seen.includes(node.$ref)) return { $ref: name, note: 'circular reference' }; + if (seen.length >= limits.maxRefDepth) + return { $ref: name, note: 'not expanded; describe a narrower field if needed' }; + const target = refTarget(document, node.$ref); + return target === undefined + ? { $ref: name } + : inlineSchema(document, target, limits, [...seen, node.$ref], nesting); + } + + const copy: Record = {}; + for (const [key, value] of Object.entries(node)) { + if (DROPPED_KEYS.has(key) || key.startsWith('x-')) continue; + copy[key] = + key === 'description' && typeof value === 'string' && value.length > MAX_DESCRIPTION + ? `${value.slice(0, MAX_DESCRIPTION)}…` + : inlineSchema(document, value, limits, seen, NESTING_KEYS.has(key) ? nesting + 1 : nesting); + } + return copy; +} + +interface Parameter { + name: string; + in: string; + required?: boolean; + description?: string; + schema?: Json; +} + +function parameters(document: OpenApiDocument, operation: CatalogOperation, limits: DescribeLimits) { + const pathItem = document.paths[operation.path] as { parameters?: Json[] }; + const raw = [...(pathItem.parameters ?? []), ...((operation.raw.parameters as Json[] | undefined) ?? [])]; + return raw + .map((parameter) => inlineSchema(document, parameter, limits) as unknown as Parameter) + .filter((parameter) => parameter.in === 'path' || parameter.in === 'query') + .map((parameter) => ({ + name: parameter.name, + in: parameter.in, + required: parameter.in === 'path' ? true : Boolean(parameter.required), + ...(parameter.description ? { description: parameter.description } : {}), + ...(parameter.schema ? { schema: parameter.schema } : {}), + })); +} + +function jsonContentSchema(document: OpenApiDocument, content: unknown, limits: DescribeLimits) { + const entries = Object.entries((content ?? {}) as Record); + const [contentType, media] = entries.find(([type]) => type.includes('json')) ?? entries[0] ?? []; + if (!contentType) return undefined; + return { + content_type: contentType, + schema: media?.schema ? inlineSchema(document, media.schema, limits) : undefined, + }; +} + +/** Everything an agent needs to call one operation, with schemas inlined and bounded. */ +export function describeOperation( + document: OpenApiDocument, + operation: CatalogOperation, + limits: { query: DescribeLimits; body: DescribeLimits; response: DescribeLimits } = { + query: { maxRefDepth: 2, maxNesting: 1 }, + body: { maxRefDepth: 4, maxNesting: 6 }, + response: { maxRefDepth: 1, maxNesting: 3 }, + }, +) { + const params = parameters(document, operation, limits.query); + const body = operation.raw.requestBody as { required?: boolean; content?: unknown } | undefined; + const responses = Object.fromEntries( + Object.entries( + (operation.raw.responses ?? {}) as Record, + ) + .filter(([status]) => status.startsWith('2')) + .map(([status, response]) => { + const resolved = (response.$ref ? refTarget(document, response.$ref) : response) as { + description?: string; + content?: unknown; + }; + return [ + status, + { description: resolved?.description, ...jsonContentSchema(document, resolved?.content, limits.response) }, + ]; + }), + ); + + return { + operation: operation.operation, + operation_id: operation.operation_id, + area: operation.area, + method: operation.method, + path: operation.path, + summary: operation.summary, + description: + operation.description.length > 1500 ? `${operation.description.slice(0, 1500)}…` : operation.description, + tags: operation.tags, + tool: operation.tool, + ...(operation.blocked_by ? { blocked_by: operation.blocked_by } : {}), + path_params: params.filter((parameter) => parameter.in === 'path'), + query_params: params.filter((parameter) => parameter.in === 'query'), + request_body: body + ? { required: Boolean(body.required), ...jsonContentSchema(document, body.content, limits.body) } + : null, + responses, + }; +} diff --git a/packages/medusa-mcp/src/mcp/execute.ts b/packages/medusa-mcp/src/mcp/execute.ts new file mode 100644 index 000000000..258293bba --- /dev/null +++ b/packages/medusa-mcp/src/mcp/execute.ts @@ -0,0 +1,162 @@ +import type { CatalogOperation } from './catalog'; + +const MAX_RESPONSE_BYTES = 64 * 1024; + +export interface AuditEntry { + operation: string; + path_params?: Record; + /** executed: sent to Medusa. failed: sending threw, so the change may or may not have happened. */ + outcome: 'executed' | 'failed' | 'dry_run' | 'rejected' | 'refused'; + status?: number; + problems?: string[]; + reason?: string; +} + +export interface ExecutionTarget { + /** The OAuth scopes the access token was granted. */ + scopes: readonly string[]; + /** The access token record id, for per-token rate limits. */ + tokenId: string; + /** Records a write or delete attempt with who made it and against which spec revision. */ + audit: (entry: AuditEntry) => Promise; + /** Origin of this Medusa server as seen from inside the process, for example http://127.0.0.1:9000. */ + baseUrl: string; + /** A short-lived Medusa admin JWT for the signed-in admin. Never the MCP client's own token. */ + adminToken: () => Promise; + /** A publishable API key for /store requests, if the store has one. */ + publishableKey: () => Promise; +} + +export interface ExecutionArgs { + path_params?: Record; + query?: Record; + body?: unknown; +} + +export interface ExecutionResult { + status: number; + body: unknown; + truncated?: { bytes: number; note: string }; +} + +export class ExecutionError extends Error {} + +/** Declared path and query parameter names for an operation, including path-level parameters. */ +export function declaredParameters( + operation: CatalogOperation, + pathItemParameters: unknown[] = [], +): { path: Set; query: Set } { + const all = [...pathItemParameters, ...((operation.raw.parameters as unknown[] | undefined) ?? [])] as { + name?: string; + in?: string; + }[]; + const pathNames = new Set([...operation.path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1])); + return { + path: pathNames, + query: new Set(all.filter((parameter) => parameter.in === 'query' && parameter.name).map((p) => p.name as string)), + }; +} + +/** Serializes query values the way Medusa's qs-based parser reads them: arrays as `key[]`, objects as `key[op]`. */ +export function appendQuery(params: URLSearchParams, key: string, value: unknown): void { + if (value === undefined || value === null) return; + if (Array.isArray(value)) { + for (const item of value) appendQuery(params, `${key}[]`, item); + return; + } + if (typeof value === 'object') { + for (const [child, childValue] of Object.entries(value)) appendQuery(params, `${key}[${child}]`, childValue); + return; + } + params.append(key, String(value)); +} + +/** Builds the request URL, refusing undeclared or missing parameters rather than guessing. */ +export function buildRequestUrl( + baseUrl: string, + operation: CatalogOperation, + declared: { path: Set; query: Set }, + args: ExecutionArgs, +): string { + const pathParams = args.path_params ?? {}; + const unknownPath = Object.keys(pathParams).filter((name) => !declared.path.has(name)); + if (unknownPath.length) throw new ExecutionError(`Unknown path parameter(s): ${unknownPath.join(', ')}`); + + const path = operation.path.replace(/\{([^}]+)\}/g, (_, name: string) => { + const value = pathParams[name]; + if (value === undefined || value === null || value === '') { + throw new ExecutionError(`Missing path parameter "${name}" for ${operation.operation}`); + } + // encodeURIComponent leaves dots alone, and URL resolution would turn ".." into a different, unchecked path. + if (value === '.' || value === '..') { + throw new ExecutionError(`Path parameter "${name}" cannot be "${value}"`); + } + return encodeURIComponent(String(value)); + }); + + const query = args.query ?? {}; + const unknownQuery = Object.keys(query).filter((name) => !declared.query.has(name)); + if (unknownQuery.length) { + throw new ExecutionError( + `Unknown query parameter(s) for ${operation.operation}: ${unknownQuery.join(', ')}. Use describe_api to see the declared ones.`, + ); + } + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) appendQuery(params, key, value); + + const url = new URL(path, baseUrl); + if (url.pathname !== path) { + throw new ExecutionError(`Refusing ${operation.operation}: the request path would resolve to ${url.pathname}`); + } + url.search = params.toString(); + return url.toString(); +} + +/** Calls the operation on this Medusa server as the signed-in admin and returns a size-bounded result. */ +export async function executeOperation( + target: ExecutionTarget, + operation: CatalogOperation, + declared: { path: Set; query: Set }, + args: ExecutionArgs, +): Promise { + const url = buildRequestUrl(target.baseUrl, operation, declared, args); + const headers: Record = { accept: 'application/json' }; + if (operation.area === 'admin') headers.authorization = `Bearer ${await target.adminToken()}`; + if (operation.area === 'store') { + const key = await target.publishableKey(); + if (key) headers['x-publishable-api-key'] = key; + } + const hasBody = args.body !== undefined && operation.method !== 'GET' && operation.method !== 'DELETE'; + if (hasBody) headers['content-type'] = 'application/json'; + + const response = await fetch(url, { + method: operation.method, + headers, + body: hasBody ? JSON.stringify(args.body) : undefined, + signal: AbortSignal.timeout(30_000), + }); + const bytes = Buffer.from(await response.arrayBuffer()); + const text = bytes.toString('utf8'); + if (bytes.length > MAX_RESPONSE_BYTES) { + // Cut by bytes, then drop a multi-byte character the cut split, which decodes as U+FFFD. + const prefix = bytes + .subarray(0, MAX_RESPONSE_BYTES) + .toString('utf8') + .replace(/\uFFFD+$/, ''); + return { + status: response.status, + body: `${prefix}…`, + truncated: { + bytes: bytes.length, + note: 'The response was cut off. Request fewer records with `limit`, or fewer fields with `fields`.', + }, + }; + } + let body: unknown = text; + try { + body = text ? JSON.parse(text) : null; + } catch { + // Not JSON; return the text as-is. + } + return { status: response.status, body }; +} diff --git a/packages/medusa-mcp/src/mcp/policy.ts b/packages/medusa-mcp/src/mcp/policy.ts new file mode 100644 index 000000000..36ff4eca8 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/policy.ts @@ -0,0 +1,54 @@ +import type { HttpMethod } from '../openapi/types'; + +/** + * Operations no agent may call, whatever the signed-in admin could do in the dashboard. They mint credentials, + * change identities, run arbitrary workflows, or open long-lived streams. Entries are `METHOD /path` or + * `* /prefix/**`, and match OpenAPI paths such as `/admin/users/{id}`. + */ +export const BUILT_IN_BLOCKLIST = [ + '* /auth/**', + '* /admin/api-keys', + '* /admin/api-keys/**', + '* /admin/invites', + '* /admin/invites/**', + 'POST /admin/users/{id}', + 'DELETE /admin/users/{id}', + 'POST /admin/users/{id}/reset-password', + '* /admin/workflows-executions/{workflow_id}/run', + '* /admin/workflows-executions/{workflow_id}/steps/**', + '* /admin/workflows-executions/{workflow_id}/subscribe', + '* /admin/workflows-executions/{workflow_id}/{transaction_id}/subscribe', +] as const; + +interface Rule { + entry: string; + method: HttpMethod | '*'; + path: string; + prefix: boolean; +} + +function parseRule(entry: string): Rule { + const match = /^(\*|GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD) (\/\S*)$/.exec(entry.trim()); + if (!match) throw new Error(`Invalid medusa-mcp blocked operation "${entry}". Use "METHOD /path" or "* /prefix/**".`); + const [, method, path] = match; + const prefix = path.endsWith('/**'); + return { entry, method: method as Rule['method'], path: prefix ? path.slice(0, -3) : path, prefix }; +} + +export interface OperationPolicy { + /** The blocklist entry that blocks this operation, if any. */ + blockedBy(method: HttpMethod, path: string): string | undefined; +} + +export function createPolicy(extraBlocked: readonly string[] = []): OperationPolicy { + const rules = [...BUILT_IN_BLOCKLIST, ...extraBlocked].map(parseRule); + return { + blockedBy(method, path) { + return rules.find( + (rule) => + (rule.method === '*' || rule.method === method) && + (rule.prefix ? path === rule.path || path.startsWith(`${rule.path}/`) : path === rule.path), + )?.entry; + }, + }; +} diff --git a/packages/medusa-mcp/src/mcp/rate-limit.ts b/packages/medusa-mcp/src/mcp/rate-limit.ts new file mode 100644 index 000000000..f5e22fe39 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/rate-limit.ts @@ -0,0 +1,19 @@ +const WINDOW_MS = 60_000; + +/** Per-token sliding-window limits on tool calls, kept in this process. */ +export const RATE_LIMITS = { call: 120, change: 30 } as const; + +const history = new Map(); + +/** Records a call and returns a message if it exceeds the limit for its kind, or undefined if it is allowed. */ +export function takeRateLimit(tokenId: string, kind: keyof typeof RATE_LIMITS, now = Date.now()): string | undefined { + const key = `${tokenId}:${kind}`; + const recent = (history.get(key) ?? []).filter((time) => now - time < WINDOW_MS); + if (recent.length >= RATE_LIMITS[kind]) { + history.set(key, recent); + return `Rate limit reached: at most ${RATE_LIMITS[kind]} ${kind === 'call' ? 'tool calls' : 'writes and deletes'} per minute. Try again shortly.`; + } + recent.push(now); + history.set(key, recent); + return undefined; +} diff --git a/packages/medusa-mcp/src/mcp/registry.ts b/packages/medusa-mcp/src/mcp/registry.ts new file mode 100644 index 000000000..ae9d3d2f1 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/registry.ts @@ -0,0 +1,31 @@ +import { buildApiSpec } from '../openapi/build-spec'; +import { buildCatalog, type Catalog } from './catalog'; +import { createPolicy } from './policy'; +import { buildSearchIndex, type SearchIndex } from './search'; + +export interface ApiRegistry { + catalog: Catalog; + search: SearchIndex; + builtAt: Date; +} + +let cached: { key: string; registry: ApiRegistry } | undefined; + +/** + * The published spec, operation catalog, and search index for this process. Built once on first use: route and + * contract changes restart `medusa develop`, so a new process always starts from the current routes. + */ +export function getApiRegistry(options: { + projectRoot: string; + plugins: string[]; + blockedOperations?: readonly string[]; +}): ApiRegistry { + const key = JSON.stringify([options.projectRoot, options.plugins, options.blockedOperations ?? []]); + if (cached?.key === key) return cached.registry; + + const spec = buildApiSpec({ projectRoot: options.projectRoot, plugins: options.plugins }); + const catalog = buildCatalog(spec, createPolicy(options.blockedOperations)); + const registry = { catalog, search: buildSearchIndex(catalog.operations), builtAt: new Date() }; + cached = { key, registry }; + return registry; +} diff --git a/packages/medusa-mcp/src/mcp/search.ts b/packages/medusa-mcp/src/mcp/search.ts new file mode 100644 index 000000000..c78f750e1 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/search.ts @@ -0,0 +1,175 @@ +import { compareCodeUnits } from '../openapi/compare'; +import type { CatalogOperation } from './catalog'; + +/** Field weights for ranking: what an operation is called counts more than its long description. */ +const FIELD_WEIGHTS = { summary: 3, operation_id: 2, path: 2, tags: 2, description: 1 } as const; +const K1 = 1.2; +const B = 0.75; +const STOP_WORDS = new Set([ + 'a', + 'an', + 'the', + 'of', + 'to', + 'for', + 'in', + 'on', + 'and', + 'or', + 'by', + 'with', + 'my', + 'me', + 'i', +]); + +/** Verbs that say which HTTP method the user wants. Matching operations rank higher. */ +const INTENT_VERBS: Record = { + list: 'GET', + get: 'GET', + show: 'GET', + find: 'GET', + read: 'GET', + fetch: 'GET', + retrieve: 'GET', + view: 'GET', + look: 'GET', + create: 'POST', + add: 'POST', + update: 'POST', + edit: 'POST', + change: 'POST', + set: 'POST', + modify: 'POST', + rename: 'POST', + delete: 'DELETE', + remove: 'DELETE', +}; +const INTENT_BOOST = 1.5; +const PARTIAL_MATCH_WEIGHT = 0.5; +const MIN_PARTIAL_LENGTH = 4; + +function stem(token: string): string { + let stemmed = token; + if (stemmed.length > 3 && stemmed.endsWith('ies')) stemmed = `${stemmed.slice(0, -3)}y`; + else if (stemmed.length > 3 && stemmed.endsWith('s') && !stemmed.endsWith('ss')) stemmed = stemmed.slice(0, -1); + if (stemmed.length > 5 && stemmed.endsWith('ing')) stemmed = stemmed.slice(0, -3); + else if (stemmed.length > 4 && stemmed.endsWith('ed')) stemmed = stemmed.slice(0, -2); + // "shipp" from "shipped" -> "ship" + if (stemmed.length > 3 && stemmed.at(-1) === stemmed.at(-2) && !/[aeiouls]/.test(stemmed.at(-1) ?? '')) { + stemmed = stemmed.slice(0, -1); + } + return stemmed; +} + +/** Lowercase word tokens, splitting camelCase and path punctuation, with light stemming. */ +export function tokenize(text: string): string[] { + return text + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((token) => token && !STOP_WORDS.has(token)) + .map(stem); +} + +/** The single HTTP method the query's verbs point to, if they agree on one. */ +export function queryIntent(query: string): string | undefined { + const methods = new Set( + query + .toLowerCase() + .split(/[^a-z]+/) + .map((word) => INTENT_VERBS[word]) + .filter(Boolean), + ); + return methods.size === 1 ? [...methods][0] : undefined; +} + +function weightedTerms(operation: CatalogOperation): Map { + const terms = new Map(); + const add = (text: string, weight: number) => { + for (const token of tokenize(text)) terms.set(token, (terms.get(token) ?? 0) + weight); + }; + add(operation.summary, FIELD_WEIGHTS.summary); + add(operation.operation_id, FIELD_WEIGHTS.operation_id); + add(operation.path.replace(/\{[^}]+\}/g, ' '), FIELD_WEIGHTS.path); + add(operation.tags.join(' '), FIELD_WEIGHTS.tags); + add(operation.description.slice(0, 600), FIELD_WEIGHTS.description); + return terms; +} + +export interface SearchFilters { + area?: 'admin' | 'store'; + method?: string; + tag?: string; +} + +export interface SearchIndex { + search(query: string, filters?: SearchFilters, limit?: number): { operation: CatalogOperation; score: number }[]; +} + +/** BM25 over each operation's weighted summary, id, path, tags, and description. Deterministic for equal input. */ +export function buildSearchIndex(operations: CatalogOperation[]): SearchIndex { + const documents = operations.map((operation) => { + const terms = weightedTerms(operation); + return { operation, terms, length: [...terms.values()].reduce((sum, weight) => sum + weight, 0) }; + }); + const averageLength = documents.reduce((sum, doc) => sum + doc.length, 0) / Math.max(documents.length, 1); + const documentFrequency = new Map(); + for (const doc of documents) { + for (const term of doc.terms.keys()) documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1); + } + const idf = (term: string) => { + const frequency = documentFrequency.get(term) ?? 0; + return Math.log(1 + (documents.length - frequency + 0.5) / (frequency + 0.5)); + }; + + const vocabulary = [...documentFrequency.keys()]; + /** Index terms that share a prefix with a query term (shipment for ship, store for storefront), at half weight. */ + const partials = (term: string) => + term.length < MIN_PARTIAL_LENGTH + ? [] + : vocabulary.filter( + (candidate) => + candidate !== term && + candidate.length >= MIN_PARTIAL_LENGTH && + (candidate.startsWith(term) || term.startsWith(candidate)), + ); + + return { + search(query, filters = {}, limit = 5) { + const terms = [...new Set(tokenize(query))].map((term) => ({ term, partials: partials(term) })); + const intent = queryIntent(query); + const bm25 = (doc: (typeof documents)[number], term: string, weight: number) => { + const frequency = doc.terms.get(term) ?? 0; + if (!frequency) return 0; + return ( + (weight * idf(term) * frequency * (K1 + 1)) / (frequency + K1 * (1 - B + (B * doc.length) / averageLength)) + ); + }; + const method = filters.method?.toUpperCase(); + const tag = filters.tag?.toLowerCase(); + return documents + .filter(({ operation }) => !filters.area || operation.area === filters.area) + .filter(({ operation }) => !method || operation.method === method) + .filter(({ operation }) => !tag || operation.tags.some((candidate) => candidate.toLowerCase() === tag)) + .map((doc) => { + const relevance = terms.reduce( + (score, { term, partials: related }) => + score + + Math.max(bm25(doc, term, 1), ...related.map((candidate) => bm25(doc, candidate, PARTIAL_MATCH_WEIGHT))), + 0, + ); + return { + operation: doc.operation, + score: intent === doc.operation.method ? relevance * INTENT_BOOST : relevance, + }; + }) + .filter((result) => result.score > 0) + .sort( + (left, right) => + right.score - left.score || compareCodeUnits(left.operation.operation_id, right.operation.operation_id), + ) + .slice(0, limit); + }, + }; +} diff --git a/packages/medusa-mcp/src/mcp/server.ts b/packages/medusa-mcp/src/mcp/server.ts new file mode 100644 index 000000000..c405d516a --- /dev/null +++ b/packages/medusa-mcp/src/mcp/server.ts @@ -0,0 +1,356 @@ +import { fromJsonSchema, McpServer, requireScopes } from '@modelcontextprotocol/server'; +import type { CatalogOperation, ExecutionTool } from './catalog'; +import { describeOperation } from './describe'; +import { + declaredParameters, + type ExecutionArgs, + ExecutionError, + type ExecutionResult, + type ExecutionTarget, + executeOperation, +} from './execute'; +import { takeRateLimit } from './rate-limit'; +import type { ApiRegistry } from './registry'; +import { validateBody } from './validate'; + +const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }; +const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }; +const DELETE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }; + +type ToolResult = { + content: { type: 'text'; text: string }[]; + structuredContent?: Record; + isError?: boolean; +}; + +function ok(data: Record): ToolResult { + return { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data }; +} + +function fail(message: string): ToolResult { + return { content: [{ type: 'text', text: message }], isError: true }; +} + +function oauth(scope: 'mcp:read' | 'mcp:write' | 'mcp:delete') { + return { scopeChallenge: requireScopes(scope), _meta: { securitySchemes: [{ type: 'oauth2', scopes: [scope] }] } }; +} + +const operationInput = { + operation: { + type: 'string', + description: 'The operation key from search_api, for example "GET /admin/products/{id}".', + }, +} as const; + +const pathParamsInput = { + type: 'object', + description: 'Values for the {placeholders} in the operation path, for example { "id": "prod_123" }.', + additionalProperties: { type: ['string', 'number'] }, +} as const; + +const queryInput = { type: 'object', description: 'Declared query parameters, for example { "limit": 5 }.' } as const; + +type ToolArgs = ExecutionArgs & { operation: string; dry_run?: boolean }; + +/** One MCP server per request, scoped to the signed-in admin's registry and execution target. */ +export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget): McpServer { + const { catalog, search } = registry; + const server = new McpServer( + { name: 'medusa-mcp', version: '0.1.0' }, + { + instructions: + 'Medusa commerce API. Find an operation with search_api, read its parameters and body with describe_api, then call it with read_api (GET), write_api (POST/PUT/PATCH), or delete_api (DELETE). Every call runs as the signed-in Medusa admin. Use write_api with dry_run first to show the user what will change.', + }, + ); + + const lookup = (key: unknown): CatalogOperation | ToolResult => { + const operation = typeof key === 'string' ? catalog.byKey.get(key.trim()) : undefined; + return ( + operation ?? fail(`Unknown operation "${String(key)}". Use search_api to find the exact "METHOD /path" key.`) + ); + }; + + const limited = (kind: 'call' | 'change') => { + const message = takeRateLimit(target.tokenId, kind); + return message ? fail(message) : undefined; + }; + + const declaredFor = (operation: CatalogOperation) => { + const pathItem = catalog.spec.documents[operation.area].paths[operation.path] as { parameters?: unknown[] }; + return declaredParameters(operation, pathItem.parameters); + }; + + const run = async (operation: CatalogOperation, args: ExecutionArgs): Promise => { + try { + return await executeOperation(target, operation, declaredFor(operation), args); + } catch (error) { + if (error instanceof ExecutionError) return fail(error.message); + throw error; + } + }; + + /** Shared checks for read_api, write_api, and delete_api: limits, the right tool, and the policy. */ + const resolveFor = (tool: ExecutionTool, args: ToolArgs): CatalogOperation | ToolResult => { + const overLimit = limited('call') ?? (tool === 'read_api' ? undefined : limited('change')); + if (overLimit) return overLimit; + const operation = lookup(args.operation); + if ('content' in operation) return operation; + if (operation.blocked_by) { + return fail(`${operation.operation} is blocked for agents by the "${operation.blocked_by}" rule.`); + } + if (operation.tool !== tool) { + return fail(`${operation.operation} is not handled by ${tool}. Use ${operation.tool ?? 'another tool'} instead.`); + } + return operation; + }; + + const resultOf = (operation: CatalogOperation, result: ExecutionResult | ToolResult): ToolResult => + 'content' in result + ? result + : { ...ok({ operation: operation.operation, ...result }), isError: result.status >= 400 }; + + server.registerTool( + 'search_api', + { + title: 'Search the Medusa API', + description: + "Search this store's Admin and Store API operations by what you want to do. Returns the best matches with the operation key to pass to describe_api and the execution tools.", + inputSchema: fromJsonSchema({ + type: 'object', + properties: { + query: { type: 'string', description: 'What you want to do, for example "update a product description".' }, + area: { type: 'string', enum: ['admin', 'store'], description: 'Limit results to the Admin or Store API.' }, + method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }, + tag: { type: 'string', description: 'Limit results to one OpenAPI tag, for example "Products".' }, + limit: { type: 'integer', minimum: 1, maximum: 10, default: 5 }, + }, + required: ['query'], + additionalProperties: false, + }), + annotations: READ_ONLY, + ...oauth('mcp:read'), + }, + async (input) => { + const overLimit = limited('call'); + if (overLimit) return overLimit; + const args = input as { query: string; area?: 'admin' | 'store'; method?: string; tag?: string; limit?: number }; + const results = search.search(args.query, args, args.limit ?? 5).map(({ operation, score }) => ({ + operation: operation.operation, + operation_id: operation.operation_id, + summary: operation.summary, + area: operation.area, + tool: operation.tool, + ...(operation.blocked_by ? { blocked: true } : {}), + score: Math.round(score * 100) / 100, + })); + return ok({ + results, + index: { + revision: catalog.spec.revision.slice(0, 12), + medusa_version: catalog.spec.medusaVersion, + operations: catalog.operations.length, + undocumented_operations: catalog.spec.gaps.length, + }, + }); + }, + ); + + server.registerTool( + 'describe_api', + { + title: 'Describe a Medusa API operation', + description: + 'Show one operation in full: path and query parameters, request body schema, and response shape. Call this before executing an operation.', + inputSchema: fromJsonSchema({ + type: 'object', + properties: operationInput, + required: ['operation'], + additionalProperties: false, + }), + annotations: READ_ONLY, + ...oauth('mcp:read'), + }, + async (input) => { + const overLimit = limited('call'); + if (overLimit) return overLimit; + const operation = lookup((input as { operation: string }).operation); + if ('content' in operation) return operation; + return ok(describeOperation(catalog.spec.documents[operation.area], operation)); + }, + ); + + server.registerTool( + 'read_api', + { + title: 'Read from the Medusa API', + description: + 'Call a GET operation as the signed-in admin. Pass path_params for {placeholders} and query for declared query parameters. Use `fields` and `limit` to keep responses small.', + inputSchema: fromJsonSchema({ + type: 'object', + properties: { ...operationInput, path_params: pathParamsInput, query: queryInput }, + required: ['operation'], + additionalProperties: false, + }), + annotations: READ_ONLY, + ...oauth('mcp:read'), + }, + async (input) => { + const args = input as ToolArgs; + const operation = resolveFor('read_api', args); + if ('content' in operation) return operation; + return resultOf(operation, await run(operation, args)); + }, + ); + + server.registerTool( + 'write_api', + { + title: 'Write to the Medusa API', + description: + 'Call a POST, PUT, or PATCH operation as the signed-in admin with a JSON body matching describe_api. Set dry_run to true to see the current and proposed values without changing anything.', + inputSchema: fromJsonSchema({ + type: 'object', + properties: { + ...operationInput, + path_params: pathParamsInput, + query: queryInput, + body: { type: 'object', description: 'The JSON request body.' }, + dry_run: { + type: 'boolean', + description: 'Validate and preview the change without making it.', + default: false, + }, + }, + required: ['operation'], + additionalProperties: false, + }), + annotations: WRITE, + ...oauth('mcp:write'), + }, + async (input) => { + const args = input as ToolArgs; + const operation = resolveFor('write_api', args); + if ('content' in operation) return refused(args, operation); + + const requestBody = operation.raw.requestBody as { content?: Record } | undefined; + const contentTypes = Object.keys(requestBody?.content ?? {}); + if (contentTypes.length && !contentTypes.some((type) => type.includes('json'))) { + return refused( + args, + fail(`${operation.operation} takes ${contentTypes.join(' or ')}, which write_api cannot send.`), + ); + } + const schema = requestBody?.content?.['application/json']?.schema; + if (schema && args.body !== undefined) { + const problems = validateBody(catalog.spec, operation.area, schema, args.body); + if (problems.length) { + await target.audit({ ...auditBase(args), outcome: 'rejected', problems }); + return fail(`The body does not match ${operation.operation}:\n- ${problems.join('\n- ')}`); + } + } + + return audited(args, async () => { + if (args.dry_run) { + const preview = await dryRun(operation, args); + await target.audit({ ...auditBase(args), outcome: 'dry_run' }); + return preview; + } + return executeAudited(operation, args); + }); + }, + ); + + server.registerTool( + 'delete_api', + { + title: 'Delete through the Medusa API', + description: + 'Call a DELETE operation as the signed-in admin. This removes data; confirm with the user before calling it.', + inputSchema: fromJsonSchema({ + type: 'object', + properties: { ...operationInput, path_params: pathParamsInput, query: queryInput }, + required: ['operation'], + additionalProperties: false, + }), + annotations: DELETE, + ...oauth('mcp:delete'), + }, + async (input) => { + const args = input as ToolArgs; + const operation = resolveFor('delete_api', args); + if ('content' in operation) return refused(args, operation); + return audited(args, () => executeAudited(operation, args)); + }, + ); + + function auditBase(args: ToolArgs) { + return { operation: String(args.operation), ...(args.path_params ? { path_params: args.path_params } : {}) }; + } + + /** Logs a refused write or delete attempt, with the reason the agent was given, and returns the refusal. */ + async function refused(args: ToolArgs, result: ToolResult): Promise { + await target.audit({ ...auditBase(args), outcome: 'refused', reason: result.content[0]?.text }); + return result; + } + + /** Logs an attempt that threw before it finished. The request may have reached Medusa, so it must be recorded. */ + async function audited(args: ToolArgs, attempt: () => Promise): Promise { + try { + return await attempt(); + } catch (error) { + await target.audit({ ...auditBase(args), outcome: 'failed', reason: (error as Error).message }); + throw error; + } + } + + async function executeAudited(operation: CatalogOperation, args: ToolArgs): Promise { + const result = await run(operation, args); + if ('content' in result) return refused(args, result); + await target.audit({ ...auditBase(args), outcome: 'executed', status: result.status }); + return resultOf(operation, result); + } + + /** + * Shows the current value of each top-level body field next to the proposed one, by reading the same path with + * GET when that operation exists. Nothing is written. Without mcp:read the current values stay hidden, since a + * dry run must not become a way to read data the token cannot read. + */ + async function dryRun(operation: CatalogOperation, args: ToolArgs): Promise { + const fields = Object.keys((args.body as Record | undefined) ?? {}); + const read = catalog.byKey.get(`GET ${operation.path}`); + if (!target.scopes.includes('mcp:read')) { + return ok({ + operation: operation.operation, + dry_run: true, + proposed: args.body ?? null, + current: null, + note: 'Current values need the mcp:read scope.', + }); + } + if (!read || read.blocked_by) { + return ok({ operation: operation.operation, dry_run: true, proposed: args.body ?? null, current: null }); + } + + const query = declaredFor(read).query.has('fields') && fields.length ? { fields: fields.join(',') } : undefined; + const current = await run(read, { path_params: args.path_params, query }); + if ('content' in current) return current; + if (current.status >= 400) { + return { + ...ok({ operation: operation.operation, dry_run: true, current_status: current.status, current: current.body }), + isError: true, + }; + } + + const resource = Object.values((current.body as Record) ?? {}).find( + (value) => value && typeof value === 'object' && !Array.isArray(value), + ) as Record | undefined; + const changes = fields.map((field) => ({ + field, + current: resource?.[field] ?? null, + proposed: (args.body as Record)[field], + })); + return ok({ operation: operation.operation, dry_run: true, changes }); + } + + return server; +} diff --git a/packages/medusa-mcp/src/mcp/validate.ts b/packages/medusa-mcp/src/mcp/validate.ts new file mode 100644 index 000000000..2de66f096 --- /dev/null +++ b/packages/medusa-mcp/src/mcp/validate.ts @@ -0,0 +1,61 @@ +import Ajv, { type ValidateFunction } from 'ajv'; +import addFormats from 'ajv-formats'; +import type { ApiSpec } from '../openapi/build-spec'; +import type { ApiArea } from '../openapi/types'; + +const instances = new Map(); + +function documentId(spec: ApiSpec, area: ApiArea): string { + return `${spec.revision}:${area}`; +} + +function ajvFor(spec: ApiSpec, area: ApiArea): Ajv { + const id = documentId(spec, area); + let ajv = instances.get(id); + if (!ajv) { + ajv = new Ajv({ strict: false, allErrors: true, allowUnionTypes: true }); + addFormats(ajv); + ajv.addSchema({ components: spec.documents[area].components ?? {} }, id); + instances.set(id, ajv); + } + return ajv; +} + +/** Points the schema's local `#/components/...` refs at the registered document so they resolve. */ +function anchorRefs(node: unknown, id: string): unknown { + if (Array.isArray(node)) return node.map((item) => anchorRefs(item, id)); + if (!node || typeof node !== 'object') return node; + return Object.fromEntries( + Object.entries(node).map(([key, value]) => [ + key, + key === '$ref' && typeof value === 'string' && value.startsWith('#/') ? `${id}${value}` : anchorRefs(value, id), + ]), + ); +} + +/** + * Medusa's published spec never marks fields nullable, but its validators accept null for many optional fields, + * such as clearing a description. Null values are dropped before validation and left for Medusa to judge. + */ +export function withoutNulls(value: unknown): unknown { + if (Array.isArray(value)) return value.map(withoutNulls); + if (!value || typeof value !== 'object') return value; + return Object.fromEntries( + Object.entries(value) + .filter(([, child]) => child !== null) + .map(([key, child]) => [key, withoutNulls(child)]), + ); +} + +const compiled = new WeakMap(); + +/** Validates a request body against the operation's JSON request schema; returns readable problems, or none. */ +export function validateBody(spec: ApiSpec, area: ApiArea, schema: object, body: unknown): string[] { + let validate = compiled.get(schema); + if (!validate) { + validate = ajvFor(spec, area).compile(anchorRefs(schema, documentId(spec, area)) as object); + compiled.set(schema, validate); + } + if (validate(withoutNulls(body))) return []; + return (validate.errors ?? []).slice(0, 8).map((error) => `${error.instancePath || 'body'} ${error.message}`); +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/crypto.unit.spec.ts b/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/crypto.unit.spec.ts new file mode 100644 index 000000000..bccdf7a65 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/crypto.unit.spec.ts @@ -0,0 +1,64 @@ +import { isValidCodeVerifier, signPayload, verifyPayload, verifyPkceS256 } from '../crypto'; +import { parseScopes } from '../service'; + +describe('PKCE S256', () => { + // RFC 7636 Appendix B. + const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'; + const challenge = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'; + + it('matches the RFC 7636 test vector and nothing else', () => { + expect(verifyPkceS256(verifier, challenge)).toBe(true); + expect(verifyPkceS256(`${verifier}x`, challenge)).toBe(false); + expect(verifyPkceS256(verifier, challenge.slice(1))).toBe(false); + }); + + it('accepts only 43 to 128 unreserved characters as a verifier', () => { + expect(isValidCodeVerifier(verifier)).toBe(true); + expect(isValidCodeVerifier('a'.repeat(42))).toBe(false); + expect(isValidCodeVerifier('a'.repeat(129))).toBe(false); + expect(isValidCodeVerifier(`${'a'.repeat(43)}/`)).toBe(false); + expect(isValidCodeVerifier(undefined)).toBe(false); + }); +}); + +describe('signed form payloads', () => { + const secret = 'test-secret'; + + it('round-trips a payload', () => { + expect(verifyPayload('consent', signPayload('consent', { user_id: 'user_1' }, secret, 60), secret)).toMatchObject({ + user_id: 'user_1', + }); + }); + + it('refuses a token signed for a different form', () => { + const login = signPayload('login', { request: {} }, secret, 60); + expect(verifyPayload('login', login, secret)).toBeDefined(); + expect(verifyPayload('consent', login, secret)).toBeUndefined(); + }); + + it('rejects a changed payload, a different secret, and an expired token', () => { + const token = signPayload('consent', { user_id: 'user_1' }, secret, 60); + const [body, signature] = token.split('.'); + const changed = Buffer.from(Buffer.from(body, 'base64url').toString().replace('user_1', 'user_2')).toString( + 'base64url', + ); + expect(verifyPayload('consent', `${changed}.${signature}`, secret)).toBeUndefined(); + expect(verifyPayload('consent', token, 'other-secret')).toBeUndefined(); + expect(verifyPayload('consent', signPayload('consent', { user_id: 'user_1' }, secret, -1), secret)).toBeUndefined(); + expect(verifyPayload('consent', 'not.a.token', secret)).toBeUndefined(); + expect(verifyPayload('consent', undefined, secret)).toBeUndefined(); + }); +}); + +describe('parseScopes', () => { + it('grants every scope when none is requested and orders known scopes', () => { + expect(parseScopes(undefined)).toEqual(['mcp:read', 'mcp:write', 'mcp:delete']); + expect(parseScopes('')).toEqual(['mcp:read', 'mcp:write', 'mcp:delete']); + expect(parseScopes('mcp:delete mcp:read mcp:read')).toEqual(['mcp:read', 'mcp:delete']); + }); + + it('rejects unknown scopes', () => { + expect(parseScopes('mcp:read openid')).toBeUndefined(); + expect(parseScopes(['mcp:read'])).toBeUndefined(); + }); +}); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/oauth-rules.unit.spec.ts b/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/oauth-rules.unit.spec.ts new file mode 100644 index 000000000..c04630cec --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/__tests__/oauth-rules.unit.spec.ts @@ -0,0 +1,141 @@ +import { + cimdClientIdProblem, + fetchPublicJson, + isPublicAddress, + publicOnlyLookup, + validateClientMetadataDocument, +} from '../cimd'; +import { resolveOAuthConfig } from '../config'; +import { redirectUriProblem, redirectUrisProblems } from '../redirect-uri'; + +describe('redirect URIs', () => { + it.each([ + 'https://chatgpt.com/connector_platform_oauth_redirect', + 'http://localhost:6274/oauth/callback', + 'http://127.0.0.1:33418/callback', + 'http://[::1]/cb', + ])('accepts %s', (uri) => { + expect(redirectUriProblem(uri)).toBeUndefined(); + }); + + it.each([ + ['http://evil.example/cb', /must use https, or http to localhost/], + ['https://a.example/cb#frag', /must not contain a fragment/], + ['https://user:pass@a.example/cb', /must not contain credentials/], + ['javascript:alert(1)', /must use https/], + ['/relative', /not an absolute URL/], + ['', /non-empty string/], + ])('rejects %s', (uri, problem) => { + expect(redirectUriProblem(uri)).toMatch(problem); + }); + + it('requires a non-empty list of at most ten', () => { + expect(redirectUrisProblems([])).toEqual(['redirect_uris must be a non-empty array']); + expect(redirectUrisProblems('https://a.example/cb')).toEqual(['redirect_uris must be a non-empty array']); + expect(redirectUrisProblems(Array(11).fill('https://a.example/cb'))).toEqual([ + 'redirect_uris may list at most 10 URIs', + ]); + }); +}); + +describe('Client ID Metadata Document fetch guard', () => { + it.each(['8.8.8.8', '104.18.32.47', '2606:4700::6810:84e5'])('treats %s as public', (address) => { + expect(isPublicAddress(address)).toBe(true); + }); + + it.each([ + '127.0.0.1', + '10.1.2.3', + '172.16.0.1', + '192.168.1.1', + '169.254.169.254', + '100.64.0.1', + '0.0.0.0', + '::1', + '::ffff:127.0.0.1', + 'fd00::1', + 'fe80::1', + 'not-an-ip', + ])('blocks %s', (address) => { + expect(isPublicAddress(address)).toBe(false); + }); + + it('refuses to connect when the hostname resolves to a loopback address', (done) => { + publicOnlyLookup('localhost', {}, (error) => { + expect(error).toMatchObject({ code: 'EBLOCKED' }); + done(); + }); + }); + + it('accepts only https client_id URLs with a path', () => { + expect(cimdClientIdProblem('https://chatgpt.com/oauth/client.json')).toBeUndefined(); + expect(cimdClientIdProblem('http://chatgpt.com/oauth/client.json')).toMatch(/must use https/); + expect(cimdClientIdProblem('https://chatgpt.com/')).toMatch(/must have a path/); + expect(cimdClientIdProblem('https://chatgpt.com/client.json#x')).toMatch(/credentials or a fragment/); + }); + + // Node connects to an IP literal without calling the lookup hook, so these must be refused up front. + it.each([ + 'https://10.0.0.5/client.json', + 'https://127.0.0.1/x.json', + 'https://[::1]/x.json', + 'https://8.8.8.8/c.json', + ])('refuses the IP-literal client_id %s', async (clientId) => { + expect(cimdClientIdProblem(clientId)).toMatch(/domain name, not an IP address/); + await expect(fetchPublicJson(clientId)).rejects.toThrow(/IP-literal hosts/); + }); +}); + +describe('validateClientMetadataDocument', () => { + const clientId = 'https://chatgpt.com/oauth/client.json'; + const valid = { + client_id: clientId, + client_name: 'ChatGPT', + redirect_uris: ['https://chatgpt.com/connector_platform_oauth_redirect'], + token_endpoint_auth_methods_supported: ['none', 'private_key_jwt'], + }; + + it('accepts a document that matches its URL and supports public-client auth', () => { + expect(validateClientMetadataDocument(clientId, valid)).toEqual(valid); + const { token_endpoint_auth_methods_supported: _, ...withoutMethods } = valid; + expect(validateClientMetadataDocument(clientId, withoutMethods)).toEqual(withoutMethods); + }); + + it('rejects a document whose client_id does not match the URL it came from', () => { + expect(() => + validateClientMetadataDocument(clientId, { ...valid, client_id: 'https://evil.example/c.json' }), + ).toThrow(/does not match the URL/); + }); + + it('rejects documents without a name, with bad redirect URIs, or without "none" auth', () => { + expect(() => validateClientMetadataDocument(clientId, { ...valid, client_name: '' })).toThrow(/client_name/); + expect(() => + validateClientMetadataDocument(clientId, { ...valid, redirect_uris: ['http://evil.example'] }), + ).toThrow(/must use https/); + expect(() => + validateClientMetadataDocument(clientId, { + ...valid, + token_endpoint_auth_methods_supported: ['private_key_jwt'], + }), + ).toThrow(/"none"/); + expect(() => validateClientMetadataDocument(clientId, 'not json')).toThrow(/does not match/); + }); +}); + +describe('resolveOAuthConfig', () => { + it('defaults to localhost and derives the MCP resource from the issuer', () => { + expect(resolveOAuthConfig({})).toMatchObject({ + issuer: 'http://localhost:9000', + resource: 'http://localhost:9000/mcp', + }); + expect(resolveOAuthConfig({ issuer: '' }).issuer).toBe('http://localhost:9000'); + expect(resolveOAuthConfig({ issuer: 'https://barrio-demo.example.com/' }).resource).toBe( + 'https://barrio-demo.example.com/mcp', + ); + }); + + it('requires https outside localhost and an origin with no path', () => { + expect(() => resolveOAuthConfig({ issuer: 'http://barrio.example.com' })).toThrow(/https outside localhost/); + expect(() => resolveOAuthConfig({ issuer: 'https://barrio.example.com/medusa' })).toThrow(/no path/); + }); +}); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/cimd.ts b/packages/medusa-mcp/src/modules/mcp_oauth/cimd.ts new file mode 100644 index 000000000..973b29da9 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/cimd.ts @@ -0,0 +1,150 @@ +import { lookup as dnsLookup, type LookupAddress } from 'node:dns'; +import { request } from 'node:https'; +import { BlockList, isIP } from 'node:net'; +import { redirectUrisProblems } from './redirect-uri'; + +const MAX_DOCUMENT_BYTES = 64 * 1024; +const FETCH_TIMEOUT_MS = 5000; + +/** Addresses a Client ID Metadata Document fetch must never connect to. BlockList also checks IPv4-mapped IPv6 + * addresses such as ::ffff:127.0.0.1 against the IPv4 subnets, so they need no rule of their own. */ +const BLOCKED_ADDRESSES = new BlockList(); +for (const [network, prefix] of [ + ['0.0.0.0', 8], + ['10.0.0.0', 8], + ['100.64.0.0', 10], + ['127.0.0.0', 8], + ['169.254.0.0', 16], + ['172.16.0.0', 12], + ['192.0.0.0', 24], + ['192.168.0.0', 16], + ['198.18.0.0', 15], + ['224.0.0.0', 4], + ['240.0.0.0', 4], +] as const) { + BLOCKED_ADDRESSES.addSubnet(network, prefix, 'ipv4'); +} +for (const [network, prefix] of [ + ['::', 128], + ['::1', 128], + ['64:ff9b::', 96], + ['fc00::', 7], + ['fe80::', 10], + ['ff00::', 8], +] as const) { + BLOCKED_ADDRESSES.addSubnet(network, prefix, 'ipv6'); +} + +export function isPublicAddress(address: string): boolean { + const family = isIP(address); + if (!family) return false; + return !BLOCKED_ADDRESSES.check(address, family === 4 ? 'ipv4' : 'ipv6'); +} + +export interface ClientMetadataDocument { + client_id: string; + client_name: string; + redirect_uris: string[]; + [key: string]: unknown; +} + +/** Why a URL cannot be a CIMD client_id, or undefined when it can. */ +export function cimdClientIdProblem(clientId: string): string | undefined { + let url: URL; + try { + url = new URL(clientId); + } catch { + return 'client_id is not a URL'; + } + if (url.protocol !== 'https:') return 'a URL client_id must use https'; + if (url.pathname === '/' || !url.pathname) return 'a URL client_id must have a path'; + if (url.username || url.password || url.hash) return 'a URL client_id must not contain credentials or a fragment'; + // Node connects to an IP literal without calling the lookup hook, so publicOnlyLookup cannot guard it. + if (isIP(url.hostname.replace(/^\[|\]$/g, ''))) return 'a URL client_id must use a domain name, not an IP address'; + return undefined; +} + +/** Validates a fetched document against the client_id it was fetched from. */ +export function validateClientMetadataDocument(clientId: string, document: unknown): ClientMetadataDocument { + const problems: string[] = []; + const doc = (document && typeof document === 'object' ? document : {}) as Record; + + if (doc.client_id !== clientId) problems.push('client_id in the document does not match the URL it was fetched from'); + if (typeof doc.client_name !== 'string' || !doc.client_name) problems.push('client_name is required'); + problems.push(...redirectUrisProblems(doc.redirect_uris)); + + const plural = doc.token_endpoint_auth_methods_supported; + const singular = doc.token_endpoint_auth_method; + const methods = Array.isArray(plural) ? plural : typeof singular === 'string' ? [singular] : ['none']; + if (!methods.includes('none')) problems.push('the client must support token_endpoint_auth_method "none"'); + + if (problems.length) throw new Error(`Invalid client metadata document: ${problems.join('; ')}`); + return doc as ClientMetadataDocument; +} + +type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void; + +/** Resolves like dns.lookup but fails if any resolved address is not public, so the socket can only reach public IPs. */ +export function publicOnlyLookup(hostname: string, options: object, callback: LookupCallback): void { + dnsLookup(hostname, { ...options, all: true }, (error, addresses) => { + if (error) return callback(error, []); + const blocked = addresses.find((entry) => !isPublicAddress(entry.address)); + if (blocked) { + return callback( + Object.assign(new Error(`${hostname} resolves to a non-public address`), { code: 'EBLOCKED' }), + [], + ); + } + const wantsAll = (options as { all?: boolean }).all; + if (wantsAll) return callback(null, addresses); + return callback(null, addresses[0].address, addresses[0].family); + }); +} + +export type FetchJson = (url: string) => Promise; + +/** Fetches a JSON document over HTTPS from public addresses only, with no redirects, a timeout, and a size cap. */ +export const fetchPublicJson: FetchJson = (url) => + new Promise((resolve, reject) => { + const host = new URL(url).hostname.replace(/^\[|\]$/g, ''); + if (isIP(host)) { + reject(new Error(`GET ${url} refused: IP-literal hosts bypass the public-address check`)); + return; + } + const req = request( + url, + { method: 'GET', headers: { accept: 'application/json' }, lookup: publicOnlyLookup, timeout: FETCH_TIMEOUT_MS }, + (res) => { + if (res.statusCode !== 200) { + res.resume(); + return reject(new Error(`GET ${url} returned HTTP ${res.statusCode}`)); + } + const chunks: Buffer[] = []; + let size = 0; + res.on('data', (chunk: Buffer) => { + size += chunk.length; + if (size > MAX_DOCUMENT_BYTES) { + req.destroy(new Error(`GET ${url} returned more than ${MAX_DOCUMENT_BYTES} bytes`)); + return; + } + chunks.push(chunk); + }); + res.on('end', () => { + try { + resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); + } catch { + reject(new Error(`GET ${url} did not return JSON`)); + } + }); + }, + ); + // `timeout` only bounds idle time between chunks; this bounds the whole request. + const deadline = setTimeout( + () => req.destroy(new Error(`GET ${url} took longer than ${FETCH_TIMEOUT_MS} ms`)), + FETCH_TIMEOUT_MS, + ); + req.on('close', () => clearTimeout(deadline)); + req.on('timeout', () => req.destroy(new Error(`GET ${url} timed out`))); + req.on('error', reject); + req.end(); + }); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/config.ts b/packages/medusa-mcp/src/modules/mcp_oauth/config.ts new file mode 100644 index 000000000..e10fe2f1e --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/config.ts @@ -0,0 +1,68 @@ +import type { MedusaMcpPluginOptions } from '../../types'; + +export const MCP_SCOPES = ['mcp:read', 'mcp:write', 'mcp:delete'] as const; + +export type McpScope = (typeof MCP_SCOPES)[number]; + +export interface McpOAuthConfig { + /** OAuth issuer and public origin, without a trailing slash. */ + issuer: string; + /** The MCP endpoint's canonical URI, which tokens are issued for. */ + resource: string; + authorizationCodeTtlSeconds: number; + accessTokenTtlSeconds: number; + refreshTokenTtlSeconds: number; +} + +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']); + +export function isLoopbackHost(hostname: string): boolean { + return LOOPBACK_HOSTS.has(hostname); +} + +export function resolveOAuthConfig(options: MedusaMcpPluginOptions = {}): McpOAuthConfig { + const issuer = (options.issuer || 'http://localhost:9000').replace(/\/+$/, ''); + const url = new URL(issuer); + if (url.pathname !== '/' || url.search || url.hash) { + throw new Error(`medusa-mcp issuer must be an origin with no path, query, or fragment: ${issuer}`); + } + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopbackHost(url.hostname))) { + throw new Error(`medusa-mcp issuer must use https outside localhost: ${issuer}`); + } + + return { + issuer, + resource: `${issuer}/mcp`, + authorizationCodeTtlSeconds: 600, + accessTokenTtlSeconds: 3600, + refreshTokenTtlSeconds: 30 * 24 * 3600, + }; +} + +/** RFC 8414 authorization server metadata. */ +export function authorizationServerMetadata(config: McpOAuthConfig) { + return { + issuer: config.issuer, + authorization_endpoint: `${config.issuer}/oauth/authorize`, + token_endpoint: `${config.issuer}/oauth/token`, + registration_endpoint: `${config.issuer}/oauth/register`, + response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], + code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + scopes_supported: [...MCP_SCOPES], + client_id_metadata_document_supported: true, + authorization_response_iss_parameter_supported: true, + }; +} + +/** RFC 9728 protected resource metadata for the MCP endpoint. */ +export function protectedResourceMetadata(config: McpOAuthConfig) { + return { + resource: config.resource, + authorization_servers: [config.issuer], + scopes_supported: [...MCP_SCOPES], + bearer_methods_supported: ['header'], + resource_name: 'Medusa MCP', + }; +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/crypto.ts b/packages/medusa-mcp/src/modules/mcp_oauth/crypto.ts new file mode 100644 index 000000000..a2becbbbf --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/crypto.ts @@ -0,0 +1,60 @@ +import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; + +export function sha256Hex(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +/** RFC 7636: 43 to 128 characters from the unreserved set. */ +export function isValidCodeVerifier(verifier: unknown): verifier is string { + return typeof verifier === 'string' && /^[A-Za-z0-9\-._~]{43,128}$/.test(verifier); +} + +/** RFC 7636 S256: BASE64URL(SHA256(code_verifier)) must equal the code_challenge. */ +export function verifyPkceS256(verifier: string, challenge: string): boolean { + const expected = Buffer.from(createHash('sha256').update(verifier).digest('base64url')); + const actual = Buffer.from(challenge); + return expected.length === actual.length && timingSafeEqual(expected, actual); +} + +/** Which form a signed payload belongs to, so a token signed for one form is refused by another. */ +export type FormPurpose = 'login' | 'consent'; + +/** Signs a JSON payload with an expiry and a purpose, for state the authorize pages round-trip through a form. */ +export function signPayload( + purpose: FormPurpose, + payload: Record, + secret: string, + ttlSeconds: number, +): string { + const body = Buffer.from( + JSON.stringify({ ...payload, purpose, exp: Math.floor(Date.now() / 1000) + ttlSeconds }), + ).toString('base64url'); + const signature = createHmac('sha256', secret).update(body).digest('base64url'); + return `${body}.${signature}`; +} + +/** + * Returns the payload of a token from {@link signPayload}, or undefined if it is forged, malformed, expired, or was + * signed for a different purpose. + */ +export function verifyPayload(purpose: FormPurpose, token: unknown, secret: string): T | undefined { + if (typeof token !== 'string') return undefined; + const [body, signature, ...rest] = token.split('.'); + if (!body || !signature || rest.length) return undefined; + + const expected = Buffer.from(createHmac('sha256', secret).update(body).digest('base64url')); + const actual = Buffer.from(signature); + if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return undefined; + + try { + const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as T & { + exp?: number; + purpose?: string; + }; + if (payload.purpose !== purpose) return undefined; + if (typeof payload.exp !== 'number' || payload.exp < Math.floor(Date.now() / 1000)) return undefined; + return payload; + } catch { + return undefined; + } +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/errors.ts b/packages/medusa-mcp/src/modules/mcp_oauth/errors.ts new file mode 100644 index 000000000..4c118de1b --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/errors.ts @@ -0,0 +1,39 @@ +/** An error an OAuth endpoint reports as `{ error, error_description }`. */ +export class OAuthError extends Error { + constructor( + readonly code: + | 'invalid_request' + | 'invalid_client' + | 'invalid_grant' + | 'invalid_scope' + | 'invalid_target' + | 'invalid_redirect_uri' + | 'invalid_client_metadata' + | 'unsupported_grant_type' + | 'unsupported_response_type' + | 'access_denied' + | 'server_error', + message: string, + readonly status = 400, + ) { + super(message); + this.name = 'OAuthError'; + } + + toJSON() { + return { error: this.code, error_description: this.message }; + } +} + +/** An authorization error raised after the redirect URI is verified, so it goes back to the client by redirect. */ +export class RedirectableOAuthError extends OAuthError { + constructor( + code: OAuthError['code'], + message: string, + readonly redirectUri: string, + readonly state?: string, + ) { + super(code, message); + this.name = 'RedirectableOAuthError'; + } +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/index.ts b/packages/medusa-mcp/src/modules/mcp_oauth/index.ts new file mode 100644 index 000000000..3ae5f0008 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/index.ts @@ -0,0 +1,6 @@ +import { Module } from '@medusajs/framework/utils'; +import McpOAuthService from './service'; + +export const MCP_OAUTH_MODULE = 'mcp_oauth'; + +export default Module(MCP_OAUTH_MODULE, { service: McpOAuthService }); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/migrations/.snapshot-medusa-mcp-oauth.json b/packages/medusa-mcp/src/modules/mcp_oauth/migrations/.snapshot-medusa-mcp-oauth.json new file mode 100644 index 000000000..75f819f08 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/migrations/.snapshot-medusa-mcp-oauth.json @@ -0,0 +1,821 @@ +{ + "namespaces": [ + "public" + ], + "name": "public", + "tables": [ + { + "columns": { + "id": { + "name": "id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": true, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "code_hash": { + "name": "code_hash", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "client_id": { + "name": "client_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "user_id": { + "name": "user_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "auth_identity_id": { + "name": "auth_identity_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "array" + }, + "resource": { + "name": "resource", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "created_at": { + "name": "created_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + } + }, + "name": "mcp_oauth_authorization", + "schema": "public", + "indexes": [ + { + "keyName": "IDX_mcp_oauth_authorization_code_hash_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_authorization_code_hash_unique\" ON \"mcp_oauth_authorization\" (\"code_hash\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_authorization_deleted_at", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_mcp_oauth_authorization_deleted_at\" ON \"mcp_oauth_authorization\" (\"deleted_at\") WHERE deleted_at IS NULL" + }, + { + "keyName": "mcp_oauth_authorization_pkey", + "columnNames": [ + "id" + ], + "composite": false, + "constraint": true, + "primary": true, + "unique": true + } + ], + "checks": [], + "foreignKeys": {}, + "nativeEnums": {} + }, + { + "columns": { + "id": { + "name": "id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": true, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "client_id": { + "name": "client_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "registration": { + "name": "registration", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [ + "cimd", + "dcr" + ], + "mappedType": "enum" + }, + "client_name": { + "name": "client_name", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "array" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "json" + }, + "metadata_fetched_at": { + "name": "metadata_fetched_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "created_at": { + "name": "created_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + } + }, + "name": "mcp_oauth_client", + "schema": "public", + "indexes": [ + { + "keyName": "IDX_mcp_oauth_client_client_id_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_client_client_id_unique\" ON \"mcp_oauth_client\" (\"client_id\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_client_deleted_at", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_mcp_oauth_client_deleted_at\" ON \"mcp_oauth_client\" (\"deleted_at\") WHERE deleted_at IS NULL" + }, + { + "keyName": "mcp_oauth_client_pkey", + "columnNames": [ + "id" + ], + "composite": false, + "constraint": true, + "primary": true, + "unique": true + } + ], + "checks": [], + "foreignKeys": {}, + "nativeEnums": {} + }, + { + "columns": { + "id": { + "name": "id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": true, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "family_id": { + "name": "family_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "authorization_id": { + "name": "authorization_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "parent_token_id": { + "name": "parent_token_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "client_id": { + "name": "client_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "user_id": { + "name": "user_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "auth_identity_id": { + "name": "auth_identity_id", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "array" + }, + "resource": { + "name": "resource", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "access_token_hash": { + "name": "access_token_hash", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "access_expires_at": { + "name": "access_expires_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "refresh_token_hash": { + "name": "refresh_token_hash", + "type": "text", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": null, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "text" + }, + "refresh_expires_at": { + "name": "refresh_expires_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "rotated_at": { + "name": "rotated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "created_at": { + "name": "created_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": false, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": "now()", + "comment": null, + "enumItems": [], + "mappedType": "datetime" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamptz", + "unsigned": false, + "autoincrement": false, + "primary": false, + "nullable": true, + "unique": false, + "length": 6, + "precision": null, + "scale": null, + "default": null, + "comment": null, + "enumItems": [], + "mappedType": "datetime" + } + }, + "name": "mcp_oauth_token", + "schema": "public", + "indexes": [ + { + "keyName": "IDX_mcp_oauth_token_authorization_id_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_authorization_id_unique\" ON \"mcp_oauth_token\" (\"authorization_id\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_token_parent_token_id_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_parent_token_id_unique\" ON \"mcp_oauth_token\" (\"parent_token_id\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_token_access_token_hash_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_access_token_hash_unique\" ON \"mcp_oauth_token\" (\"access_token_hash\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_token_refresh_token_hash_unique", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_refresh_token_hash_unique\" ON \"mcp_oauth_token\" (\"refresh_token_hash\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_token_deleted_at", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_deleted_at\" ON \"mcp_oauth_token\" (\"deleted_at\") WHERE deleted_at IS NULL" + }, + { + "keyName": "IDX_mcp_oauth_token_family_id", + "columnNames": [], + "composite": false, + "constraint": false, + "primary": false, + "unique": false, + "expression": "CREATE INDEX IF NOT EXISTS \"IDX_mcp_oauth_token_family_id\" ON \"mcp_oauth_token\" (\"family_id\") WHERE deleted_at IS NULL" + }, + { + "keyName": "mcp_oauth_token_pkey", + "columnNames": [ + "id" + ], + "composite": false, + "constraint": true, + "primary": true, + "unique": true + } + ], + "checks": [], + "foreignKeys": {}, + "nativeEnums": {} + } + ], + "nativeEnums": {} +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/migrations/Migration20261110204756.ts b/packages/medusa-mcp/src/modules/mcp_oauth/migrations/Migration20261110204756.ts new file mode 100644 index 000000000..3045bb8cf --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/migrations/Migration20261110204756.ts @@ -0,0 +1,73 @@ +import { Migration } from '@medusajs/framework/mikro-orm/migrations'; + +export class Migration20261110204756 extends Migration { + override async up(): Promise { + this.addSql( + `alter table if exists "mcp_oauth_token" drop constraint if exists "mcp_oauth_token_refresh_token_hash_unique";`, + ); + this.addSql( + `alter table if exists "mcp_oauth_token" drop constraint if exists "mcp_oauth_token_access_token_hash_unique";`, + ); + this.addSql( + `alter table if exists "mcp_oauth_token" drop constraint if exists "mcp_oauth_token_parent_token_id_unique";`, + ); + this.addSql( + `alter table if exists "mcp_oauth_token" drop constraint if exists "mcp_oauth_token_authorization_id_unique";`, + ); + this.addSql( + `alter table if exists "mcp_oauth_client" drop constraint if exists "mcp_oauth_client_client_id_unique";`, + ); + this.addSql( + `alter table if exists "mcp_oauth_authorization" drop constraint if exists "mcp_oauth_authorization_code_hash_unique";`, + ); + this.addSql( + `create table if not exists "mcp_oauth_authorization" ("id" text not null, "code_hash" text not null, "client_id" text not null, "user_id" text not null, "auth_identity_id" text not null, "scopes" text[] not null, "resource" text not null, "redirect_uri" text not null, "code_challenge" text not null, "expires_at" timestamptz not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "mcp_oauth_authorization_pkey" primary key ("id"));`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_authorization_code_hash_unique" ON "mcp_oauth_authorization" ("code_hash") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE INDEX IF NOT EXISTS "IDX_mcp_oauth_authorization_deleted_at" ON "mcp_oauth_authorization" ("deleted_at") WHERE deleted_at IS NULL;`, + ); + + this.addSql( + `create table if not exists "mcp_oauth_client" ("id" text not null, "client_id" text not null, "registration" text check ("registration" in ('cimd', 'dcr')) not null, "client_name" text not null, "redirect_uris" text[] not null, "metadata" jsonb not null, "metadata_fetched_at" timestamptz null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "mcp_oauth_client_pkey" primary key ("id"));`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_client_client_id_unique" ON "mcp_oauth_client" ("client_id") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE INDEX IF NOT EXISTS "IDX_mcp_oauth_client_deleted_at" ON "mcp_oauth_client" ("deleted_at") WHERE deleted_at IS NULL;`, + ); + + this.addSql( + `create table if not exists "mcp_oauth_token" ("id" text not null, "family_id" text not null, "authorization_id" text null, "parent_token_id" text null, "client_id" text not null, "user_id" text not null, "auth_identity_id" text not null, "scopes" text[] not null, "resource" text not null, "access_token_hash" text not null, "access_expires_at" timestamptz not null, "refresh_token_hash" text not null, "refresh_expires_at" timestamptz not null, "rotated_at" timestamptz null, "revoked_at" timestamptz null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "mcp_oauth_token_pkey" primary key ("id"));`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_authorization_id_unique" ON "mcp_oauth_token" ("authorization_id") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_parent_token_id_unique" ON "mcp_oauth_token" ("parent_token_id") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_access_token_hash_unique" ON "mcp_oauth_token" ("access_token_hash") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_refresh_token_hash_unique" ON "mcp_oauth_token" ("refresh_token_hash") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_deleted_at" ON "mcp_oauth_token" ("deleted_at") WHERE deleted_at IS NULL;`, + ); + this.addSql( + `CREATE INDEX IF NOT EXISTS "IDX_mcp_oauth_token_family_id" ON "mcp_oauth_token" ("family_id") WHERE deleted_at IS NULL;`, + ); + } + + override async down(): Promise { + this.addSql(`drop table if exists "mcp_oauth_authorization" cascade;`); + + this.addSql(`drop table if exists "mcp_oauth_client" cascade;`); + + this.addSql(`drop table if exists "mcp_oauth_token" cascade;`); + } +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/models/authorization.ts b/packages/medusa-mcp/src/modules/mcp_oauth/models/authorization.ts new file mode 100644 index 000000000..03da98281 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/models/authorization.ts @@ -0,0 +1,15 @@ +import { model } from '@medusajs/framework/utils'; + +/** A single-use authorization code, bound to the PKCE challenge, redirect URI, and resource it was issued for. */ +export const McpOAuthAuthorization = model.define('mcp_oauth_authorization', { + id: model.id({ prefix: 'mcpaz' }).primaryKey(), + code_hash: model.text().unique(), + client_id: model.text(), + user_id: model.text(), + auth_identity_id: model.text(), + scopes: model.array(), + resource: model.text(), + redirect_uri: model.text(), + code_challenge: model.text(), + expires_at: model.dateTime(), +}); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/models/client.ts b/packages/medusa-mcp/src/modules/mcp_oauth/models/client.ts new file mode 100644 index 000000000..d98101759 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/models/client.ts @@ -0,0 +1,12 @@ +import { model } from '@medusajs/framework/utils'; + +/** An OAuth client, registered by Client ID Metadata Document (`cimd`) or Dynamic Client Registration (`dcr`). */ +export const McpOAuthClient = model.define('mcp_oauth_client', { + id: model.id({ prefix: 'mcpcl' }).primaryKey(), + client_id: model.text().unique(), + registration: model.enum(['cimd', 'dcr']), + client_name: model.text(), + redirect_uris: model.array(), + metadata: model.json(), + metadata_fetched_at: model.dateTime().nullable(), +}); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/models/token.ts b/packages/medusa-mcp/src/modules/mcp_oauth/models/token.ts new file mode 100644 index 000000000..cabe84496 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/models/token.ts @@ -0,0 +1,25 @@ +import { model } from '@medusajs/framework/utils'; + +/** + * An access token and its refresh token. `authorization_id` and `parent_token_id` are unique, so a code can be + * exchanged once and a refresh token rotated once, even under concurrent requests. + */ +export const McpOAuthToken = model + .define('mcp_oauth_token', { + id: model.id({ prefix: 'mcptk' }).primaryKey(), + family_id: model.text(), + authorization_id: model.text().unique().nullable(), + parent_token_id: model.text().unique().nullable(), + client_id: model.text(), + user_id: model.text(), + auth_identity_id: model.text(), + scopes: model.array(), + resource: model.text(), + access_token_hash: model.text().unique(), + access_expires_at: model.dateTime(), + refresh_token_hash: model.text().unique(), + refresh_expires_at: model.dateTime(), + rotated_at: model.dateTime().nullable(), + revoked_at: model.dateTime().nullable(), + }) + .indexes([{ on: ['family_id'] }]); diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/redirect-uri.ts b/packages/medusa-mcp/src/modules/mcp_oauth/redirect-uri.ts new file mode 100644 index 000000000..babf9d873 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/redirect-uri.ts @@ -0,0 +1,29 @@ +import { isLoopbackHost } from './config'; + +const MAX_REDIRECT_URIS = 10; +const MAX_URI_LENGTH = 2048; + +/** Why a redirect URI is unacceptable, or undefined when it is acceptable: HTTPS, or HTTP to a loopback host. */ +export function redirectUriProblem(value: unknown): string | undefined { + if (typeof value !== 'string' || !value) return 'redirect URI must be a non-empty string'; + if (value.length > MAX_URI_LENGTH) return `redirect URI is longer than ${MAX_URI_LENGTH} characters`; + + let url: URL; + try { + url = new URL(value); + } catch { + return `redirect URI is not an absolute URL: ${value}`; + } + if (url.hash || value.includes('#')) return `redirect URI must not contain a fragment: ${value}`; + if (url.username || url.password) return `redirect URI must not contain credentials: ${value}`; + if (url.protocol === 'https:') return undefined; + if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return undefined; + return `redirect URI must use https, or http to localhost: ${value}`; +} + +/** Validates a client's redirect URI list, returning the problems found. */ +export function redirectUrisProblems(value: unknown): string[] { + if (!Array.isArray(value) || !value.length) return ['redirect_uris must be a non-empty array']; + if (value.length > MAX_REDIRECT_URIS) return [`redirect_uris may list at most ${MAX_REDIRECT_URIS} URIs`]; + return value.map(redirectUriProblem).filter((problem): problem is string => Boolean(problem)); +} diff --git a/packages/medusa-mcp/src/modules/mcp_oauth/service.ts b/packages/medusa-mcp/src/modules/mcp_oauth/service.ts new file mode 100644 index 000000000..1aeee90c5 --- /dev/null +++ b/packages/medusa-mcp/src/modules/mcp_oauth/service.ts @@ -0,0 +1,414 @@ +import { randomBytes } from 'node:crypto'; +import { MedusaService } from '@medusajs/framework/utils'; +import type { MedusaMcpPluginOptions } from '../../types'; +import { cimdClientIdProblem, type FetchJson, fetchPublicJson, validateClientMetadataDocument } from './cimd'; +import { MCP_SCOPES, type McpOAuthConfig, type McpScope, resolveOAuthConfig } from './config'; +import { isValidCodeVerifier, sha256Hex, verifyPkceS256 } from './crypto'; +import { OAuthError, RedirectableOAuthError } from './errors'; +import { McpOAuthAuthorization } from './models/authorization'; +import { McpOAuthClient } from './models/client'; +import { McpOAuthToken } from './models/token'; +import { redirectUrisProblems } from './redirect-uri'; + +const CIMD_CACHE_MS = 60 * 60 * 1000; +const SUPPORTED_GRANT_TYPES = ['authorization_code', 'refresh_token']; +const MAX_CLIENT_NAME_LENGTH = 200; + +export interface ResolvedClient { + client_id: string; + registration: 'cimd' | 'dcr'; + client_name: string; + redirect_uris: string[]; +} + +/** A validated authorization request, ready for the user to approve. */ +export interface AuthorizationRequest { + client_id: string; + client_name: string; + redirect_uri: string; + scopes: McpScope[]; + state?: string; + code_challenge: string; + resource: string; +} + +/** Who approved an authorization: the Medusa admin user and their auth identity. */ +export interface AuthorizingUser { + user_id: string; + auth_identity_id: string; +} + +export interface TokenResponse { + access_token: string; + token_type: 'Bearer'; + expires_in: number; + refresh_token: string; + scope: string; +} + +/** What an access token grants, as the MCP endpoint sees it. */ +export interface VerifiedAccessToken extends AuthorizingUser { + token_id: string; + client_id: string; + scopes: McpScope[]; + resource: string; + expires_at: Date; +} + +const CODE_CHALLENGE = /^[A-Za-z0-9\-_]{43,128}$/; + +/** Parses a space-delimited scope string into known MCP scopes; no scope means every scope. */ +export function parseScopes(scope: unknown): McpScope[] | undefined { + if (scope === undefined || scope === '') return [...MCP_SCOPES]; + if (typeof scope !== 'string') return undefined; + const requested = [...new Set(scope.split(' ').filter(Boolean))]; + if (!requested.every((item): item is McpScope => (MCP_SCOPES as readonly string[]).includes(item))) return undefined; + return MCP_SCOPES.filter((item) => requested.includes(item)); +} + +function optionalString(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined; +} + +export function randomToken(prefix: string): string { + return `${prefix}${randomBytes(32).toString('base64url')}`; +} + +function stringArray(value: unknown): string[] | undefined { + return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : undefined; +} + +export default class McpOAuthService extends MedusaService({ + McpOAuthClient, + McpOAuthAuthorization, + McpOAuthToken, +}) { + readonly config: McpOAuthConfig; + readonly options: MedusaMcpPluginOptions; + protected fetchJson: FetchJson = fetchPublicJson; + + constructor(container: Record, options?: MedusaMcpPluginOptions) { + super(container, options); + this.options = options ?? {}; + this.config = resolveOAuthConfig(options); + } + + /** Test seam for Client ID Metadata Document fetches. */ + async setFetchJson(fetchJson: FetchJson): Promise { + this.fetchJson = fetchJson; + } + + /** + * Finds the client for a client_id. A URL client_id is a Client ID Metadata Document, fetched (and cached for + * an hour) from that URL. Any other client_id must have been registered through Dynamic Client Registration. + */ + async resolveClient(clientId: unknown): Promise { + if (typeof clientId !== 'string' || !clientId) throw new OAuthError('invalid_request', 'client_id is required'); + const [existing] = await this.listMcpOAuthClients({ client_id: clientId }); + + if (!clientId.startsWith('https://')) { + if (!existing || existing.registration !== 'dcr') throw new OAuthError('invalid_client', 'Unknown client_id'); + return existing as ResolvedClient; + } + + const problem = cimdClientIdProblem(clientId); + if (problem) throw new OAuthError('invalid_client', problem); + if ( + existing?.metadata_fetched_at && + Date.now() - new Date(existing.metadata_fetched_at).getTime() < CIMD_CACHE_MS + ) { + return existing as ResolvedClient; + } + + let document: ReturnType; + try { + document = validateClientMetadataDocument(clientId, await this.fetchJson(clientId)); + } catch (error) { + throw new OAuthError('invalid_client', (error as Error).message); + } + + const data = { + client_id: clientId, + registration: 'cimd' as const, + client_name: document.client_name.slice(0, MAX_CLIENT_NAME_LENGTH), + redirect_uris: document.redirect_uris, + metadata: document, + metadata_fetched_at: new Date(), + }; + if (existing) return (await this.updateMcpOAuthClients({ id: existing.id, ...data })) as ResolvedClient; + try { + return (await this.createMcpOAuthClients(data)) as ResolvedClient; + } catch (error) { + // Another request created this client first; the unique client_id index rejected the duplicate. + const [created] = await this.listMcpOAuthClients({ client_id: clientId }); + if (created) return created as ResolvedClient; + throw error; + } + } + + /** RFC 7591 Dynamic Client Registration for public clients. */ + async registerDynamicClient(body: unknown) { + const request = (body && typeof body === 'object' ? body : {}) as Record; + + const redirectProblems = redirectUrisProblems(request.redirect_uris); + if (redirectProblems.length) throw new OAuthError('invalid_redirect_uri', redirectProblems.join('; ')); + + const problems: string[] = []; + if (request.token_endpoint_auth_method !== undefined && request.token_endpoint_auth_method !== 'none') { + problems.push('token_endpoint_auth_method must be "none"; this server only registers public clients'); + } + const grantTypes = request.grant_types === undefined ? SUPPORTED_GRANT_TYPES : stringArray(request.grant_types); + if (!grantTypes?.every((grant) => SUPPORTED_GRANT_TYPES.includes(grant))) { + problems.push(`grant_types must be a subset of ${SUPPORTED_GRANT_TYPES.join(', ')}`); + } + const responseTypes = request.response_types === undefined ? ['code'] : stringArray(request.response_types); + if (!responseTypes?.every((type) => type === 'code')) problems.push('response_types must be ["code"]'); + if (request.client_name !== undefined && typeof request.client_name !== 'string') { + problems.push('client_name must be a string'); + } + if (problems.length) throw new OAuthError('invalid_client_metadata', problems.join('; ')); + + const clientName = ((request.client_name as string | undefined) || 'Unnamed MCP client').slice( + 0, + MAX_CLIENT_NAME_LENGTH, + ); + const metadata = { + client_name: clientName, + redirect_uris: request.redirect_uris as string[], + token_endpoint_auth_method: 'none', + grant_types: grantTypes, + response_types: responseTypes, + }; + const client = await this.createMcpOAuthClients({ + client_id: randomToken('mcpdcr_'), + registration: 'dcr', + client_name: clientName, + redirect_uris: metadata.redirect_uris, + metadata, + }); + + return { + client_id: client.client_id, + client_id_issued_at: Math.floor(new Date(client.created_at).getTime() / 1000), + ...metadata, + }; + } + + /** + * Validates an authorization request. Problems found before the redirect URI is verified throw an + * {@link OAuthError}, shown to the user. Problems after that throw a {@link RedirectableOAuthError}, sent back to + * the client. + */ + async parseAuthorizationRequest(params: Record): Promise { + const client = await this.resolveClient(params.client_id); + const redirectUri = optionalString(params.redirect_uri); + if (!redirectUri) throw new OAuthError('invalid_request', 'redirect_uri is required'); + if (!client.redirect_uris.includes(redirectUri)) { + throw new OAuthError('invalid_request', 'redirect_uri is not registered for this client'); + } + + const state = optionalString(params.state); + const fail = (code: OAuthError['code'], message: string) => + new RedirectableOAuthError(code, message, redirectUri, state); + + if (params.response_type !== 'code') throw fail('unsupported_response_type', 'response_type must be "code"'); + if (params.code_challenge_method !== 'S256') throw fail('invalid_request', 'code_challenge_method must be "S256"'); + const codeChallenge = optionalString(params.code_challenge); + if (!codeChallenge || !CODE_CHALLENGE.test(codeChallenge)) { + throw fail('invalid_request', 'code_challenge must be a base64url S256 challenge'); + } + const resource = optionalString(params.resource) ?? this.config.resource; + if (resource !== this.config.resource) throw fail('invalid_target', `resource must be ${this.config.resource}`); + const scopes = parseScopes(params.scope); + if (!scopes) throw fail('invalid_scope', `scope must be a subset of: ${MCP_SCOPES.join(' ')}`); + + return { + client_id: client.client_id, + client_name: client.client_name, + redirect_uri: redirectUri, + scopes, + state, + code_challenge: codeChallenge, + resource, + }; + } + + /** Stores a single-use authorization code for an approved request and returns the code. */ + async issueAuthorizationCode( + request: AuthorizationRequest, + user: AuthorizingUser, + scopes: McpScope[], + ): Promise { + const code = randomToken('mcp_ac_'); + await this.createMcpOAuthAuthorizations({ + code_hash: sha256Hex(code), + client_id: request.client_id, + user_id: user.user_id, + auth_identity_id: user.auth_identity_id, + scopes, + resource: request.resource, + redirect_uri: request.redirect_uri, + code_challenge: request.code_challenge, + expires_at: new Date(Date.now() + this.config.authorizationCodeTtlSeconds * 1000), + }); + return code; + } + + /** The `authorization_code` grant. A code that was already exchanged revokes every token issued from it. */ + async exchangeAuthorizationCode(params: Record): Promise { + const code = optionalString(params.code); + if (!code) throw new OAuthError('invalid_request', 'code is required'); + const [authorization] = await this.listMcpOAuthAuthorizations({ code_hash: sha256Hex(code) }); + if (!authorization) throw new OAuthError('invalid_grant', 'authorization code is invalid'); + if (new Date(authorization.expires_at).getTime() < Date.now()) { + throw new OAuthError('invalid_grant', 'authorization code has expired'); + } + if (authorization.client_id !== params.client_id) { + throw new OAuthError('invalid_grant', 'authorization code was issued to a different client'); + } + if (authorization.redirect_uri !== params.redirect_uri) { + throw new OAuthError('invalid_grant', 'redirect_uri does not match the authorization request'); + } + if ( + !isValidCodeVerifier(params.code_verifier) || + !verifyPkceS256(params.code_verifier, authorization.code_challenge) + ) { + throw new OAuthError('invalid_grant', 'PKCE verification failed'); + } + if (params.resource !== undefined && params.resource !== authorization.resource) { + throw new OAuthError('invalid_target', `resource must be ${authorization.resource}`); + } + + const replayed = async () => { + const issued = await this.listMcpOAuthTokens({ authorization_id: authorization.id }); + await Promise.all( + [...new Set(issued.map((token) => token.family_id))].map((family) => this.revokeFamily(family)), + ); + return new OAuthError('invalid_grant', 'authorization code was already used; tokens issued from it are revoked'); + }; + const [alreadyIssued] = await this.listMcpOAuthTokens({ authorization_id: authorization.id }); + if (alreadyIssued) throw await replayed(); + + try { + return await this.issueTokens({ + family_id: randomToken('mcpfam_'), + authorization_id: authorization.id, + parent_token_id: null, + client_id: authorization.client_id, + user_id: authorization.user_id, + auth_identity_id: authorization.auth_identity_id, + scopes: authorization.scopes as McpScope[], + resource: authorization.resource, + }); + } catch (error) { + const [raced] = await this.listMcpOAuthTokens({ authorization_id: authorization.id }); + if (raced) throw await replayed(); + throw error; + } + } + + /** + * The `refresh_token` grant with rotation. Presenting a refresh token that was already rotated is treated as + * theft and revokes the whole token family. + */ + async refreshAccessToken(params: Record): Promise { + const refreshToken = optionalString(params.refresh_token); + if (!refreshToken) throw new OAuthError('invalid_request', 'refresh_token is required'); + const [token] = await this.listMcpOAuthTokens({ refresh_token_hash: sha256Hex(refreshToken) }); + if (!token || token.client_id !== params.client_id) + throw new OAuthError('invalid_grant', 'refresh token is invalid'); + if (token.revoked_at) throw new OAuthError('invalid_grant', 'refresh token was revoked'); + + const reused = async () => { + await this.revokeFamily(token.family_id); + return new OAuthError('invalid_grant', 'refresh token was already used; every token from this grant is revoked'); + }; + if (token.rotated_at) throw await reused(); + if (new Date(token.refresh_expires_at).getTime() < Date.now()) { + throw new OAuthError('invalid_grant', 'refresh token has expired'); + } + if (params.resource !== undefined && params.resource !== token.resource) { + throw new OAuthError('invalid_target', `resource must be ${token.resource}`); + } + + const granted = token.scopes as McpScope[]; + const requested = params.scope === undefined ? granted : parseScopes(params.scope); + if (!requested?.every((scope) => granted.includes(scope))) { + throw new OAuthError('invalid_scope', 'a refreshed token cannot gain scopes the original grant did not have'); + } + + let response: TokenResponse; + try { + response = await this.issueTokens({ + family_id: token.family_id, + authorization_id: null, + parent_token_id: token.id, + client_id: token.client_id, + user_id: token.user_id, + auth_identity_id: token.auth_identity_id, + scopes: requested, + resource: token.resource, + }); + } catch (error) { + const [raced] = await this.listMcpOAuthTokens({ parent_token_id: token.id }); + if (raced) throw await reused(); + throw error; + } + await this.updateMcpOAuthTokens({ id: token.id, rotated_at: new Date() }); + return response; + } + + /** Looks up a live access token for the given resource; undefined when unknown, expired, or revoked. */ + async verifyAccessToken(accessToken: string, resource: string): Promise { + if (!accessToken.startsWith('mcp_at_')) return undefined; + const [token] = await this.listMcpOAuthTokens({ access_token_hash: sha256Hex(accessToken) }); + if (!token || token.revoked_at || token.resource !== resource) return undefined; + const expiresAt = new Date(token.access_expires_at); + if (expiresAt.getTime() < Date.now()) return undefined; + return { + token_id: token.id, + user_id: token.user_id, + auth_identity_id: token.auth_identity_id, + client_id: token.client_id, + scopes: token.scopes as McpScope[], + resource: token.resource, + expires_at: expiresAt, + }; + } + + async revokeFamily(familyId: string): Promise { + await this.updateMcpOAuthTokens({ + selector: { family_id: familyId, revoked_at: null }, + data: { revoked_at: new Date() }, + }); + } + + protected async issueTokens(grant: { + family_id: string; + authorization_id: string | null; + parent_token_id: string | null; + client_id: string; + user_id: string; + auth_identity_id: string; + scopes: McpScope[]; + resource: string; + }): Promise { + const accessToken = randomToken('mcp_at_'); + const refreshToken = randomToken('mcp_rt_'); + const now = Date.now(); + await this.createMcpOAuthTokens({ + ...grant, + access_token_hash: sha256Hex(accessToken), + access_expires_at: new Date(now + this.config.accessTokenTtlSeconds * 1000), + refresh_token_hash: sha256Hex(refreshToken), + refresh_expires_at: new Date(now + this.config.refreshTokenTtlSeconds * 1000), + }); + return { + access_token: accessToken, + token_type: 'Bearer', + expires_in: this.config.accessTokenTtlSeconds, + refresh_token: refreshToken, + scope: grant.scopes.join(' '), + }; + } +} diff --git a/packages/medusa-mcp/src/openapi/__tests__/build-spec.unit.spec.ts b/packages/medusa-mcp/src/openapi/__tests__/build-spec.unit.spec.ts new file mode 100644 index 000000000..f6cc7725b --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/build-spec.unit.spec.ts @@ -0,0 +1,175 @@ +import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { buildApiSpec, countOperations } from '../build-spec'; +import { compareCodeUnits } from '../compare'; +import { loadCoreSpecs, specsDirectory } from '../core-spec'; +import { OpenApiContractError } from '../discover-routes'; + +const fixture = (name: string) => path.join(__dirname, 'fixtures', name); + +const CORE_ADMIN_OPERATIONS = 414; +const CORE_STORE_OPERATIONS = 79; + +function contractProblems(run: () => unknown): string[] { + try { + run(); + } catch (error) { + if (error instanceof OpenApiContractError) return error.problems; + throw error; + } + throw new Error('Expected an OpenApiContractError'); +} + +describe('buildApiSpec', () => { + const spec = buildApiSpec({ projectRoot: fixture('valid') }); + const admin = spec.documents.admin; + + it('adds documented custom routes to the pinned core spec for the project Medusa version', () => { + expect(spec.medusaVersion).toBe('2.22.1'); + expect(countOperations(admin)).toBe(CORE_ADMIN_OPERATIONS + 4); + expect(countOperations(spec.documents.store)).toBe(CORE_STORE_OPERATIONS + 1); + expect(admin.paths['/admin/widgets']).toEqual( + expect.objectContaining({ get: expect.any(Object), post: expect.any(Object) }), + ); + expect(Object.keys(admin.paths['/admin/widgets/{id}']).sort()).toEqual(['delete', 'get']); + expect(spec.documents.store.paths['/store/widgets'].get).toMatchObject({ operationId: 'listStoreWidgets' }); + }); + + it('turns path segments, query schemas, bodies, and responses into OpenAPI 3.0 shapes', () => { + const list = admin.paths['/admin/widgets'].get as Record; + expect(list).toMatchObject({ + operationId: 'listAdminWidgets', + tags: ['Widgets'], + security: [{ api_token: [] }, { cookie_auth: [] }, { jwt_token: [] }], + 'x-medusa-mcp-source': 'custom', + }); + expect(list.parameters).toEqual([ + { name: 'limit', in: 'query', required: false, schema: expect.objectContaining({ type: 'integer' }) }, + { name: 'q', in: 'query', required: false, schema: { type: 'string' } }, + ]); + + expect(list.responses).toMatchObject({ + 200: { + content: { + 'application/json': { + schema: { + properties: { widgets: { items: { properties: { retired_at: { type: 'string', nullable: true } } } } }, + }, + }, + }, + }, + }); + + expect(admin.paths['/admin/widgets'].post).toHaveProperty('requestBody', { + required: true, + content: { + 'application/json': { + schema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, + }, + }, + }); + + expect((admin.paths['/admin/widgets/{id}'].get as Record).parameters).toEqual([ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } }, + ]); + }); + + it('keeps hidden routes and routes outside /admin and /store out of the documents and reports them as gaps', () => { + expect(admin.paths['/admin/internal-sql']).toBeUndefined(); + expect(spec.gaps).toEqual([ + { method: 'GET', path: '/admin/internal-sql', source: 'app', reason: 'hidden' }, + { method: 'POST', path: '/hooks/ping', source: 'app', reason: 'outside-admin-and-store' }, + ]); + }); + + it('reports plugins it cannot resolve or scan instead of failing the build', () => { + const withPlugins = buildApiSpec({ + projectRoot: fixture('valid'), + plugins: ['@lambdacurry/medusa-mcp', './plugins/bad-segments', 'not-an-installed-plugin'], + }); + expect(withPlugins.documents).toEqual(spec.documents); + expect(withPlugins.unscannedPlugins).toEqual([ + { name: './plugins/bad-segments', reason: expect.stringMatching(/Unsupported route segment "\[\.\.\.path\]"/) }, + { name: 'not-an-installed-plugin', reason: expect.any(String) }, + ]); + }); + + it('orders by code unit, independent of locale', () => { + expect(['b', 'Z', 'a', 'É'].sort(compareCodeUnits)).toEqual(['Z', 'a', 'b', 'É']); + }); + + it('produces the same revision for the same content and a new one when a contract changes', () => { + expect(buildApiSpec({ projectRoot: fixture('valid') }).revision).toBe(spec.revision); + + const copy = mkdtempSync(path.join(__dirname, 'tmp-')); + try { + cpSync(fixture('valid'), copy, { recursive: true }); + const contract = path.join(copy, 'src/api/store/widgets/openapi.ts'); + writeFileSync(contract, readFileSync(contract, 'utf8').replace('List widgets', 'List every widget')); + const changed = buildApiSpec({ projectRoot: copy }); + expect(changed.revision).not.toBe(spec.revision); + expect(changed.documents.admin).toEqual(admin); + } finally { + rmSync(copy, { recursive: true, force: true }); + } + }); + + it('fails when a route has no contract', () => { + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('missing-contract') }))).toEqual([ + 'admin/widgets/route.ts has no openapi.ts contract next to it', + ]); + }); + + it('fails when a contract and its route disagree about methods', () => { + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('mismatch') }))).toEqual([ + 'admin/widgets/route.ts and its contract disagree. Undocumented: POST. Documented but not exported: DELETE.', + ]); + }); + + it('fails when a custom route collides with a core operation unless the override is declared', () => { + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('collision') }))).toEqual([ + "POST /admin/products/{id} is already defined by Medusa's core spec", + ]); + + const overridden = buildApiSpec({ projectRoot: fixture('collision'), overrides: ['post /admin/products/{id}'] }); + expect(overridden.documents.admin.paths['/admin/products/{id}'].post).toMatchObject({ + operationId: 'postCustomProductsId', + 'x-medusa-overridden-by-custom-route': true, + }); + }); + + it('fails on duplicate operation ids, including ids the core spec already uses', () => { + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('duplicate-id') }))).toEqual([ + 'operationId "getThing" is used by both GET /admin/a and GET /admin/b', + ]); + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('core-operation-id') }))).toEqual([ + 'operationId "PostProductsId" is used by both POST /admin/products/{id} and GET /admin/thing', + ]); + }); + + it('rejects route segments it cannot map to an OpenAPI path', () => { + expect(contractProblems(() => buildApiSpec({ projectRoot: fixture('catch-all') }))[0]).toMatch( + /Unsupported route segment "\[\.\.\.path\]"/, + ); + }); +}); + +describe('loadCoreSpecs', () => { + it('fails for a Medusa version with no pinned spec', () => { + expect(() => loadCoreSpecs('9.9.9')).toThrow('No pinned core OpenAPI spec for Medusa 9.9.9 (pinned: 2.22.1)'); + }); + + it('fails when a pinned spec no longer matches its recorded checksum', () => { + const root = mkdtempSync(path.join(__dirname, 'tmp-')); + try { + cpSync(path.join(specsDirectory(), '2.22.1'), path.join(root, '2.22.1'), { recursive: true }); + const manifestFile = path.join(root, '2.22.1/manifest.json'); + const manifest = JSON.parse(readFileSync(manifestFile, 'utf8')); + manifest.specs.store.sha256 = '0'.repeat(64); + writeFileSync(manifestFile, JSON.stringify(manifest)); + expect(() => loadCoreSpecs('2.22.1', root)).toThrow('Core store spec for Medusa 2.22.1 fails its checksum'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/catch-all/src/api/admin/files/[...path]/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/catch-all/src/api/admin/files/[...path]/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/catch-all/src/api/admin/files/[...path]/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/openapi.ts new file mode 100644 index 000000000..3238c6fde --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/openapi.ts @@ -0,0 +1,10 @@ +export default { + tag: 'Products', + operations: { + POST: { + operationId: 'postCustomProductsId', + summary: 'Custom product update', + responses: { 200: { description: 'OK' } }, + }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/route.ts new file mode 100644 index 000000000..ed2cdb47c --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/collision/src/api/admin/products/[id]/route.ts @@ -0,0 +1 @@ +export const POST = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/openapi.ts new file mode 100644 index 000000000..3bda12987 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/openapi.ts @@ -0,0 +1,6 @@ +export default { + tag: 'Things', + operations: { + GET: { operationId: 'PostProductsId', summary: 'Reuses a core id', responses: { 200: { description: 'OK' } } }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/core-operation-id/src/api/admin/thing/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/openapi.ts new file mode 100644 index 000000000..0aa13e5d0 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/openapi.ts @@ -0,0 +1,4 @@ +export default { + tag: 'A', + operations: { GET: { operationId: 'getThing', summary: 'A', responses: { 200: { description: 'OK' } } } }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/a/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/openapi.ts new file mode 100644 index 000000000..3f930c198 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/openapi.ts @@ -0,0 +1,4 @@ +export default { + tag: 'B', + operations: { GET: { operationId: 'getThing', summary: 'B', responses: { 200: { description: 'OK' } } } }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/duplicate-id/src/api/admin/b/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/openapi.ts new file mode 100644 index 000000000..733269a9c --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/openapi.ts @@ -0,0 +1,7 @@ +export default { + tag: 'Widgets', + operations: { + GET: { operationId: 'listAdminWidgets', summary: 'List', responses: { 200: { description: 'OK' } } }, + DELETE: { operationId: 'deleteAdminWidgets', summary: 'Delete', responses: { 200: { description: 'OK' } } }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/route.ts new file mode 100644 index 000000000..fb66fc593 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/mismatch/src/api/admin/widgets/route.ts @@ -0,0 +1,2 @@ +export const GET = async () => {}; +export const POST = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/missing-contract/src/api/admin/widgets/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/missing-contract/src/api/admin/widgets/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/missing-contract/src/api/admin/widgets/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/.medusa/server/src/api/admin/files/[...path]/route.js b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/.medusa/server/src/api/admin/files/[...path]/route.js new file mode 100644 index 000000000..9dbdb8ee0 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/.medusa/server/src/api/admin/files/[...path]/route.js @@ -0,0 +1 @@ +exports.GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/package.json b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/package.json new file mode 100644 index 000000000..f5a5ea8a2 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/plugins/bad-segments/package.json @@ -0,0 +1 @@ +{ "name": "bad-segments", "version": "0.0.0" } diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/openapi.ts new file mode 100644 index 000000000..2f080e109 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/openapi.ts @@ -0,0 +1,7 @@ +export default { + hidden: true, + tag: 'Internal', + operations: { + GET: { operationId: 'getAdminInternalSql', summary: 'Internal', responses: { 200: { description: 'OK' } } }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/internal-sql/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/openapi.ts new file mode 100644 index 000000000..15b759c21c9e --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/openapi.ts @@ -0,0 +1,11 @@ +export default { + tag: 'Widgets', + operations: { + GET: { operationId: 'getAdminWidget', summary: 'Get a widget', responses: { 200: { description: 'Widget' } } }, + DELETE: { + operationId: 'deleteAdminWidget', + summary: 'Delete a widget', + responses: { 200: { description: 'Deleted' } }, + }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/route.ts new file mode 100644 index 000000000..67aec87cc --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/[id]/route.ts @@ -0,0 +1,4 @@ +export async function GET() {} +const remove = async () => {}; + +export { remove as DELETE }; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/openapi.ts new file mode 100644 index 000000000..2c1a4d50c --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/openapi.ts @@ -0,0 +1,21 @@ +import { z } from '@medusajs/framework/zod'; + +const Widget = z.looseObject({ id: z.string(), name: z.string(), retired_at: z.string().nullable().optional() }); + +export default { + tag: 'Widgets', + operations: { + GET: { + operationId: 'listAdminWidgets', + summary: 'List widgets', + query: z.object({ limit: z.coerce.number().int().optional(), q: z.string().optional() }), + responses: { 200: { description: 'Widgets', schema: z.object({ widgets: z.array(Widget) }) } }, + }, + POST: { + operationId: 'createAdminWidget', + summary: 'Create a widget', + body: z.object({ name: z.string() }), + responses: { 200: { description: 'Created widget', schema: z.object({ widget: Widget }) } }, + }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/route.ts new file mode 100644 index 000000000..fb66fc593 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/admin/widgets/route.ts @@ -0,0 +1,2 @@ +export const GET = async () => {}; +export const POST = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/openapi.ts new file mode 100644 index 000000000..61145dc17 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/openapi.ts @@ -0,0 +1,6 @@ +export default { + tag: 'Hooks', + operations: { + POST: { operationId: 'postPingHook', summary: 'Ping hook', responses: { 200: { description: 'OK' } } }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/route.ts new file mode 100644 index 000000000..ed2cdb47c --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/hooks/ping/route.ts @@ -0,0 +1 @@ +export const POST = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/openapi.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/openapi.ts new file mode 100644 index 000000000..1b80f95f1 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/openapi.ts @@ -0,0 +1,6 @@ +export default { + tag: 'Widgets', + operations: { + GET: { operationId: 'listStoreWidgets', summary: 'List widgets', responses: { 200: { description: 'Widgets' } } }, + }, +}; diff --git a/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/route.ts b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/route.ts new file mode 100644 index 000000000..a463c2dca --- /dev/null +++ b/packages/medusa-mcp/src/openapi/__tests__/fixtures/valid/src/api/store/widgets/route.ts @@ -0,0 +1 @@ +export const GET = async () => {}; diff --git a/packages/medusa-mcp/src/openapi/build-spec.ts b/packages/medusa-mcp/src/openapi/build-spec.ts new file mode 100644 index 000000000..3f20897d1 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/build-spec.ts @@ -0,0 +1,126 @@ +import { createHash } from 'node:crypto'; +import path from 'node:path'; +import { compareCodeUnits } from './compare'; +import { loadCoreSpecs, projectMedusaVersion } from './core-spec'; +import { discoverDocumentedRoutes, discoverRoutes, OpenApiContractError } from './discover-routes'; +import { buildCustomPaths, projectZodJsonSchema } from './generate'; +import { mergeDocuments } from './merge'; +import { API_AREAS, type ApiArea, HTTP_METHODS, type OpenApiDocument, type SpecGap } from './types'; + +const OWN_PACKAGE = '@lambdacurry/medusa-mcp'; + +export interface ApiSpec { + medusaVersion: string; + /** Content hash of the published documents. Equal specs always produce the same revision. */ + revision: string; + documents: Record; + gaps: SpecGap[]; + /** Registered plugins whose routes could not be listed, so their gaps are unknown. */ + unscannedPlugins: UnscannedPlugin[]; +} + +export interface UnscannedPlugin { + name: string; + reason: string; +} + +export interface BuildApiSpecOptions { + /** The Medusa project directory, the one containing `src/api`. */ + projectRoot: string; + /** Plugin package names registered in `medusa-config`. Their routes are reported as gaps. */ + plugins?: string[]; + /** Operation keys such as `post /admin/promotions/{id}` that custom routes may knowingly replace. */ + overrides?: string[]; +} + +function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (value && typeof value === 'object') { + return `{${Object.keys(value) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as Record)[key])}`) + .join(',')}}`; + } + return JSON.stringify(value); +} + +function isDocumented(documents: Record, method: string, routePath: string): boolean { + return API_AREAS.some((area) => Boolean(documents[area].paths[routePath]?.[method.toLowerCase()])); +} + +/** + * Lists the operations other plugins serve that the documents do not describe. A plugin that cannot be resolved or + * scanned is reported in `unscanned` rather than failing the build, since the project cannot fix it. + */ +function pluginGaps( + projectRoot: string, + plugins: string[], + documents: Record, +): { gaps: SpecGap[]; unscanned: UnscannedPlugin[] } { + const gaps: SpecGap[] = []; + const unscanned: UnscannedPlugin[] = []; + + for (const name of plugins.filter((plugin) => plugin !== OWN_PACKAGE)) { + try { + const pluginRoot = path.dirname(require.resolve(`${name}/package.json`, { paths: [projectRoot] })); + for (const route of discoverRoutes(path.join(pluginRoot, '.medusa/server/src/api'))) { + for (const method of route.methods) { + if (isDocumented(documents, method, route.path)) continue; + gaps.push({ method, path: route.path, source: name, reason: 'undocumented-plugin-route' }); + } + } + } catch (error) { + const reason = + error instanceof OpenApiContractError + ? error.problems.join('; ') + : error instanceof Error + ? error.message.split('\n')[0] + : String(error); + unscanned.push({ name, reason }); + } + } + + return { gaps, unscanned }; +} + +/** + * Builds the published admin and store specs for a Medusa project: the pinned core spec for its Medusa + * version plus every custom route's `openapi.ts` contract. Throws {@link OpenApiContractError} listing every + * contract problem. + */ +export function buildApiSpec({ projectRoot, plugins = [], overrides = [] }: BuildApiSpecOptions): ApiSpec { + const apiDirectory = path.join(projectRoot, 'src/api'); + const routes = discoverDocumentedRoutes(apiDirectory); + const custom = buildCustomPaths(routes, projectZodJsonSchema(projectRoot), apiDirectory); + + const medusaVersion = projectMedusaVersion(projectRoot); + const core = loadCoreSpecs(medusaVersion); + const overrideKeys = new Set(overrides); + const problems = [...custom.problems]; + const documents = Object.fromEntries( + API_AREAS.map((area) => { + const merged = mergeDocuments(core[area], custom.paths[area], overrideKeys); + problems.push(...merged.problems); + return [area, merged.document]; + }), + ) as Record; + + if (problems.length) throw new OpenApiContractError(problems); + + const plugin = pluginGaps(projectRoot, plugins, documents); + const gaps = [...custom.gaps, ...plugin.gaps].sort((left, right) => + compareCodeUnits(`${left.path} ${left.method}`, `${right.path} ${right.method}`), + ); + const revision = createHash('sha256').update(canonicalJson({ medusaVersion, documents })).digest('hex'); + + return { medusaVersion, revision, documents, gaps, unscannedPlugins: plugin.unscanned }; +} + +const OPERATION_KEYS = new Set(HTTP_METHODS.map((method) => method.toLowerCase())); + +export function countOperations(document: OpenApiDocument): number { + return Object.values(document.paths).reduce( + (total, item) => total + Object.keys(item).filter((key) => OPERATION_KEYS.has(key)).length, + 0, + ); +} diff --git a/packages/medusa-mcp/src/openapi/compare.ts b/packages/medusa-mcp/src/openapi/compare.ts new file mode 100644 index 000000000..81ea13e74 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/compare.ts @@ -0,0 +1,7 @@ +/** + * Orders strings by UTF-16 code unit. Unlike `localeCompare`, the result never depends on the host's locale or ICU + * version, which matters because ordering feeds the spec revision hash. + */ +export function compareCodeUnits(left: string, right: string): number { + return left < right ? -1 : left > right ? 1 : 0; +} diff --git a/packages/medusa-mcp/src/openapi/core-spec.ts b/packages/medusa-mcp/src/openapi/core-spec.ts new file mode 100644 index 000000000..421b2438e --- /dev/null +++ b/packages/medusa-mcp/src/openapi/core-spec.ts @@ -0,0 +1,62 @@ +import { createHash } from 'node:crypto'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import path from 'node:path'; +import { gunzipSync } from 'node:zlib'; +import { API_AREAS, type ApiArea, type OpenApiDocument } from './types'; + +interface SpecManifest { + medusaVersion: string; + specs: Record; +} + +const PACKAGE_NAME = '@lambdacurry/medusa-mcp'; + +function packageRoot(): string { + let directory = __dirname; + while (directory !== path.dirname(directory)) { + const manifest = path.join(directory, 'package.json'); + if (existsSync(manifest) && JSON.parse(readFileSync(manifest, 'utf8')).name === PACKAGE_NAME) return directory; + directory = path.dirname(directory); + } + throw new Error(`Could not find the ${PACKAGE_NAME} package root from ${__dirname}`); +} + +export function specsDirectory(): string { + return path.join(packageRoot(), 'specs'); +} + +/** The `@medusajs/medusa` version the project at `projectRoot` resolves. */ +export function projectMedusaVersion(projectRoot: string): string { + const manifest = require.resolve('@medusajs/medusa/package.json', { paths: [projectRoot] }); + return (JSON.parse(readFileSync(manifest, 'utf8')) as { version: string }).version; +} + +/** + * Loads the pinned core Medusa specs matching the project's Medusa version and verifies each against the + * checksum recorded when it was fetched. + */ +export function loadCoreSpecs( + medusaVersion: string, + specsRoot: string = specsDirectory(), +): Record { + const directory = path.join(specsRoot, medusaVersion); + if (!existsSync(directory)) { + const pinned = readdirSync(specsRoot).join(', ') || 'none'; + throw new Error( + `No pinned core OpenAPI spec for Medusa ${medusaVersion} (pinned: ${pinned}). Run: node scripts/fetch-core-specs.mjs ${medusaVersion}`, + ); + } + + const manifest = JSON.parse(readFileSync(path.join(directory, 'manifest.json'), 'utf8')) as SpecManifest; + return Object.fromEntries( + API_AREAS.map((area) => { + const { file, sha256 } = manifest.specs[area]; + const text = gunzipSync(readFileSync(path.join(directory, file))).toString('utf8'); + const actual = createHash('sha256').update(text).digest('hex'); + if (actual !== sha256) { + throw new Error(`Core ${area} spec for Medusa ${medusaVersion} fails its checksum: ${actual} != ${sha256}`); + } + return [area, JSON.parse(text) as OpenApiDocument]; + }), + ) as Record; +} diff --git a/packages/medusa-mcp/src/openapi/discover-routes.ts b/packages/medusa-mcp/src/openapi/discover-routes.ts new file mode 100644 index 000000000..cf23c6121 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/discover-routes.ts @@ -0,0 +1,127 @@ +import { readdirSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { HTTP_METHODS, type HttpMethod, type OpenApiRouteContract } from './types'; + +const ROUTE_FILE = /^route\.(ts|js)$/; +const CONTRACT_FILES = ['openapi.ts', 'openapi.js']; +const SKIPPED_DIRECTORIES = new Set(['node_modules', '__tests__']); + +export interface DiscoveredRoute { + /** OpenAPI path, for example `/admin/products/{id}`. */ + path: string; + /** Methods the route module exports, which are the methods Medusa serves for it. */ + methods: HttpMethod[]; + routeFile: string; + contractFile?: string; + contract?: OpenApiRouteContract; +} + +export class OpenApiContractError extends Error { + constructor(readonly problems: string[]) { + super(`OpenAPI contract check failed:\n${problems.map((problem) => `- ${problem}`).join('\n')}`); + this.name = 'OpenApiContractError'; + } +} + +export function findRouteFiles(directory: string): string[] { + let entries: string[]; + try { + entries = readdirSync(directory); + } catch { + return []; + } + + return entries + .flatMap((entry) => { + const entryPath = path.join(directory, entry); + if (statSync(entryPath).isDirectory()) { + return SKIPPED_DIRECTORIES.has(entry) ? [] : findRouteFiles(entryPath); + } + return ROUTE_FILE.test(entry) ? [entryPath] : []; + }) + .sort(); +} + +export function toOpenApiPath(apiDirectory: string, routeFile: string): string { + const segments = path.relative(apiDirectory, path.dirname(routeFile)).split(path.sep).filter(Boolean); + + return `/${segments + .map((segment) => { + const parameter = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/.exec(segment); + if (parameter) return `{${parameter[1]}}`; + if (segment.includes('[') || segment.includes(']')) { + throw new OpenApiContractError([`Unsupported route segment "${segment}" in ${routeFile}`]); + } + return segment; + }) + .join('/')}`; +} + +export function exportedMethods(routeModule: Record): HttpMethod[] { + return HTTP_METHODS.filter((method) => typeof routeModule[method] === 'function'); +} + +function loadModule(file: string): Record { + return require(file) as Record; +} + +function findContractFile(routeFile: string): string | undefined { + const directory = path.dirname(routeFile); + return CONTRACT_FILES.map((file) => path.join(directory, file)).find((file) => { + try { + return statSync(file).isFile(); + } catch { + return false; + } + }); +} + +/** Lists the routes under an API directory and the methods each one serves, without requiring contracts. */ +export function discoverRoutes(apiDirectory: string): DiscoveredRoute[] { + return findRouteFiles(apiDirectory).map((routeFile) => ({ + path: toOpenApiPath(apiDirectory, routeFile), + methods: exportedMethods(loadModule(routeFile)), + routeFile, + })); +} + +/** + * Lists the routes under an API directory and pairs each with its `openapi.ts` contract. Throws one + * {@link OpenApiContractError} listing every route with a missing contract or a method mismatch. + */ +export function discoverDocumentedRoutes(apiDirectory: string): DiscoveredRoute[] { + const problems: string[] = []; + const routes = discoverRoutes(apiDirectory).map((route): DiscoveredRoute => { + const relativeRoute = path.relative(apiDirectory, route.routeFile); + if (!route.methods.length) { + problems.push(`${relativeRoute} exports no HTTP method handlers`); + return route; + } + + const contractFile = findContractFile(route.routeFile); + if (!contractFile) { + problems.push(`${relativeRoute} has no openapi.ts contract next to it`); + return route; + } + + const contract = loadModule(contractFile).default as OpenApiRouteContract | undefined; + if (!contract?.operations || !contract.tag) { + problems.push(`${path.relative(apiDirectory, contractFile)} must default-export { tag, operations }`); + return { ...route, contractFile }; + } + + const documented = Object.keys(contract.operations) as HttpMethod[]; + const missing = route.methods.filter((method) => !documented.includes(method)); + const orphaned = documented.filter((method) => !route.methods.includes(method)); + if (missing.length || orphaned.length) { + problems.push( + `${relativeRoute} and its contract disagree. Undocumented: ${missing.join(', ') || 'none'}. Documented but not exported: ${orphaned.join(', ') || 'none'}.`, + ); + } + + return { ...route, contractFile, contract }; + }); + + if (problems.length) throw new OpenApiContractError(problems); + return routes; +} diff --git a/packages/medusa-mcp/src/openapi/generate.ts b/packages/medusa-mcp/src/openapi/generate.ts new file mode 100644 index 000000000..091df2d6c --- /dev/null +++ b/packages/medusa-mcp/src/openapi/generate.ts @@ -0,0 +1,157 @@ +import path from 'node:path'; +import type { DiscoveredRoute } from './discover-routes'; +import type { ApiArea, HttpMethod, OpenApiOperation, SpecGap } from './types'; + +export type JsonSchema = Record; + +export type ToJsonSchema = (schema: unknown, io: 'input' | 'output') => JsonSchema; + +/** Matches the security Medusa's own admin operations declare. */ +const ADMIN_SECURITY = [{ api_token: [] }, { cookie_auth: [] }, { jwt_token: [] }]; + +interface ZodWithJsonSchema { + toJSONSchema: (schema: unknown, params: Record) => JsonSchema; +} + +/** + * Converts contract schemas with the Zod the indexed project itself resolves through + * `@medusajs/framework/zod`. The plugin may load a different Zod copy, and a schema has to be converted by the + * Zod that created it. + */ +export function projectZodJsonSchema(projectRoot: string): ToJsonSchema { + const zodModule = require(require.resolve('@medusajs/framework/zod', { paths: [projectRoot] })) as { + z?: ZodWithJsonSchema; + } & ZodWithJsonSchema; + const z = zodModule.z ?? zodModule; + + return (schema, io) => z.toJSONSchema(schema, { target: 'openapi-3.0', io, unrepresentable: 'throw' }); +} + +export function areaOf(openApiPath: string): ApiArea | undefined { + if (openApiPath === '/admin' || openApiPath.startsWith('/admin/')) return 'admin'; + if (openApiPath === '/store' || openApiPath.startsWith('/store/')) return 'store'; + return undefined; +} + +export interface CustomPaths { + paths: Record>>; + gaps: SpecGap[]; + problems: string[]; +} + +function buildOperation( + route: DiscoveredRoute, + tag: string, + area: ApiArea, + operation: OpenApiOperation, + toJsonSchema: ToJsonSchema, +): Record { + const parameters: Record[] = [...route.path.matchAll(/\{([^}]+)\}/g)].map((match) => ({ + name: match[1], + in: 'path', + required: true, + schema: { type: 'string' }, + })); + + if (operation.query) { + const query = toJsonSchema(operation.query, 'input'); + const properties = query.properties as Record | undefined; + if (query.type !== 'object' || !properties) { + throw new Error('query must be a Zod object schema'); + } + const required = new Set((query.required as string[] | undefined) ?? []); + for (const [name, schema] of Object.entries(properties)) { + parameters.push({ name, in: 'query', required: required.has(name), schema }); + } + } + + return { + operationId: operation.operationId, + summary: operation.summary, + ...(operation.description ? { description: operation.description } : {}), + tags: [tag], + ...(parameters.length ? { parameters } : {}), + ...(operation.body + ? { + requestBody: { + required: operation.bodyRequired ?? true, + content: { + [operation.bodyContentType ?? 'application/json']: { schema: toJsonSchema(operation.body, 'input') }, + }, + }, + } + : {}), + responses: Object.fromEntries( + Object.entries(operation.responses).map(([status, response]) => [ + status, + { + description: response.description, + ...(response.schema + ? { + content: { + [response.contentType ?? 'application/json']: { schema: toJsonSchema(response.schema, 'output') }, + }, + } + : {}), + }, + ]), + ), + ...(area === 'admin' ? { security: ADMIN_SECURITY } : {}), + 'x-medusa-mcp-source': 'custom', + }; +} + +/** Turns documented project routes into OpenAPI path items, split by area. */ +export function buildCustomPaths( + routes: DiscoveredRoute[], + toJsonSchema: ToJsonSchema, + apiDirectory: string, +): CustomPaths { + const result: CustomPaths = { paths: { admin: {}, store: {} }, gaps: [], problems: [] }; + const operationIds = new Map(); + + for (const route of routes) { + const { contract } = route; + if (!contract) continue; + + const area = areaOf(route.path); + for (const method of route.methods) { + const location = `${method} ${route.path}`; + if (contract.hidden || !area) { + result.gaps.push({ + method, + path: route.path, + source: 'app', + reason: contract.hidden ? 'hidden' : 'outside-admin-and-store', + }); + continue; + } + + const operation = contract.operations[method as HttpMethod]; + if (!operation) continue; + + const previous = operationIds.get(operation.operationId); + if (previous) { + result.problems.push(`operationId "${operation.operationId}" is used by both ${previous} and ${location}`); + continue; + } + operationIds.set(operation.operationId, location); + + try { + result.paths[area][route.path] ??= {}; + result.paths[area][route.path][method.toLowerCase()] = buildOperation( + route, + contract.tag, + area, + operation, + toJsonSchema, + ); + } catch (error) { + const contractFile = route.contractFile ? path.relative(apiDirectory, route.contractFile) : route.routeFile; + result.problems.push(`${location} in ${contractFile}: ${(error as Error).message}`); + } + } + } + + return result; +} diff --git a/packages/medusa-mcp/src/openapi/index.ts b/packages/medusa-mcp/src/openapi/index.ts new file mode 100644 index 000000000..71acf80f7 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/index.ts @@ -0,0 +1,10 @@ +export { + type ApiSpec, + type BuildApiSpecOptions, + buildApiSpec, + countOperations, + type UnscannedPlugin, +} from './build-spec'; +export { loadCoreSpecs, projectMedusaVersion } from './core-spec'; +export { type DiscoveredRoute, OpenApiContractError } from './discover-routes'; +export type { ApiArea, HttpMethod, OpenApiDocument, OpenApiOperation, OpenApiRouteContract, SpecGap } from './types'; diff --git a/packages/medusa-mcp/src/openapi/merge.ts b/packages/medusa-mcp/src/openapi/merge.ts new file mode 100644 index 000000000..7aa47804b --- /dev/null +++ b/packages/medusa-mcp/src/openapi/merge.ts @@ -0,0 +1,65 @@ +import { compareCodeUnits } from './compare'; +import type { OpenApiDocument } from './types'; + +const OPERATION_KEYS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace']); + +export interface MergeResult { + document: OpenApiDocument; + problems: string[]; +} + +/** + * Adds custom path items to a core Medusa document. A custom operation on a path and method Medusa already + * defines is an error, unless that operation key (`post /admin/promotions/{id}`) is listed in `overrides`. + */ +export function mergeDocuments( + core: OpenApiDocument, + custom: Record>, + overrides: ReadonlySet = new Set(), +): MergeResult { + const problems: string[] = []; + const paths = structuredClone(core.paths); + + for (const [routePath, customItem] of Object.entries(custom)) { + const item = (paths[routePath] ??= {}); + for (const [key, value] of Object.entries(customItem)) { + const operationKey = `${key} ${routePath}`; + const isOverride = overrides.has(operationKey); + if (key in item && !isOverride) { + problems.push(`${key.toUpperCase()} ${routePath} is already defined by Medusa's core spec`); + continue; + } + item[key] = isOverride + ? { ...(value as Record), 'x-medusa-overridden-by-custom-route': true } + : value; + } + } + + const operationIds = new Map(); + for (const [routePath, item] of Object.entries(paths)) { + for (const [key, operation] of Object.entries(item)) { + const operationId = OPERATION_KEYS.has(key) ? (operation as { operationId?: string }).operationId : undefined; + if (!operationId) continue; + const location = `${key.toUpperCase()} ${routePath}`; + const previous = operationIds.get(operationId); + if (previous) problems.push(`operationId "${operationId}" is used by both ${previous} and ${location}`); + operationIds.set(operationId, location); + } + } + + const tags = structuredClone(core.tags ?? []); + const tagNames = new Set(tags.map((tag) => tag.name)); + for (const item of Object.values(paths)) { + for (const [key, operation] of Object.entries(item)) { + if (!OPERATION_KEYS.has(key)) continue; + for (const name of (operation as { tags?: string[] }).tags ?? []) { + if (tagNames.has(name)) continue; + tagNames.add(name); + tags.push({ name }); + } + } + } + tags.sort((left, right) => compareCodeUnits(left.name, right.name)); + + return { document: { ...core, paths, tags }, problems }; +} diff --git a/packages/medusa-mcp/src/openapi/types.ts b/packages/medusa-mcp/src/openapi/types.ts new file mode 100644 index 000000000..631daae32 --- /dev/null +++ b/packages/medusa-mcp/src/openapi/types.ts @@ -0,0 +1,57 @@ +/** Every HTTP method a Medusa route file can export. */ +export const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const; + +export type HttpMethod = (typeof HTTP_METHODS)[number]; + +export const API_AREAS = ['admin', 'store'] as const; + +export type ApiArea = (typeof API_AREAS)[number]; + +export interface OpenApiResponse { + description: string; + /** A Zod schema from `@medusajs/framework/zod`. */ + schema?: unknown; + contentType?: 'application/json' | 'text/csv' | 'text/html'; +} + +export interface OpenApiOperation { + operationId: string; + summary: string; + description?: string; + /** A Zod schema for the request body. */ + body?: unknown; + bodyRequired?: boolean; + bodyContentType?: 'application/json' | 'multipart/form-data'; + /** A Zod object schema for the query string. */ + query?: unknown; + responses: Record; +} + +/** + * The contract a route publishes in an `openapi.ts` file next to its `route.ts`. It must document every HTTP + * method the route exports, and nothing else. + */ +export interface OpenApiRouteContract { + /** Keep the route out of the published spec, for internal or unsafe routes. */ + hidden?: boolean; + tag: string; + operations: Partial>; +} + +export interface OpenApiDocument { + openapi: string; + info: { title: string; version: string; [key: string]: unknown }; + paths: Record>; + tags?: { name: string; [key: string]: unknown }[]; + components?: Record>; + [key: string]: unknown; +} + +/** An operation Medusa serves that the published spec does not describe. */ +export interface SpecGap { + method: HttpMethod; + path: string; + /** `app` for the project's own routes, otherwise the plugin package name. */ + source: string; + reason: 'undocumented-plugin-route' | 'outside-admin-and-store' | 'hidden'; +} diff --git a/packages/medusa-mcp/src/types.ts b/packages/medusa-mcp/src/types.ts new file mode 100644 index 000000000..09018b451 --- /dev/null +++ b/packages/medusa-mcp/src/types.ts @@ -0,0 +1,6 @@ +export interface MedusaMcpPluginOptions { + /** Public origin of this Medusa server, used as the OAuth issuer and the MCP resource URL base. */ + issuer?: string; + /** Extra `METHOD /path` operation keys to block, added to the plugin's built-in blocklist. */ + blockedOperations?: string[]; +} diff --git a/packages/medusa-mcp/tsconfig.json b/packages/medusa-mcp/tsconfig.json new file mode 100644 index 000000000..819eeee47 --- /dev/null +++ b/packages/medusa-mcp/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "target": "ES2022", + "esModuleInterop": true, + "module": "NodeNext", + "moduleResolution": "NodeNext", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "skipLibCheck": true, + "skipDefaultLibCheck": true, + "declaration": true, + "sourceMap": false, + "inlineSourceMap": true, + "outDir": "./.medusa/server", + "rootDir": "./", + "jsx": "react-jsx", + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "checkJs": false, + "strict": true, + "incremental": true, + "isolatedModules": true, + "types": [ + "node", + "jest" + ] + }, + "include": [ + "src/**/*", + "src/api/.well-known/**/*" + ], + "exclude": [ + "node_modules", + ".medusa", + "**/__tests__/**" + ] +} diff --git a/scripts/docker-workspace-packages.mjs b/scripts/docker-workspace-packages.mjs new file mode 100644 index 000000000..563bc47cf --- /dev/null +++ b/scripts/docker-workspace-packages.mjs @@ -0,0 +1,63 @@ +// Lets a production Docker image install workspace packages such as @lambdacurry/medusa-mcp. +// +// The runner stage installs an app's built package.json on its own, outside the monorepo, so `workspace:` +// dependencies have nothing to resolve to. A symlinked workspace would not work anyway: the package would resolve +// peers like @medusajs/framework from its own folder, where production installs leave none. So the installer stage +// packs each workspace package into a tarball, and the runner points the dependency at it, which installs the +// package into the app's node_modules the same way npm-published plugins are installed. The root manifest's +// `resolutions` are carried over too, since they pin versions (all of @medusajs/*) that the app manifest omits. +// +// node scripts/docker-workspace-packages.mjs pack (repo root, after building) +// node scripts/docker-workspace-packages.mjs use +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; + +const [mode, outDir, packageJsonPath] = process.argv.slice(2); +const indexFile = (dir) => path.join(dir, 'index.json'); + +/** The concrete files a package.json `exports` field points to; wildcard targets are skipped. */ +function exportTargets(exports) { + if (typeof exports === 'string') return exports.includes('*') ? [] : [exports]; + if (exports && typeof exports === 'object') return Object.values(exports).flatMap(exportTargets); + return []; +} + +if (mode === 'pack' && outDir) { + mkdirSync(outDir, { recursive: true }); + const packages = {}; + for (const dir of existsSync('packages') ? readdirSync('packages') : []) { + const manifest = path.join('packages', dir, 'package.json'); + if (!existsSync(manifest)) continue; + const { name, exports } = JSON.parse(readFileSync(manifest, 'utf8')); + const tarball = path.resolve(outDir, `${dir}.tgz`); + execFileSync('yarn', ['workspace', name, 'pack', '--out', tarball], { stdio: 'inherit' }); + // A package whose build output was left out of the tarball still installs, and only fails when Medusa boots. + const packed = new Set(execFileSync('tar', ['-tzf', tarball], { encoding: 'utf8' }).split('\n')); + const missing = exportTargets(exports).filter((target) => !packed.has(path.posix.join('package', target))); + if (missing.length > 0) throw new Error(`${name} was packed without its exports: ${missing.join(', ')}`); + packages[name] = tarball; + } + const { resolutions = {} } = JSON.parse(readFileSync('package.json', 'utf8')); + writeFileSync(indexFile(outDir), `${JSON.stringify({ packages, resolutions }, null, 2)}\n`); + console.log(`Packed ${Object.keys(packages).length} workspace package(s): ${Object.keys(packages).join(', ') || 'none'}`); +} else if (mode === 'use' && outDir && packageJsonPath) { + const { packages, resolutions } = JSON.parse(readFileSync(indexFile(outDir), 'utf8')); + const manifest = JSON.parse(readFileSync(packageJsonPath, 'utf8')); + const rewritten = []; + for (const field of ['dependencies', 'optionalDependencies']) { + for (const [name, spec] of Object.entries(manifest[field] ?? {})) { + if (!String(spec).startsWith('workspace:')) continue; + if (!packages[name]) throw new Error(`${name} is a workspace dependency, but no packed tarball exists for it`); + manifest[field][name] = `file:${packages[name]}`; + rewritten.push(name); + } + } + manifest.resolutions = { ...resolutions, ...manifest.resolutions }; + writeFileSync(packageJsonPath, `${JSON.stringify(manifest, null, 2)}\n`); + console.log(`Using packed tarballs for: ${rewritten.join(', ') || 'none'}`); + console.log(`Applied ${Object.keys(manifest.resolutions).length} resolution(s) from the root and app manifests`); +} else { + console.error('Usage: docker-workspace-packages.mjs pack | use '); + process.exit(1); +} diff --git a/turbo.json b/turbo.json index ad9c1c8fb..c102c0063 100644 --- a/turbo.json +++ b/turbo.json @@ -5,7 +5,7 @@ "build": { "dependsOn": ["^build"], "inputs": ["$TURBO_DEFAULT$", ".env*"], - "outputs": ["build", "dist"] + "outputs": ["build", "dist", ".medusa/**"] }, "lint": { "dependsOn": ["^lint"] @@ -18,12 +18,18 @@ }, "dev": { "cache": false, - "persistent": true + "persistent": true, + "dependsOn": ["^build"] }, "medusa:init": { - "cache": false + "cache": false, + "dependsOn": ["^build"] }, "typecheck": { + "dependsOn": ["^build"] + }, + "test:unit": { + "dependsOn": ["^build"] } } } diff --git a/yarn.lock b/yarn.lock index 8783a39f5..b9c7a66a6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2170,6 +2170,15 @@ __metadata: languageName: node linkType: hard +"@hono/node-server@npm:^1.19.9 || ^2.1.3": + version: 2.1.6 + resolution: "@hono/node-server@npm:2.1.6" + peerDependencies: + hono: ^4 || ^5.0.0-0 + checksum: 10c0/bb57a4e00f193b37f1e7c8a4b8206914ab3f6073d8e7da7ca4b005f0205d89ef9cd0bdb783a4b59869a4c9211f1567f3e0717f31e92704ed7b1801a33d3252d3 + languageName: node + linkType: hard + "@hookform/error-message@npm:^2.0.1": version: 2.0.1 resolution: "@hookform/error-message@npm:2.0.1" @@ -2956,6 +2965,30 @@ __metadata: languageName: node linkType: hard +"@lambdacurry/medusa-mcp@workspace:*, @lambdacurry/medusa-mcp@workspace:packages/medusa-mcp": + version: 0.0.0-use.local + resolution: "@lambdacurry/medusa-mcp@workspace:packages/medusa-mcp" + dependencies: + "@medusajs/cli": "npm:2.22.1" + "@medusajs/framework": "npm:2.22.1" + "@medusajs/medusa": "npm:2.22.1" + "@modelcontextprotocol/node": "npm:2.1.2" + "@modelcontextprotocol/server": "npm:2.4.0" + "@swc/core": "npm:^1.16.20" + "@swc/jest": "npm:^0.2.39" + "@types/jest": "npm:^30.0.0" + "@types/node": "npm:26.6.5" + ajv: "npm:^8.13.0" + ajv-formats: "npm:^3.0.1" + jest: "npm:^30.5.2" + ts-node: "npm:^10.9.2" + typescript: "npm:^6.0.3" + peerDependencies: + "@medusajs/framework": ^2.22.1 + "@medusajs/medusa": ^2.22.1 + languageName: unknown + linkType: soft + "@lambdacurry/medusa-plugins-sdk@npm:0.0.5": version: 0.0.5 resolution: "@lambdacurry/medusa-plugins-sdk@npm:0.0.5" @@ -4191,6 +4224,37 @@ __metadata: languageName: node linkType: hard +"@modelcontextprotocol/core@npm:2.4.0": + version: 2.4.0 + resolution: "@modelcontextprotocol/core@npm:2.4.0" + dependencies: + zod: "npm:^4.2.0" + checksum: 10c0/4dd07f18c7eee3f3cf7bcea9a7dd11799f13ce2255fda9ae77aff9978a21d16ee4026f63e5a3e13d5d91209acc3e7d6b97d459c1ff1b78f3b872eb0597b3dd53 + languageName: node + linkType: hard + +"@modelcontextprotocol/node@npm:2.1.2": + version: 2.1.2 + resolution: "@modelcontextprotocol/node@npm:2.1.2" + dependencies: + "@hono/node-server": "npm:^1.19.9 || ^2.1.3" + hono: "npm:^4.11.4" + peerDependencies: + "@modelcontextprotocol/server": ^2.4.0 + checksum: 10c0/0aebe06454b9e583658f702fd1c8af4eddb91f91a7b5dd7b7ffdbe19d0b8503400e2cbcf8b6511c14767fde5ffcfc73154921c52644269b5e4eb41d600be2594 + languageName: node + linkType: hard + +"@modelcontextprotocol/server@npm:2.4.0": + version: 2.4.0 + resolution: "@modelcontextprotocol/server@npm:2.4.0" + dependencies: + "@modelcontextprotocol/core": "npm:2.4.0" + zod: "npm:^4.2.0" + checksum: 10c0/e52966e6f115296c6dbfd08550e81773f5f71fb4809c7411b11fcc619b3bd621b07f296a5571de777ea2351eca7003e6b3f4d172fe8c21563be1205b1ee4f0ec + languageName: node + linkType: hard + "@msgpackr-extract/msgpackr-extract-darwin-arm64@npm:3.0.3": version: 3.0.3 resolution: "@msgpackr-extract/msgpackr-extract-darwin-arm64@npm:3.0.3" @@ -11779,7 +11843,7 @@ __metadata: languageName: node linkType: hard -"ajv-formats@npm:~3.0.1": +"ajv-formats@npm:^3.0.1, ajv-formats@npm:~3.0.1": version: 3.0.1 resolution: "ajv-formats@npm:3.0.1" dependencies: @@ -11817,6 +11881,18 @@ __metadata: languageName: node linkType: hard +"ajv@npm:^8.13.0": + version: 8.20.0 + resolution: "ajv@npm:8.20.0" + dependencies: + fast-deep-equal: "npm:^3.1.3" + fast-uri: "npm:^3.0.1" + json-schema-traverse: "npm:^1.0.0" + require-from-string: "npm:^2.0.2" + checksum: 10c0/5df9a1c8f83863cde1bd3a9ddb426f599718f88e3dc9153616c79fb28e0be455335830d7f21d745576519f057b371352daa31047b6a33d7036fe08777d60cf2a + languageName: node + linkType: hard + "ajv@npm:~8.13.0": version: 8.13.0 resolution: "ajv@npm:8.13.0" @@ -14763,6 +14839,13 @@ __metadata: languageName: node linkType: hard +"hono@npm:^4.11.4": + version: 4.13.17 + resolution: "hono@npm:4.13.17" + checksum: 10c0/63a2d834f0cf1b3858d5872883589ea48522567251bc4eb62c5f17e47cc6f793b2201150bca4822374165e92dbdcc8d3573443c7cdb8a340a933dce39e6df34d + languageName: node + linkType: hard + "hosted-git-info@npm:^4.0.2": version: 4.1.0 resolution: "hosted-git-info@npm:4.1.0" @@ -16632,6 +16715,7 @@ __metadata: version: 0.0.0-use.local resolution: "medusa@workspace:apps/medusa" dependencies: + "@lambdacurry/medusa-mcp": "workspace:*" "@lambdacurry/medusa-product-reviews": "npm:1.4.0" "@medusajs/admin-sdk": "npm:2.22.1" "@medusajs/cli": "npm:2.22.1" @@ -21302,7 +21386,7 @@ __metadata: languageName: node linkType: hard -"zod@npm:4.6.7": +"zod@npm:4.6.7, zod@npm:^4.2.0": version: 4.6.7 resolution: "zod@npm:4.6.7" checksum: 10c0/4ce2eb14034317b7254e347ca37b5ad591cf8333147030cf05b9b5d31692d45073f7f2747aa50cf8c6b29012194d2b22978cecc89969cf34a0d18e89d0ee7d7b