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
79 changes: 73 additions & 6 deletions packages/medusa-mcp/src/mcp/__tests__/mcp.unit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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';
import { buildSearchIndex, pathResource, queryIntent, queryTerms, tokenize } from '../search';

const spec = buildApiSpec({ projectRoot: path.join(__dirname, '../../openapi/__tests__/fixtures/valid') });
const catalog = buildCatalog(spec, createPolicy());
Expand Down Expand Up @@ -208,6 +208,39 @@ describe('search', () => {
'category',
]);
expect(tokenize('shipped shipping orders')).toEqual(['ship', 'ship', 'order']);
expect(tokenize("an existing product's new description")).toEqual(['product', 'description']);
});

it('weights terms in a detail clause at half, unless they also name the target', () => {
expect(queryTerms('create a product with variants and options')).toEqual([
{ term: 'variant', weight: 0.5 },
{ term: 'option', weight: 0.5 },
{ term: 'create', weight: 1 },
{ term: 'product', weight: 1 },
]);
expect(queryTerms('create a collection to group products')).toContainEqual({ term: 'group', weight: 0.5 });
expect(queryTerms('add a product to a product list')).toContainEqual({ term: 'product', weight: 1 });
// A marker before the verb does not start a clause.
expect(queryTerms('how to create a product with variants')).toContainEqual({ term: 'product', weight: 1 });
// When the head names no resource, the clause holds the target and keeps its weight.
const resources = new Set(['item', 'location', 'product']);
expect(queryTerms('set stock quantity for an inventory item', resources)).toContainEqual({
term: 'item',
weight: 1,
});
});

it('keeps the inventory level update within the default five results', () => {
const results = index.search('set stock quantity for an inventory item at a location');
expect(results.map((result) => result.operation.operation)).toContain(
'POST /admin/inventory-items/{id}/location-levels/{location_id}',
);
});

it('reads the resource an operation acts on from the end of its path', () => {
expect(pathResource('/admin/products/{id}/variants')).toBe('variant');
expect(pathResource('/admin/payment-collections')).toBe('collection');
expect(pathResource('/admin/products/{id}')).toBe('product');
});

it('reads one method intent from the query verbs', () => {
Expand All @@ -222,7 +255,10 @@ describe('search', () => {
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.
// Measured on the pinned 2.22.1 spec. The first 15 phrasings sit close to Medusa's summaries; the rest are written the
// way agents ask, with qualifiers and detail clauses, and include the three that misranked live in ChatGPT. Before
// modifier weighting and the path-resource boost: hit@1 18/34, hit@3 25/34 (without the last case). Now: hit@1
// 26/35, hit@3 31/35.
it('finds the expected operation for common agent tasks', () => {
const cases: [string, string, { area?: 'admin' | 'store' }?][] = [
['update a product description', 'POST /admin/products/{id}'],
Expand All @@ -243,17 +279,48 @@ describe('search', () => {
['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' }],
['create a new customer with an email address', 'POST /admin/customers'],
['add a product to a sales channel', 'POST /admin/sales-channels/{id}/products'],
['change the title of an existing collection', 'POST /admin/collections/{id}'],
['remove a product from a collection', 'POST /admin/collections/{id}/products'],
['create a discount code for 10% off', 'POST /admin/promotions'],
['look up an order by its display id', 'GET /admin/orders'],
['archive a product by setting its status', 'POST /admin/products/{id}'],
['create a price list for wholesale customers', 'POST /admin/price-lists'],
['add a tag to a product', 'POST /admin/products/{id}'],
['create a product category under a parent category', 'POST /admin/product-categories'],
['delete a customer group', 'DELETE /admin/customer-groups/{id}'],
['list the variants of a product', 'GET /admin/products/{id}/variants'],
['create a shipping option for a region', 'POST /admin/shipping-options'],
[
'update the inventory quantity of a variant at a stock location',
'POST /admin/inventory-items/{id}/location-levels/{location_id}',
],
['create a stock location for a warehouse', 'POST /admin/stock-locations'],
['get a customer by id', 'GET /admin/customers/{id}'],
['create a product as draft with variants and options', 'POST /admin/products'],
["update an existing product's description", 'POST /admin/products/{id}'],
['create a product collection to group products', 'POST /admin/collections'],
['how to create a product with variants', 'POST /admin/products'],
];
const ranks = cases.map(([query, expected, filters]) => ({
query,
rank: index.search(query, filters ?? {}, 5).findIndex((result) => result.operation.operation === expected) + 1,
rank: index.search(query, filters ?? {}, 10).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);
if (hitAt1 < 26 || hitAt3 < 31)
throw new Error(`Search regressed: hit@1 ${hitAt1}/${cases.length}, hit@3 ${hitAt3}/${cases.length}\n${report}`);
for (const query of [
'update a product description',
'create a product as draft with variants and options',
"update an existing product's description",
'create a product collection to group products',
'how to create a product with variants',
]) {
expect({ query, rank: ranks.find((entry) => entry.query === query)?.rank }).toEqual({ query, rank: 1 });
}
});
});
99 changes: 92 additions & 7 deletions packages/medusa-mcp/src/mcp/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,41 @@ const STOP_WORDS = new Set([
'my',
'me',
'i',
'as',
'it',
'its',
// Words that qualify a resource without naming one. "existing" alone matched every "Update Existing ..." summary.
'existing',
'new',
'current',
'single',
'specific',
'given',
]);

/** Words that start a clause describing details or purpose, as in "create a product with variants" or "a collection
* to group products". Agents name the target first, so terms after one of these count for less. */
const MODIFIER_MARKERS = new Set([
'with',
'to',
'for',
'at',
'in',
'on',
'by',
'from',
'so',
'that',
'using',
'including',
'which',
'where',
]);
const MODIFIER_WEIGHT = 0.5;
/** Boost for an operation whose path ends in the resource the query names, so "create a product with variants" finds
* product creation before variant creation. */
const RESOURCE_BOOST = 1.5;

/** Verbs that say which HTTP method the user wants. Matching operations rank higher. */
const INTENT_VERBS: Record<string, string> = {
list: 'GET',
Expand Down Expand Up @@ -65,6 +98,7 @@ function stem(token: string): string {
/** Lowercase word tokens, splitting camelCase and path punctuation, with light stemming. */
export function tokenize(text: string): string[] {
return text
.replace(/['’]s\b/g, '')
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.toLowerCase()
.split(/[^a-z0-9]+/)
Expand All @@ -84,6 +118,51 @@ export function queryIntent(query: string): string | undefined {
return methods.size === 1 ? [...methods][0] : undefined;
}

/** The resource an operation acts on: the last word of its last literal path segment, so `variant` for
* `/admin/products/{id}/variants` and `collection` for `/admin/payment-collections`. */
export function pathResource(path: string): string | undefined {
const literal = path
.split('/')
.filter((segment) => segment && !segment.startsWith('{'))
.at(-1);
return literal ? tokenize(literal).at(-1) : undefined;
}

/** A query split at its first detail-clause marker after the operation verb, so "how to create a product with
* variants" splits at "with", not at "to". `subject` is the head after the verb: the words naming the target. */
function splitQuery(query: string): { head: string[]; subject: string[]; tail: string[] } {
const words = query.split(/\s+/).filter(Boolean);
const verb = words.findIndex((word) => INTENT_VERBS[word.toLowerCase()]);
const marker = words.findIndex(
(word, position) => position > Math.max(verb, 0) && MODIFIER_MARKERS.has(word.toLowerCase()),
);
const head = tokenize((marker < 0 ? words : words.slice(0, marker)).join(' '));
const tail = marker < 0 ? [] : tokenize(words.slice(marker).join(' '));
return { head, subject: head.slice(head.findIndex((term) => INTENT_VERBS[term]) + 1), tail };
}

/** The query's distinct terms, each weighted by whether it comes before the first detail clause. A term in both parts
* keeps its full weight. When the head names no resource in `resources`, as in "set stock quantity for an inventory
* item", the clause holds the target, so it keeps full weight too. */
export function queryTerms(query: string, resources?: Set<string>): { term: string; weight: number }[] {
const { head, subject, tail } = splitQuery(query);
const detailWeight = resources && !subject.some((term) => resources.has(term)) ? 1 : MODIFIER_WEIGHT;
const weights = new Map<string, number>();
for (const term of tail) weights.set(term, detailWeight);
for (const term of head) weights.set(term, 1);
return [...weights].map(([term, weight]) => ({ term, weight }));
}

/** The resource a query targets: the last term of its subject that names a resource in the catalog. In English the
* last noun of a phrase is its head, so "product collection" targets collections. The subject starts after the
* method verb, so "set stock quantity" does not target fulfillment sets, while "create a price list" still targets
* price lists. */
function targetResource(query: string, resources: Set<string>): string | undefined {
return splitQuery(query)
.subject.filter((term) => resources.has(term))
.at(-1);
}

function weightedTerms(operation: CatalogOperation): Map<string, number> {
const terms = new Map<string, number>();
const add = (text: string, weight: number) => {
Expand Down Expand Up @@ -113,6 +192,7 @@ export function buildSearchIndex(operations: CatalogOperation[]): SearchIndex {
const terms = weightedTerms(operation);
return { operation, terms, length: [...terms.values()].reduce((sum, weight) => sum + weight, 0) };
});
const resources = new Set(operations.map((operation) => pathResource(operation.path)).filter(Boolean) as string[]);
const averageLength = documents.reduce((sum, doc) => sum + doc.length, 0) / Math.max(documents.length, 1);
const documentFrequency = new Map<string, number>();
for (const doc of documents) {
Expand All @@ -137,8 +217,13 @@ export function buildSearchIndex(operations: CatalogOperation[]): SearchIndex {

return {
search(query, filters = {}, limit = 5) {
const terms = [...new Set(tokenize(query))].map((term) => ({ term, partials: partials(term) }));
const terms = queryTerms(query, resources).map(({ term, weight }) => ({
term,
weight,
partials: partials(term),
}));
const intent = queryIntent(query);
const target = targetResource(query, resources);
const bm25 = (doc: (typeof documents)[number], term: string, weight: number) => {
const frequency = doc.terms.get(term) ?? 0;
if (!frequency) return 0;
Expand All @@ -154,15 +239,15 @@ export function buildSearchIndex(operations: CatalogOperation[]): SearchIndex {
.filter(({ operation }) => !tag || operation.tags.some((candidate) => candidate.toLowerCase() === tag))
.map((doc) => {
const relevance = terms.reduce(
(score, { term, partials: related }) =>
(score, { term, weight, partials: related }) =>
score +
Math.max(bm25(doc, term, 1), ...related.map((candidate) => bm25(doc, candidate, PARTIAL_MATCH_WEIGHT))),
weight *
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,
};
const intentBoost = intent === doc.operation.method ? INTENT_BOOST : 1;
const resourceBoost = target && pathResource(doc.operation.path) === target ? RESOURCE_BOOST : 1;
return { operation: doc.operation, score: relevance * intentBoost * resourceBoost };
})
.filter((result) => result.score > 0)
.sort(
Expand Down
Loading