-
Notifications
You must be signed in to change notification settings - Fork 2
feat(nimbus-mcp): add search_icons tool #1230
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
Open
tylermorrisford
wants to merge
6
commits into
main
Choose a base branch
from
CRAFT-2136-search-icons-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a3e3fe5
feat(nimbus-mcp): add search_icons tool
tylermorrisford 3bb30e8
refactor(nimbus-mcp): consolidate IconResult into shared IconCatalogE…
tylermorrisford 4850c5f
refactor(nimbus-mcp): rename MAX_RESULTS to MAX_ICON_RESULTS
tylermorrisford 865d2a2
refactor(nimbus-mcp): add offset-based pagination to search_icons
tylermorrisford 5a855be
fix(nimbus-mcp): update search_icons tests for pagination and fix sea…
tylermorrisford d6be945
fix(data-loader): prefer existing caching for icons json read
tylermorrisford 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
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,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"); | ||
| } | ||
| }); | ||
| }); |
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,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(); | ||
|
|
||
| // 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, | ||
| }; | ||
| } | ||
| } | ||
| ); | ||
| } | ||
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.
im sure needle means something im not familiar with yet. yes, i can see that nameLower is used further down.
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.
Refers to the figurative 'haystack'
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.
it was so random that i suspected as much. TIL