-
Notifications
You must be signed in to change notification settings - Fork 8
feat(mcp-server): tags & tax-category lookup tools (MCP Prompt 14) #4015
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
gilgardosh
wants to merge
2
commits into
claude/mcp-prompt-13-charges-tool
Choose a base branch
from
claude/mcp-prompt-14-lookup-tools
base: claude/mcp-prompt-13-charges-tool
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
2 commits
Select commit
Hold shift + click to select a range
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
113 changes: 113 additions & 0 deletions
113
packages/mcp-server/src/tools/__tests__/lookups.test.ts
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,113 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
| import { buildAuthContext, type McpAuthContext } from '../../auth/identity.js'; | ||
| import type { AuthPrincipal } from '../../auth/token.js'; | ||
| import { UpstreamGraphQLClient } from '../../upstream/graphql-client.js'; | ||
| import { executeRegisteredTool } from '../execute.js'; | ||
| import { listTagsTool, listTaxCategoriesTool } from '../lookups.js'; | ||
|
|
||
| function authContext(businessIds: string[]): McpAuthContext { | ||
| const principal: AuthPrincipal = { | ||
| subject: 'user-1', | ||
| issuer: 'https://tenant.auth0.com/', | ||
| audience: 'aud', | ||
| scopes: [], | ||
| email: null, | ||
| expiresAt: undefined, | ||
| claims: { sub: 'user-1' }, | ||
| }; | ||
| return buildAuthContext( | ||
| principal, | ||
| businessIds.map(businessId => ({ businessId, roleId: 'accountant' })), | ||
| ); | ||
| } | ||
|
|
||
| function clientReturning(data: unknown) { | ||
| const fetchImpl = vi.fn( | ||
| async () => ({ ok: true, status: 200, json: async () => ({ data }) }) as unknown as Response, | ||
| ); | ||
| return new UpstreamGraphQLClient({ | ||
| endpoint: 'http://localhost:4000/graphql', | ||
| timeoutMs: 1000, | ||
| fetchImpl: fetchImpl as unknown as typeof fetch, | ||
| }); | ||
| } | ||
|
|
||
| const runTool = ( | ||
| tool: typeof listTagsTool | typeof listTaxCategoriesTool, | ||
| client: UpstreamGraphQLClient, | ||
| auth: McpAuthContext, | ||
| rawArgs: unknown, | ||
| ) => executeRegisteredTool({ tool, rawArgs, auth, correlationId: 'c', client, authorization: 'Bearer t' }); | ||
|
|
||
| describe('listTagsTool', () => { | ||
| const client = () => | ||
| clientReturning({ | ||
| allTags: [ | ||
| { id: '3', name: 'Zebra', namePath: ['Zebra'] }, | ||
| { id: '1', name: 'apple', namePath: ['apple'] }, | ||
| { id: '2', name: 'Banana', namePath: ['food', 'Banana'] }, | ||
| ], | ||
| }); | ||
|
|
||
| it('returns tags sorted by name (case-insensitive), then id', async () => { | ||
| const result = await runTool(listTagsTool, client(), authContext(['b1']), {}); | ||
| const names = (result.structuredContent as { tags: Array<{ name: string }> }).tags.map(t => t.name); | ||
| expect(names).toEqual(['apple', 'Banana', 'Zebra']); | ||
| }); | ||
|
|
||
| it('filters by nameContains (case-insensitive)', async () => { | ||
| const result = await runTool(listTagsTool, client(), authContext(['b1']), { nameContains: 'an' }); | ||
| const structured = result.structuredContent as { tags: Array<{ name: string }>; total: number }; | ||
| expect(structured.tags.map(t => t.name)).toEqual(['Banana']); | ||
| expect(structured.total).toBe(1); | ||
| }); | ||
|
|
||
| it('caps results and flags truncation', async () => { | ||
| const result = await runTool(listTagsTool, client(), authContext(['b1']), { limit: 2 }); | ||
| const structured = result.structuredContent as { tags: unknown[]; total: number; truncated: boolean }; | ||
| expect(structured.tags).toHaveLength(2); | ||
| expect(structured.total).toBe(3); | ||
| expect(structured.truncated).toBe(true); | ||
| }); | ||
|
|
||
| it('enforces business scope (denies a caller with no memberships)', async () => { | ||
| const result = await runTool(listTagsTool, client(), authContext([]), {}); | ||
| expect(result.isError).toBe(true); | ||
| expect((result.structuredContent as { code: string }).code).toBe('AUTHORIZATION_ERROR'); | ||
| }); | ||
|
|
||
| it('rejects unknown input fields', async () => { | ||
| const result = await runTool(listTagsTool, client(), authContext(['b1']), { bogus: 1 }); | ||
| expect(result.isError).toBe(true); | ||
| expect((result.structuredContent as { code: string }).code).toBe('VALIDATION_ERROR'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('listTaxCategoriesTool', () => { | ||
| const client = () => | ||
| clientReturning({ | ||
| taxCategories: [ | ||
| { id: '1', name: 'Income', irsCode: 100, isActive: true }, | ||
| { id: '2', name: 'Assets', irsCode: null, isActive: false }, | ||
| ], | ||
| }); | ||
|
|
||
| it('returns tax categories sorted by name with fields limited to the use case', async () => { | ||
| const result = await runTool(listTaxCategoriesTool, client(), authContext(['b1']), {}); | ||
| const rows = (result.structuredContent as { | ||
| taxCategories: Array<{ name: string; irsCode: number | null; isActive: boolean }>; | ||
| }).taxCategories; | ||
| expect(rows).toEqual([ | ||
| { id: '2', name: 'Assets', irsCode: null, isActive: false }, | ||
| { id: '1', name: 'Income', irsCode: 100, isActive: true }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('filters to active categories when activeOnly is set', async () => { | ||
| const result = await runTool(listTaxCategoriesTool, client(), authContext(['b1']), { | ||
| activeOnly: true, | ||
| }); | ||
| const rows = (result.structuredContent as { taxCategories: Array<{ name: string }> }).taxCategories; | ||
| expect(rows.map(r => r.name)).toEqual(['Income']); | ||
| }); | ||
| }); |
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,187 @@ | ||
| import { z } from 'zod'; | ||
| import type { ToolDefinition, ToolExecutionContext, ToolResult } from './registry.js'; | ||
|
|
||
| /** | ||
| * Tool 2: read-only lookups for tags and tax categories (spec §8.2). | ||
| * | ||
| * These are reference-data lookups. Input is minimal, output is deterministically | ||
| * sorted (by name, then id) and size-capped. A caller must belong to at least | ||
| * one business (scope-gated) to browse them. | ||
| */ | ||
|
|
||
| export const LIST_TAGS_TOOL_NAME = 'accounter_list_tags'; | ||
| export const LIST_TAX_CATEGORIES_TOOL_NAME = 'accounter_list_tax_categories'; | ||
|
|
||
| /** Hard cap on returned rows (spec §9.3). */ | ||
| export const MAX_LOOKUP_RESULTS = 500; | ||
|
|
||
| const nameContains = z | ||
| .string() | ||
| .min(1) | ||
| .max(100) | ||
| .optional() | ||
| .describe('Case-insensitive substring to filter by name.'); | ||
|
|
||
| const limit = z | ||
| .number() | ||
| .int() | ||
| .positive() | ||
| .max(MAX_LOOKUP_RESULTS) | ||
| .optional() | ||
| .default(MAX_LOOKUP_RESULTS) | ||
| .describe(`Maximum rows to return (capped at ${MAX_LOOKUP_RESULTS}).`); | ||
|
|
||
| /** Stable order: by name (case-insensitive, locale-aware), tie-broken by id. */ | ||
| function byNameThenId(a: { name: string; id: string }, b: { name: string; id: string }): number { | ||
| return ( | ||
| a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }) || a.id.localeCompare(b.id) | ||
| ); | ||
| } | ||
|
|
||
| function applyFilterSortCap<T extends { name: string; id: string }>( | ||
| rows: T[], | ||
| search: string | undefined, | ||
| max: number, | ||
| ): { rows: T[]; total: number; truncated: boolean } { | ||
| const needle = search?.toLowerCase(); | ||
| const filtered = needle ? rows.filter(row => row.name.toLowerCase().includes(needle)) : rows; | ||
| const sorted = [...filtered].sort(byNameThenId); | ||
| return { | ||
| rows: sorted.slice(0, max), | ||
| total: filtered.length, | ||
| truncated: filtered.length > max, | ||
| }; | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Tags | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| const listTagsInput = z.object({ nameContains, limit }); | ||
| type ListTagsInput = z.infer<typeof listTagsInput>; | ||
|
|
||
| const LIST_TAGS_QUERY = /* GraphQL */ ` | ||
| query McpListTags { | ||
| allTags { | ||
| id | ||
| name | ||
| namePath | ||
| } | ||
| } | ||
| `; | ||
|
|
||
| interface RawTag { | ||
| id: string; | ||
| name: string; | ||
| namePath: string[] | null; | ||
| } | ||
|
|
||
| async function listTagsHandler( | ||
| input: ListTagsInput, | ||
| context: ToolExecutionContext, | ||
| ): Promise<ToolResult> { | ||
| const data = await context.client.query<{ allTags: RawTag[] }>( | ||
| { query: LIST_TAGS_QUERY }, | ||
| { correlationId: context.correlationId, authorization: context.authorization }, | ||
| ); | ||
|
|
||
| const { rows, total, truncated } = applyFilterSortCap( | ||
| data.allTags, | ||
| input.nameContains, | ||
| input.limit, | ||
| ); | ||
| const tags = rows.map(tag => ({ | ||
| id: tag.id, | ||
| name: tag.name, | ||
| namePath: tag.namePath ?? [tag.name], | ||
| })); | ||
|
|
||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: `Found ${total} ${total === 1 ? 'tag' : 'tags'}${truncated ? ' (truncated)' : ''}.`, | ||
| }, | ||
| ], | ||
| structuredContent: { tags, total, truncated }, | ||
| }; | ||
| } | ||
|
|
||
| export const listTagsTool: ToolDefinition<typeof listTagsInput> = { | ||
| name: LIST_TAGS_TOOL_NAME, | ||
| description: | ||
| 'List the tags available for categorizing charges, optionally filtered by name. Read-only.', | ||
| inputSchema: listTagsInput, | ||
| policy: { requiresBusinessScope: true, dataClassification: 'business' }, | ||
| handler: listTagsHandler, | ||
| }; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Tax categories | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| const listTaxCategoriesInput = z.object({ | ||
| nameContains, | ||
| activeOnly: z.boolean().optional().default(false).describe('Return only active tax categories.'), | ||
| limit, | ||
| }); | ||
| type ListTaxCategoriesInput = z.infer<typeof listTaxCategoriesInput>; | ||
|
|
||
| const LIST_TAX_CATEGORIES_QUERY = /* GraphQL */ ` | ||
| query McpListTaxCategories { | ||
| taxCategories { | ||
| id | ||
| name | ||
| irsCode | ||
| isActive | ||
| } | ||
| } | ||
| `; | ||
|
|
||
| interface RawTaxCategory { | ||
| id: string; | ||
| name: string; | ||
| irsCode: number | null; | ||
| isActive: boolean; | ||
| } | ||
|
|
||
| async function listTaxCategoriesHandler( | ||
| input: ListTaxCategoriesInput, | ||
| context: ToolExecutionContext, | ||
| ): Promise<ToolResult> { | ||
| const data = await context.client.query<{ taxCategories: RawTaxCategory[] }>( | ||
| { query: LIST_TAX_CATEGORIES_QUERY }, | ||
| { correlationId: context.correlationId, authorization: context.authorization }, | ||
| ); | ||
|
|
||
| const activeFiltered = input.activeOnly | ||
| ? data.taxCategories.filter(category => category.isActive) | ||
| : data.taxCategories; | ||
| // `rows` are already `RawTaxCategory` with exactly the fields we expose. | ||
| const { | ||
| rows: taxCategories, | ||
| total, | ||
| truncated, | ||
| } = applyFilterSortCap(activeFiltered, input.nameContains, input.limit); | ||
|
|
||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: `Found ${total} tax ${total === 1 ? 'category' : 'categories'}${ | ||
| truncated ? ' (truncated)' : '' | ||
| }.`, | ||
| }, | ||
| ], | ||
| structuredContent: { taxCategories, total, truncated }, | ||
| }; | ||
| } | ||
|
|
||
| export const listTaxCategoriesTool: ToolDefinition<typeof listTaxCategoriesInput> = { | ||
| name: LIST_TAX_CATEGORIES_TOOL_NAME, | ||
| description: | ||
| 'List tax categories (id, name, IRS code, active flag), optionally filtered by name or active status. Read-only.', | ||
| inputSchema: listTaxCategoriesInput, | ||
| policy: { requiresBusinessScope: true, dataClassification: 'business' }, | ||
| handler: listTaxCategoriesHandler, | ||
| }; | ||
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
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.
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.
The
byNameThenIdcomparison logic can be simplified and made more robust, especially for international characters, by usingString.prototype.localeCompare.