Repository navigation
Barrio MCP: OpenAPI-driven MCP server inside Medusa, with Medusa-hosted OAuth #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
36 commits
Select commit
Hold shift + click to select a range
be08969
Add the medusa-mcp plugin skeleton as a workspace package
jaruesink a255016
Build the published API spec from pinned core specs and route contracts
jaruesink 31718f9
Declare the plugin options as an interface
jaruesink 6f6848b
MCP slice 0: medusa-mcp plugin skeleton (#91)
jaruesink eb0184e
Merge feat/medusa-mcp (slice 0 merged as #91) into slice 1
jaruesink bbc8df1
Declare OpenAPI object shapes as interfaces
jaruesink e8b8e4e
Keep Jest from running compiled test copies in .medusa
jaruesink 5b01817
Add the OAuth module, discovery metadata, and client registration
jaruesink afb03c8
Make the spec revision locale-independent and plugin scans non-fatal
jaruesink 18f5bcc
Merge slice 1 review fixes into slice 2a
jaruesink eddf37e
Add sign-in, consent, and the token endpoint to the OAuth server
jaruesink 6de7893
Close the IP-literal SSRF gap in client metadata fetches
jaruesink 6398669
Merge slice 2a review fixes into slice 2b
jaruesink ac735a1
Serve the MCP endpoint with search, describe, and read tools
jaruesink bd181b6
Add write_api and delete_api with validation, dry runs, and audit logs
jaruesink 499dce5
Make the MCP demo reproducible locally, from agent to storefront
jaruesink 542275f
Stop asserting Node's module-resolution wording in the unscanned-plug…
jaruesink 737fd9a
MCP slice 1: build the published API spec from pinned core specs and …
jaruesink 1815c3d
Merge feat/medusa-mcp (slice 1 merged as #92) into slice 2a
jaruesink 26f31b4
MCP slice 2a: OAuth module, discovery metadata, and client registrati…
jaruesink de25b0b
Merge feat/medusa-mcp (slice 2a merged as #93) into slice 2b
jaruesink 41660df
Let browsers finish consent, bind form tokens to purpose, and add CORS
jaruesink 9618ae3
MCP slice 2b: sign-in, consent, and the token endpoint (#94)
jaruesink 09b3ef9
Merge feat/medusa-mcp (slice 2b merged as #94) into slice 3
jaruesink 6d3c27f
Close a dot-segment bypass of the MCP blocklist
jaruesink 63f5f92
Make the truncation test split a character at the 64 KiB cut
jaruesink d3e64d5
MCP slice 3: the /mcp endpoint with search, describe, and read tools …
jaruesink 3e3a2cf
Merge feat/medusa-mcp (slice 3 merged as #95) into slice 4
jaruesink 0f6c1e0
Audit every write and delete attempt, and keep dry runs inside the re…
jaruesink 9647064
MCP slice 4: write_api and delete_api with validation, dry runs, and …
jaruesink 64c5032
Merge feat/medusa-mcp (slice 4 merged as #96) into slice 5
jaruesink a539da6
Require replacing the seeded admins before tunneling, and harden two …
jaruesink 34cbec9
Refuse a public MCP server signed with Medusa's default secrets
jaruesink 3ca7bfc
Sign OAuth forms with a per-process key, not Medusa's cookie secret
jaruesink d7ba8cc
MCP slice 5: reproducible local demo, from agent to storefront (#97)
jaruesink 3799371
MCP slice 6: ship the plugin in the production Medusa image (#99)
jaruesink File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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/<version>`. After upgrading | ||
| `@medusajs/medusa`, run `yarn workspace @lambdacurry/medusa-mcp fetch-core-specs <version>`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| AGENTS.md |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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> | [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<Response> { | ||
| 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<string> { | ||
| 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<string, unknown>) { | ||
| 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); | ||
| }); | ||
| } | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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('<p>Connected</p>'); | ||
| }); | ||
| await new Promise<void>((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(); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep the cache fresh before testing invalidation.
The cache is populated at Line 94, before OAuth, search, reads, and preview requests. Those steps can consume the ten-second TTL. The five-second assertion window therefore does not exclude normal cache expiry. With the supplied stale-while-revalidate behavior, retries can show the updated description even when the revalidation subscriber is broken.
Populate a fresh cache entry immediately before the write. Ensure its remaining TTL exceeds the write and assertion window, or use a controlled longer TTL for this test.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fair point about test strength. Deferring: the live demo exercises the same path, and tightening the test needs a controllable TTL.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jaruesink Understood. The live demo exercises the path, though the automated test can still pass through cache expiry.
Would you like me to open a follow-up issue for a controllable TTL and a stronger invalidation test?
Learnings used
You are interacting with an AI system.