Skip to content
Open
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
5 changes: 1 addition & 4 deletions packages/nimbus-mcp/src/data-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,7 @@ export interface IconCatalog {
}

/** Returns the full icon catalog. */
export async function getIconCatalog(): Promise<IconCatalog> {
const catalogPath = resolve(getDataDir(), "icons.json");
return readJson<IconCatalog>(catalogPath);
}
export const getIconCatalog = lazyJson<IconCatalog>("icons.json");

// ---------------------------------------------------------------------------
// Flattened token data
Expand Down
2 changes: 2 additions & 0 deletions packages/nimbus-mcp/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { registerGetComponent } from "./tools/get-component.js";
import { registerListComponents } from "./tools/list-components.js";
import { registerSearchIcons } from "./tools/search-icons.js";

/**
* Creates and configures the Nimbus MCP server.
Expand All @@ -25,6 +26,7 @@ export function createServer(): McpServer {
// Register all tools
registerGetComponent(server);
registerListComponents(server);
registerSearchIcons(server);

return server;
}
173 changes: 173 additions & 0 deletions packages/nimbus-mcp/src/tools/search-icons.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { createTestClient } from "../test-utils.js";
import type { IconCatalogEntry } from "../types.js";

/**
* Behavioral tests for the search_icons tool.
*
* Reads the icon catalog from data/icons.json (populated by the prebuild step).
* Tests assert result shapes, pagination metadata, and known icon matches.
*/

/** Shape returned by the paginated search_icons tool. */
interface SearchIconsResponse {
query: string;
totalIcons: number;
totalResults: number;
offset?: number;
pageSize?: number;
hasMore?: boolean;
hint?: string;
results: IconCatalogEntry[];
}

async function callSearchIcons(
client: Client,
args: { query: string; offset?: number }
): Promise<SearchIconsResponse> {
const result = await client.callTool({
name: "search_icons",
arguments: args,
});
const text = (result.content as Array<{ type: string; text: string }>).find(
(c) => c.type === "text"
)?.text;

return JSON.parse(text!) as SearchIconsResponse;
}

describe("search_icons — basic search", () => {
let client: Client;
let close: () => Promise<void>;

beforeAll(async () => {
const ctx = createTestClient();
await ctx.connect();
client = ctx.client;
close = ctx.close;
});

afterAll(() => close());

it("returns results for a matching query", async () => {
const response = await callSearchIcons(client, { query: "check" });
expect(response.totalResults).toBeGreaterThan(0);
expect(response.results.length).toBeGreaterThan(0);
});

it("every entry has the required fields", async () => {
const response = await callSearchIcons(client, { query: "arrow" });
expect(response.results.length).toBeGreaterThan(0);
for (const icon of response.results) {
expect(typeof icon.name).toBe("string");
expect(icon.importPath).toBe("@commercetools/nimbus-icons");
expect(["material", "custom"]).toContain(icon.category);
expect(Array.isArray(icon.keywords)).toBe(true);
}
});

it("returns pagination metadata", async () => {
const response = await callSearchIcons(client, { query: "arrow" });
expect(response.totalIcons).toBeGreaterThan(0);
expect(response.totalResults).toBeGreaterThan(0);
expect(response.offset).toBe(0);
expect(response.pageSize).toBe(5);
expect(typeof response.hasMore).toBe("boolean");
});

it("pages results at 5 per page", async () => {
const response = await callSearchIcons(client, { query: "arrow" });
expect(response.results.length).toBeLessThanOrEqual(5);
});

it("caps total results at 10", async () => {
// "s" is a very broad query that should match many icons
const response = await callSearchIcons(client, { query: "s" });
expect(response.totalResults).toBeLessThanOrEqual(10);
});

it("returns zero results for a nonsense query", async () => {
const response = await callSearchIcons(client, { query: "zzqxjwvfk" });
expect(response.totalResults).toBe(0);
expect(response.results).toEqual([]);
});
});

describe("search_icons — pagination", () => {
let client: Client;
let close: () => Promise<void>;

beforeAll(async () => {
const ctx = createTestClient();
await ctx.connect();
client = ctx.client;
close = ctx.close;
});

afterAll(() => close());

it("returns hasMore and hint when more results exist", async () => {
const response = await callSearchIcons(client, { query: "arrow" });
// "arrow" should match more than 5 icons
expect(response.hasMore).toBe(true);
expect(response.hint).toBeDefined();
expect(response.hint).toContain("offset");
});

it("retrieves the next page with offset", async () => {
const page1 = await callSearchIcons(client, { query: "arrow" });
const page2 = await callSearchIcons(client, {
query: "arrow",
offset: 5,
});

expect(page2.results.length).toBeGreaterThan(0);
// pages should not overlap
const page1Names = page1.results.map((r) => r.name);
const page2Names = page2.results.map((r) => r.name);
for (const name of page2Names) {
expect(page1Names).not.toContain(name);
}
});

it("returns hasMore: false on the last page", async () => {
const response = await callSearchIcons(client, {
query: "arrow",
offset: 5,
});
expect(response.hasMore).toBe(false);
expect(response.hint).toBeUndefined();
});
});

describe("search_icons — acceptance criteria", () => {
let client: Client;
let close: () => Promise<void>;

beforeAll(async () => {
const ctx = createTestClient();
await ctx.connect();
client = ctx.client;
close = ctx.close;
});

afterAll(() => close());

it('search_icons("CheckCircle") returns CheckCircle across pages', async () => {
const page1 = await callSearchIcons(client, { query: "CheckCircle" });
const page2 = page1.hasMore
? await callSearchIcons(client, { query: "CheckCircle", offset: 5 })
: { results: [] as IconCatalogEntry[] };

const names = [...page1.results, ...page2.results].map((r) => r.name);
expect(names).toContain("CheckCircle");
});

it("results include correct import paths", async () => {
const response = await callSearchIcons(client, { query: "checkmark" });
for (const icon of response.results) {
expect(icon.importPath).toBe("@commercetools/nimbus-icons");
}
});
});
175 changes: 175 additions & 0 deletions packages/nimbus-mcp/src/tools/search-icons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import Fuse from "fuse.js";
import { z } from "zod";
import { getIconCatalog } from "../data-loader.js";
import type { IconCatalogEntry } from "../types.js";

/** Maximum number of matches the search will consider. */
const MAX_ICON_RESULTS = 10;

/** Number of results returned per page. */
const PAGE_SIZE = 5;

/** Minimum keyword length for substring matching to avoid single-char noise. */
const MIN_KEYWORD_LENGTH = 2;

/** Cached Fuse instance (created on first call). */
let fuseInstance: Fuse<IconCatalogEntry> | undefined;

async function getFuse(): Promise<Fuse<IconCatalogEntry>> {
if (!fuseInstance) {
const catalog = await getIconCatalog();
fuseInstance = new Fuse(catalog.icons, {
keys: [
{ name: "name", weight: 2 },
{ name: "keywords", weight: 1 },
],
threshold: 0.4,
ignoreLocation: true,
includeScore: true,
minMatchCharLength: 2,
});
}
return fuseInstance;
}

/**
* Two-pass search matching the list_components pattern:
* Pass 1: Substring match — query contains a keyword or keyword contains query.
* Pass 2: Fuse.js fuzzy fallback.
*/
async function searchIcons(query: string): Promise<IconCatalogEntry[]> {
const catalog = await getIconCatalog();
const needle = query.toLowerCase();
Copy link
Collaborator

@valoriecarli valoriecarli Mar 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

im sure needle means something im not familiar with yet. yes, i can see that nameLower is used further down.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refers to the figurative 'haystack'

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it was so random that i suspected as much. TIL


// Pass 1: substring match on name and keywords, name matches ranked first
const nameMatches: IconCatalogEntry[] = [];
const keywordMatches: IconCatalogEntry[] = [];

for (const icon of catalog.icons) {
const nameLower = icon.name.toLowerCase();
if (nameLower.includes(needle) || needle.includes(nameLower)) {
nameMatches.push(icon);
} else if (
icon.keywords.some(
(kw) =>
kw.length >= MIN_KEYWORD_LENGTH &&
(kw.includes(needle) || needle.includes(kw))
)
) {
keywordMatches.push(icon);
}
}

const substringMatches = [...nameMatches, ...keywordMatches];

if (substringMatches.length > 0) {
return substringMatches.slice(0, MAX_ICON_RESULTS);
}

// Pass 2: fuzzy fallback — filter out low-quality matches
const fuse = await getFuse();
return fuse
.search(query, { limit: MAX_ICON_RESULTS })
.filter((r) => (r.score ?? 1) < 0.35)
.map((r) => r.item);
}

/**
* Registers the `search_icons` tool on the given MCP server.
*
* Accepts a `query` param and an optional `offset` for pagination.
* Performs a two-pass search (substring then Fuse.js fuzzy) against icon names
* and keywords from the icon catalog. Returns a page of {@link PAGE_SIZE}
* results with metadata about total matches and how to fetch more.
*/
export function registerSearchIcons(server: McpServer): void {
server.registerTool(
"search_icons",
{
title: "Search Icons",
description:
"Fuzzy-search Nimbus icons by name or keyword. " +
"Returns matching icon names with import paths from @commercetools/nimbus-icons. " +
`Results are paginated (${PAGE_SIZE} per page). Use the offset parameter to retrieve additional results.`,
inputSchema: {
query: z
.string()
.describe(
'Search query to match against icon names and keywords, e.g. "checkmark", "arrow", "settings".'
),
offset: z
.number()
.int()
.min(0)
.default(0)
.describe(
"Starting index for paginated results. Omit or pass 0 for the first page."
),
},
},
async ({ query, offset }) => {
try {
const catalog = await getIconCatalog();
const allResults = await searchIcons(query);
const page = allResults.slice(offset, offset + PAGE_SIZE);
const hasMore = offset + PAGE_SIZE < allResults.length;

if (allResults.length === 0) {
return {
content: [
{
type: "text" as const,
text: JSON.stringify(
{
query,
totalIcons: catalog.icons.length,
totalResults: 0,
results: [],
},
null,
2
),
},
],
};
}

const payload: Record<string, unknown> = {
query,
totalIcons: catalog.icons.length,
totalResults: allResults.length,
offset,
pageSize: PAGE_SIZE,
hasMore,
results: page,
};

if (hasMore) {
payload.hint =
`Showing ${offset + 1}–${offset + page.length} of ${allResults.length} matches. ` +
`Call search_icons again with offset: ${offset + PAGE_SIZE} to see more.`;
}

return {
content: [
{
type: "text" as const,
text: JSON.stringify(payload, null, 2),
},
],
};
} catch {
return {
content: [
{
type: "text" as const,
text: "Icon catalog is not available in this environment.",
},
],
isError: true,
};
}
}
);
}
Loading