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
4 changes: 4 additions & 0 deletions packages/mcp-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ payload (spec §10.2): `VALIDATION_ERROR`, `AUTHORIZATION_ERROR`, `UPSTREAM_ERRO
businesses. Optional `businessIds` (subset of memberships), `fromDate`/`toDate` (bounded to 366
days), `tags`, `freeText`, and `flow` (`ALL`/`INCOME`/`EXPENSE`), with bounded pagination
(`pageSize` ≤ 50). Returns normalized charges plus pagination metadata.
- **`accounter_list_tags`** — list tags for categorizing charges, optionally filtered by name.
Deterministically sorted (name, then id) and size-capped (≤ 500).
- **`accounter_list_tax_categories`** — list tax categories (id, name, IRS code, active flag),
optionally filtered by name or active status. Same deterministic sort + cap.

## Upstream GraphQL client

Expand Down
113 changes: 113 additions & 0 deletions packages/mcp-server/src/tools/__tests__/lookups.test.ts
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']);
});
});
187 changes: 187 additions & 0 deletions packages/mcp-server/src/tools/lookups.ts
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)
);
}
Comment on lines +35 to +39

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The byNameThenId comparison logic can be simplified and made more robust, especially for international characters, by using String.prototype.localeCompare.

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,
};
3 changes: 3 additions & 0 deletions packages/mcp-server/src/tools/registry-instance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { searchChargesTool } from './charges.js';
import { listTagsTool, listTaxCategoriesTool } from './lookups.js';
import { ToolRegistry } from './registry.js';

/**
Expand All @@ -8,3 +9,5 @@ import { ToolRegistry } from './registry.js';
export const toolRegistry = new ToolRegistry();

toolRegistry.register(searchChargesTool);
toolRegistry.register(listTagsTool);
toolRegistry.register(listTaxCategoriesTool);
Loading