Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions apps/medusa/integration-tests/http/mcp-write.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ medusaIntegrationTestRunner({
expect(preview.structuredContent).toEqual({
operation: 'POST /admin/products/{id}',
dry_run: true,
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('Nothing was sent to Medusa'),
changes: [
{ field: 'description', current: 'Smooth and sweet.', proposed: 'Rich, chocolatey, and caffeine-free.' },
],
Expand All @@ -110,6 +113,11 @@ medusaIntegrationTestRunner({
});
expect(rejected.isError).toBe(true);
expect(rejected.content[0].text).toContain('/description must be string');
expect(rejected.structuredContent).toMatchObject({
operation: 'POST /admin/products/{id}',
error: { phase: 'schema', problems: [expect.stringContaining('/description must be string')] },
spec_revision: expect.any(String),
});
expect((await product()).description).toBe('Smooth and sweet.');
});

Expand Down Expand Up @@ -202,6 +210,78 @@ medusaIntegrationTestRunner({
}
});

it("says a dry run cannot predict business rules, and returns Medusa's rejection in a form an agent can act on", async () => {
// From the live ChatGPT smoke test: the published schema makes `options` optional, but Medusa's create workflow
// rejects a product without options. No schema can see that rule, so the dry run must not imply acceptance and
// the real rejection must say what to fix.
const products = getContainer().resolve(Modules.PRODUCT);
const before = await products.listProducts({}, { select: ['id'] });
const draft = { title: 'MCP smoke test', handle: 'mcp-smoke-test', status: 'draft' };

const preview = await callTool(api, fullToken, 'write_api', {
operation: 'POST /admin/products',
body: draft,
dry_run: true,
});
expect(preview.isError).toBeFalsy();
expect(preview.structuredContent).toEqual({
operation: 'POST /admin/products',
dry_run: true,
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('the real call can still be rejected'),
proposed: draft,
current: null,
note: expect.stringContaining('no current values'),
});

const rejected = await callTool(api, fullToken, 'write_api', { operation: 'POST /admin/products', body: draft });
expect(rejected.isError).toBe(true);
expect(rejected.structuredContent).toMatchObject({
operation: 'POST /admin/products',
status: 400,
error: {
phase: 'medusa',
status: 400,
type: 'invalid_data',
message: expect.stringContaining('Product options are not provided'),
hint: expect.stringContaining('business rules'),
},
spec_revision: expect.any(String),
});

const created = await callTool(api, fullToken, 'write_api', {
operation: 'POST /admin/products',
body: {
...draft,
options: [{ title: 'Format', values: ['Test'] }],
variants: [{ title: 'Test', sku: 'MCP-SMOKE', options: { Format: 'Test' }, prices: [] }],
},
});
expect(created.isError).toBeFalsy();
const createdId = created.structuredContent?.body.product.id as string;

const deleted = await callTool(api, fullToken, 'delete_api', {
operation: 'DELETE /admin/products/{id}',
path_params: { id: createdId },
});
expect(deleted.structuredContent).toMatchObject({ status: 200, body: { id: createdId, deleted: true } });
expect(await products.listProducts({ handle: 'mcp-smoke-test' })).toHaveLength(0);
expect(await products.listProducts({}, { select: ['id'] })).toHaveLength(before.length);
});

it('says when a dry run checked nothing against the schema', async () => {
const preview = await callTool(api, fullToken, 'write_api', { operation: 'POST /admin/products', dry_run: true });
expect(preview.isError).toBeFalsy();
expect(preview.structuredContent).toMatchObject({
executed: false,
schema_check: 'no_body',
limits: expect.stringContaining('No body was given, so nothing was checked'),
proposed: null,
});
expect(preview.structuredContent?.limits).not.toContain('matches the published schema');
});

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', {
Expand All @@ -213,6 +293,9 @@ medusaIntegrationTestRunner({
expect(preview.structuredContent).toEqual({
operation: 'POST /admin/products/{id}',
dry_run: true,
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('Nothing was sent to Medusa'),
proposed: { description: 'Proposed.' },
current: null,
note: 'Current values need the mcp:read scope.',
Expand Down
8 changes: 7 additions & 1 deletion packages/medusa-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,15 @@ Status: in development on `feat/medusa-mcp`. Design and plan: Arbor thread DEM-1
| `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. |
| `write_api` | `mcp:write` | Calls a POST, PUT, or PATCH after validating the body. `dry_run` previews current vs proposed values without sending anything. |
| `delete_api` | `mcp:delete` | Calls a DELETE. Marked destructive. |

A dry run checks the body against the published spec only. Medusa enforces business rules in its workflows, which no
spec describes: creating a product without `options` passes the schema and fails in Medusa's create workflow. So every
preview says it was not executed and whether the body was checked (`schema_check`), and a failed call returns an `error` object with the phase (`schema` or `medusa`),
Medusa's `type`, `code`, and `message`, a hint for the status, and the spec revision, so an agent can correct the body
and call again.

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,
Expand Down
122 changes: 90 additions & 32 deletions packages/medusa-mcp/src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,51 @@ function ok(data: Record<string, unknown>): 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 fail(message: string, data?: Record<string, unknown>): ToolResult {
return { content: [{ type: 'text', text: message }], ...(data ? { structuredContent: data } : {}), isError: true };
}

/** Whether a write's body was checked against the published schema: it passed, there was no body, or the operation
* publishes no JSON body schema. A failed check never reaches a dry run. */
type SchemaCheck = 'passed' | 'no_body' | 'no_schema';

const SCHEMA_CHECKED: Record<SchemaCheck, string> = {
passed: 'The body matches the published schema',
no_body: 'No body was given, so nothing was checked against the schema',
no_schema: 'This operation publishes no body schema, so the body was not checked',
};

/** What a dry run proves and what it cannot, sent with every preview so an agent never reads one as acceptance. */
function dryRunLimits(check: SchemaCheck): string {
return (
`Nothing was sent to Medusa. ${SCHEMA_CHECKED[check]}, but Medusa checks its business rules only when the call ` +
'runs, so the real call can still be rejected.'
);
}

/** Advice for an agent on a failed call, by status. Medusa's own message says what to change. */
function errorHint(status: number): string {
if (status === 400) {
return 'Medusa rejected the request. Its business rules can require more than the published schema does, so correct the body using the message, then call again.';
}
if (status === 401 || status === 403) return 'The signed-in admin is not allowed to do this.';
if (status === 404) return 'Medusa found no such resource. Check the path parameters.';
if (status === 409) return 'The request conflicts with current data, for example a duplicate handle.';
if (status >= 500) {
return 'Medusa failed while handling the request. A write may have partly applied, so read the resource before retrying.';
}
return 'Medusa did not accept the request.';
}

/** Medusa's error fields (`type`, `code`, `message`), when the body has them. */
function medusaError(body: unknown): Record<string, string> {
if (!body || typeof body !== 'object') return {};
const fields: Record<string, string> = {};
for (const key of ['type', 'code', 'message'] as const) {
const value = (body as Record<string, unknown>)[key];
if (typeof value === 'string') fields[key] = value;
}
return fields;
}

function oauth(scope: 'mcp:read' | 'mcp:write' | 'mcp:delete') {
Expand Down Expand Up @@ -104,10 +147,19 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
return operation;
};

const resultOf = (operation: CatalogOperation, result: ExecutionResult | ToolResult): ToolResult =>
'content' in result
? result
: { ...ok({ operation: operation.operation, ...result }), isError: result.status >= 400 };
const specRevision = catalog.spec.revision.slice(0, 12);

const resultOf = (operation: CatalogOperation, result: ExecutionResult | ToolResult): ToolResult => {
if ('content' in result) return result;
if (result.status < 400) return ok({ operation: operation.operation, ...result });
const error = {
phase: 'medusa',
status: result.status,
...medusaError(result.body),
hint: errorHint(result.status),
};
return { ...ok({ operation: operation.operation, ...result, error, spec_revision: specRevision }), isError: true };
};

server.registerTool(
'search_api',
Expand Down Expand Up @@ -207,7 +259,7 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
{
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.',
"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 check the body against the schema and see current and proposed values without changing anything. A dry run does not run Medusa's business rules, so the real call can still be rejected; a rejection comes back with Medusa's message to correct the body.",
inputSchema: fromJsonSchema({
type: 'object',
properties: {
Expand All @@ -217,7 +269,7 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
body: { type: 'object', description: 'The JSON request body.' },
dry_run: {
type: 'boolean',
description: 'Validate and preview the change without making it.',
description: 'Check the body against the schema and preview the change without sending it to Medusa.',
default: false,
},
},
Expand All @@ -241,17 +293,26 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
);
}
const schema = requestBody?.content?.['application/json']?.schema;
const schemaCheck: SchemaCheck = !schema ? 'no_schema' : args.body === undefined ? 'no_body' : 'passed';
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 fail(`The body does not match ${operation.operation}:\n- ${problems.join('\n- ')}`, {
operation: operation.operation,
error: {
phase: 'schema',
problems,
hint: 'Nothing was sent to Medusa. Fix the body to match describe_api, then call again.',
},
spec_revision: specRevision,
});
}
}

return audited(args, async () => {
if (args.dry_run) {
const preview = await dryRun(operation, args);
const preview = await dryRun(operation, args, schemaCheck);
await target.audit({ ...auditBase(args), outcome: 'dry_run' });
return preview;
}
Expand Down Expand Up @@ -311,35 +372,32 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
}

/**
* 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.
* Previews a write without sending it. For an operation on one resource (its path ends in a path parameter), shows
* the current value of each top-level body field next to the proposed one, by reading the same path with GET. A
* create or action has no current values, so only the proposal is shown. 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<ToolResult> {
async function dryRun(operation: CatalogOperation, args: ToolArgs, schemaCheck: SchemaCheck): Promise<ToolResult> {
const fields = Object.keys((args.body as Record<string, unknown> | undefined) ?? {});
const preview = {
operation: operation.operation,
dry_run: true,
executed: false,
schema_check: schemaCheck,
limits: dryRunLimits(schemaCheck),
};
const proposalOnly = (note: string) => ok({ ...preview, proposed: args.body ?? null, current: null, note });

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 });
if (!/\{[^}]+\}$/.test(operation.path) || !read || read.blocked_by) {
return proposalOnly('This operation creates or acts on a resource, so there are no current values to compare.');
}
if (!target.scopes.includes('mcp:read')) return proposalOnly('Current values need the mcp:read scope.');

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,
};
}
if (current.status >= 400) return resultOf(read, current);

const resource = Object.values((current.body as Record<string, unknown>) ?? {}).find(
(value) => value && typeof value === 'object' && !Array.isArray(value),
Expand All @@ -349,7 +407,7 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
current: resource?.[field] ?? null,
proposed: (args.body as Record<string, unknown>)[field],
}));
return ok({ operation: operation.operation, dry_run: true, changes });
return ok({ ...preview, changes });
}

return server;
Expand Down
Loading