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
70 changes: 69 additions & 1 deletion apps/medusa/integration-tests/http/mcp-write.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ medusaIntegrationTestRunner({
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('Nothing was sent to Medusa'),
spec_revision: expect.any(String),
changes: [
{ field: 'description', current: 'Smooth and sweet.', proposed: 'Rich, chocolatey, and caffeine-free.' },
],
Expand Down Expand Up @@ -149,7 +150,61 @@ medusaIntegrationTestRunner({
operation: 'DELETE /admin/products/{id}',
path_params: { id: productId },
});
expect(deleted.structuredContent).toMatchObject({ status: 200, body: { id: productId, deleted: true } });
expect(deleted.structuredContent).toMatchObject({
status: 200,
body: { id: productId, deleted: true },
precheck: { operation: 'GET /admin/products/{id}', found: true },
spec_revision: expect.any(String),
});
await expect(product()).rejects.toThrow();
});

it('does not send a DELETE for a resource that does not exist, since Medusa would answer deleted: true', async () => {
// Medusa's DELETE route reports success for any id, and GET /admin/collections/{id} answers 200 {} for a missing
// collection, so both a 404 and an empty body must stop the delete.
const missingProduct = await callTool(api, fullToken, 'delete_api', {
operation: 'DELETE /admin/products/{id}',
path_params: { id: 'prod_does_not_exist' },
});
expect(missingProduct.isError).toBe(true);
expect(missingProduct.structuredContent).toMatchObject({
operation: 'DELETE /admin/products/{id}',
executed: false,
error: {
phase: 'precheck',
check: 'GET /admin/products/{id}',
status: 404,
hint: expect.stringContaining('Nothing was deleted'),
},
});
expect(missingProduct.content[0].text).toContain('The DELETE was not sent.');

const [collection] = await getContainer()
.resolve(Modules.PRODUCT)
.createProductCollections([{ title: 'MCP check collection', handle: 'mcp-check-collection' }]);
const first = await callTool(api, fullToken, 'delete_api', {
operation: 'DELETE /admin/collections/{id}',
path_params: { id: collection.id },
});
expect(first.structuredContent).toMatchObject({ status: 200, precheck: { found: true } });
const again = await callTool(api, fullToken, 'delete_api', {
operation: 'DELETE /admin/collections/{id}',
path_params: { id: collection.id },
});
expect(again.structuredContent).toMatchObject({
executed: false,
error: { phase: 'precheck', check: 'GET /admin/collections/{id}', status: 200 },
});

// A GET too large to read whole cannot show whether the resource exists, so the DELETE goes ahead unchecked.
await getContainer()
.resolve(Modules.PRODUCT)
.updateProducts(productId, { description: 'x'.repeat(80 * 1024) });
const unchecked = await callTool(api, fullToken, 'delete_api', {
operation: 'DELETE /admin/products/{id}',
path_params: { id: productId },
});
expect(unchecked.structuredContent).toMatchObject({ status: 200, body: { deleted: true }, precheck: null });
await expect(product()).rejects.toThrow();
});

Expand All @@ -159,12 +214,22 @@ medusaIntegrationTestRunner({
body: { title: 'agent key', type: 'secret' },
});
expect(blocked.content[0].text).toContain('blocked for agents');
expect(blocked.structuredContent).toMatchObject({
operation: 'POST /admin/api-keys',
error: {
phase: 'refused',
message: expect.stringContaining('blocked for agents'),
hint: 'Nothing was sent to Medusa.',
},
spec_revision: expect.any(String),
});

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');
expect(wrongTool.structuredContent?.error).toMatchObject({ phase: 'refused' });
});

it('audits refused, executed, and previewed write attempts with their path parameters', async () => {
Expand Down Expand Up @@ -230,6 +295,7 @@ medusaIntegrationTestRunner({
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('the real call can still be rejected'),
spec_revision: expect.any(String),
proposed: draft,
current: null,
note: '"Create Product": current values are shown only for a write to a path that ends in a resource id, so only the proposal is shown.',
Expand Down Expand Up @@ -285,6 +351,7 @@ medusaIntegrationTestRunner({
operation: 'POST /admin/products/export',
dry_run: true,
});
expect(action.structuredContent?.schema_check).toBe('no_body');
expect(action.structuredContent?.note).toBe(
'"Export Products": current values are shown only for a write to a path that ends in a resource id, so only the proposal is shown.',
);
Expand All @@ -304,6 +371,7 @@ medusaIntegrationTestRunner({
executed: false,
schema_check: 'passed',
limits: expect.stringContaining('Nothing was sent to Medusa'),
spec_revision: expect.any(String),
proposed: { description: 'Proposed.' },
current: null,
note: 'Current values need the mcp:read scope.',
Expand Down
25 changes: 17 additions & 8 deletions packages/medusa-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,31 @@ Status: in development on `feat/medusa-mcp`. Design and plan: Arbor thread DEM-1
| `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 without sending anything. |
| `delete_api` | `mcp:delete` | Calls a DELETE. Marked destructive. |
| `delete_api` | `mcp:delete` | Calls a DELETE. Marked destructive. When the same path has a GET, checks the resource exists first, because Medusa answers `deleted: true` for any id. |

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` when Medusa sends them (`code` is often absent), and a hint for the status, so
an agent can correct the body and call again. `spec_revision` sits beside `error`, at the top of the result.
an agent can correct the body and call again. Every result carries `spec_revision`, the catalog it was resolved
against, at the top level beside `error`.

A failed call is an MCP tool result with `isError: true`, as the MCP spec asks for execution errors, not a JSON-RPC
error. ChatGPT presents such a result as a tool exception carrying the text. The result takes one of three shapes:
error. ChatGPT presents such a result as a tool exception carrying the text. Each failure has an `error.phase`:

| Failure | Text content | `structuredContent` |
| --- | --- | --- |
| Medusa rejected the call | The same JSON as `structuredContent` | `operation`, `status`, `body`, `error` (`phase: 'medusa'`), `spec_revision` |
| The body failed the schema | A readable list of problems | `operation`, `error` (`phase: 'schema'`, `problems`, `hint`), `spec_revision` |
| Refused before any call: unknown operation, wrong tool, blocked by policy, missing scope, rate limit, a body that is not JSON, bad path parameters | A readable message | None |
| `error.phase` | When | Text content | Reached Medusa |
| --- | --- | --- | --- |
| `medusa` | Medusa rejected the call. `structuredContent` adds `status` and `body`. | The same JSON as `structuredContent` | Yes |
| `schema` | The body failed the published schema. `error.problems` lists why. | A readable list of problems | No |
| `precheck` | `delete_api` found no such resource: a 404, or Medusa's 200 with an empty body. `error.check` names the GET. | A readable message | Only the GET |
| `refused` | Unknown operation, wrong tool, blocked by policy, rate limit, a body that is not JSON, or bad path parameters. | A readable message | No |

A token without the tool's scope gets no tool result at all: the server answers HTTP 403 with a `WWW-Authenticate`
challenge naming the scope, so the client can ask the user for more access.

A successful delete reports `precheck`: the GET that found the resource, or `null` when the path has no GET to check
with. The check reports only that the resource exists, never its fields, so it shows a token without `mcp:read`
nothing that the DELETE would not.

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,
Expand Down
11 changes: 11 additions & 0 deletions packages/medusa-mcp/src/mcp/__tests__/mcp.unit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { describeOperation } from '../describe';
import { appendQuery, buildRequestUrl, declaredParameters, ExecutionError, executeOperation } from '../execute';
import { BUILT_IN_BLOCKLIST, createPolicy } from '../policy';
import { buildSearchIndex, pathResource, queryIntent, queryTerms, tokenize } from '../search';
import { resourceIn } from '../server';

const spec = buildApiSpec({ projectRoot: path.join(__dirname, '../../openapi/__tests__/fixtures/valid') });
const catalog = buildCatalog(spec, createPolicy());
Expand Down Expand Up @@ -324,3 +325,13 @@ describe('search', () => {
}
});
});

describe('resourceIn', () => {
it('finds the resource nested under its key, or returned directly, and nothing in an empty body', () => {
expect(resourceIn({ product: { id: 'prod_1' } })).toEqual({ id: 'prod_1' });
expect(resourceIn({ id: 'custom_1', title: 'Direct' })).toEqual({ id: 'custom_1', title: 'Direct' });
expect(resourceIn({})).toBeUndefined();
expect(resourceIn('{"product":')).toBeUndefined();
expect(resourceIn(undefined)).toBeUndefined();
});
});
111 changes: 96 additions & 15 deletions packages/medusa-mcp/src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ function dryRunLimits(check: SchemaCheck): string {
);
}

/** The resource object in a GET response: `product` in Medusa's `{ product: {...} }`, or the body itself when a route
* returns the resource directly with an `id`. Medusa answers some missing resources with 200 and an empty body
* (`GET /admin/collections/{id}` returns `{}`), so callers must check for it. */
export function resourceIn(body: unknown): Record<string, unknown> | undefined {
if (!body || typeof body !== 'object' || Array.isArray(body)) return undefined;
const record = body as Record<string, unknown>;
if (typeof record.id === 'string') return record;
return Object.values(record).find((value) => value && typeof value === 'object' && !Array.isArray(value)) as
| Record<string, unknown>
| undefined;
}

/** A path that ends in a path parameter names one resource, which a GET on the same path can read. */
const ONE_RESOURCE = /\{[^}]+\}$/;

/** 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) {
Expand Down Expand Up @@ -106,16 +121,26 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
},
);

const specRevision = catalog.spec.revision.slice(0, 12);

/** A call stopped before anything reached Medusa: the reason as text, plus the same `error` shape as other failures. */
const refusal = (message: string, operation?: string): ToolResult =>
fail(message, {
...(operation ? { operation } : {}),
error: { phase: 'refused', message, hint: 'Nothing was sent to Medusa.' },
spec_revision: specRevision,
});

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.`)
operation ?? refusal(`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;
return message ? refusal(message) : undefined;
};

const declaredFor = (operation: CatalogOperation) => {
Expand All @@ -127,7 +152,7 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
try {
return await executeOperation(target, operation, declaredFor(operation), args);
} catch (error) {
if (error instanceof ExecutionError) return fail(error.message);
if (error instanceof ExecutionError) return refusal(error.message, operation.operation);
throw error;
}
};
Expand All @@ -139,19 +164,23 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
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.`);
return refusal(
`${operation.operation} is blocked for agents by the "${operation.blocked_by}" rule.`,
operation.operation,
);
}
if (operation.tool !== tool) {
return fail(`${operation.operation} is not handled by ${tool}. Use ${operation.tool ?? 'another tool'} instead.`);
return refusal(
`${operation.operation} is not handled by ${tool}. Use ${operation.tool ?? 'another tool'} instead.`,
operation.operation,
);
}
return operation;
};

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 });
if (result.status < 400) return ok({ operation: operation.operation, ...result, spec_revision: specRevision });
const error = {
phase: 'medusa',
status: result.status,
Expand Down Expand Up @@ -289,11 +318,14 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
if (contentTypes.length && !contentTypes.some((type) => type.includes('json'))) {
return refused(
args,
fail(`${operation.operation} takes ${contentTypes.join(' or ')}, which write_api cannot send.`),
refusal(
`${operation.operation} takes ${contentTypes.join(' or ')}, which write_api cannot send.`,
operation.operation,
),
);
}
const schema = requestBody?.content?.['application/json']?.schema;
const schemaCheck: SchemaCheck = !schema ? 'no_schema' : args.body === undefined ? 'no_body' : 'passed';
const schemaCheck: SchemaCheck = args.body === undefined ? 'no_body' : !schema ? 'no_schema' : 'passed';
if (schema && args.body !== undefined) {
const problems = validateBody(catalog.spec, operation.area, schema, args.body);
if (problems.length) {
Expand Down Expand Up @@ -340,7 +372,14 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
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));
return audited(args, async () => {
const precheck = await findBeforeDelete(operation, args);
if (precheck && 'content' in precheck) return refused(args, precheck);
const result = await executeAudited(operation, args);
return result.isError || !result.structuredContent
? result
: ok({ ...result.structuredContent, precheck: precheck ?? null });
});
},
);

Expand Down Expand Up @@ -371,6 +410,49 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
return resultOf(operation, result);
}

/**
* Medusa's DELETE routes answer `deleted: true` whether or not the resource existed, so a delete cannot show that
* anything was removed. When the same path has a GET, read it first: a missing resource stops the DELETE and returns
* why. Only existence is reported, never the body, so a token without mcp:read learns nothing a DELETE would not.
*/
async function findBeforeDelete(
operation: CatalogOperation,
args: ToolArgs,
): Promise<{ operation: string; found: true } | ToolResult | undefined> {
const read = catalog.byKey.get(`GET ${operation.path}`);
if (!ONE_RESOURCE.test(operation.path) || !read || read.blocked_by) return undefined;
let current: Awaited<ReturnType<typeof run>>;
try {
current = await run(read, { path_params: args.path_params });
} catch {
// A timeout or a dropped connection says nothing about existence; the DELETE decides.
return undefined;
}
if ('content' in current) return current;
// A 404 says the resource is missing whatever its body. Otherwise a truncated body cannot show whether the resource
// is in it, so the check is inconclusive.
const missing = current.status === 404 || (!current.truncated && current.status < 400 && !resourceIn(current.body));
if (current.truncated && !missing) return undefined;
if (missing) {
const message =
medusaError(current.body).message ?? `${read.operation} returned no resource for these path parameters.`;
return fail(`${message} The DELETE was not sent.`, {
operation: operation.operation,
executed: false,
error: {
phase: 'precheck',
check: read.operation,
status: current.status,
message,
hint: 'Nothing was deleted, because the resource does not exist. Check the path parameters.',
},
spec_revision: specRevision,
});
}
// Any other failure says nothing about existence, so the DELETE goes ahead without claiming a check passed.
return current.status < 400 ? { operation: read.operation, found: true } : undefined;
}

/**
* 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
Expand All @@ -385,11 +467,12 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
executed: false,
schema_check: schemaCheck,
limits: dryRunLimits(schemaCheck),
spec_revision: specRevision,
};
const proposalOnly = (note: string) => ok({ ...preview, proposed: args.body ?? null, current: null, note });

const read = catalog.byKey.get(`GET ${operation.path}`);
if (!/\{[^}]+\}$/.test(operation.path)) {
if (!ONE_RESOURCE.test(operation.path)) {
// The spec does not say whether a POST creates, updates, or acts, so the note names the operation and states what
// the preview does rather than guessing what the call will do.
const name = operation.summary ? `"${operation.summary}"` : 'This operation';
Expand All @@ -406,9 +489,7 @@ export function buildMcpServer(registry: ApiRegistry, target: ExecutionTarget):
if ('content' in current) return current;
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),
) as Record<string, unknown> | undefined;
const resource = resourceIn(current.body);
const changes = fields.map((field) => ({
field,
current: resource?.[field] ?? null,
Expand Down
Loading