fix(entitlements): gate paid MCP tools (send_invoice/agi_submit/vat_declaration_submit) server-side (#846)

The HTTP routes call requireCapability at every paid chokepoint, but the
MCP/agent path bypassed the paywall entirely: the three external-service
tools stage operations whose commit calls the email / Skatteverket services
directly, with no capability check. After the 2026-07-07 trial cutover a
trial-connected non-payer using the gnubok MCP connector could still send
invoice emails and file AGI/VAT.

Close the gap with two layers, mirroring the existing TOOL_SCOPE_MAP gate:

- Dispatch gate (mcp-server/server.ts): MCP_TOOL_CAPABILITY_MAP, checked
  right after the scope check, blocks a non-entitled company before any
  pending op is staged. Emits errorKind='capability_denied' telemetry.
- Commit-time gate (commitPendingOperation): PAID_OPERATION_CAPABILITY_MAP,
  checked before the atomic claim. The real external-service chokepoint —
  applies to the MCP approve tool AND the UI approval path, and closes the
  trial-connected-token window (the grant has expired by commit time). A
  blocked op stays 'pending', so it is re-approvable once the company subscribes.

Adds a transport-free capabilityBlockedError() helper (shared bilingual
copy) and locks both maps with tests (maps, dispatch gate, commit gate).
Only the three write/submit tools are gated; SKV read/local tools stay free
per the statutory carve-out. No DB/migration change; self-hosted stays all-on.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-30 16:38:14 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 5df6199bd1
commit db843a7a5b
9 changed files with 422 additions and 6 deletions
@@ -0,0 +1,156 @@
/**
* Tests for the capability paywall gate in the MCP dispatcher.
*
* The paid external-service tools (send_invoice → email_send, the two
* Skatteverket submissions → skatteverket) must be blocked server-side when the
* company isn't entitled — BEFORE tool.execute() runs, so no pending op is
* staged. The gate sits right after the API-key scope check and mirrors its
* shape, so the test key holds the required SCOPE but the company may lack the
* CAPABILITY. Self-hosted short-circuits hasCapability to all-on (covered in
* lib/entitlements/__tests__/has-capability.test.ts), so here we drive the
* gate directly via a mocked hasCapability.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
// A minimal chainable Supabase stub — only reached if the gate lets a call
// through to execute(); resolves everything to null so execute fails with a
// plain execution error (never capability_blocked).
const chain: unknown = new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve({ data: null, error: null })
}
return () => chain
},
},
)
return {
...actual,
extractBearerToken: vi.fn().mockReturnValue('test-token'),
validateApiKey: vi.fn().mockResolvedValue({
userId: 'user-1',
companyId: '11111111-1111-4111-8111-111111111111',
// Holds the SCOPES for all three paid tools so the scope gate passes and
// the CAPABILITY gate is what we exercise.
scopes: ['invoices:write', 'skatteverket:write', 'reports:read'],
apiKeyId: 'key-1',
apiKeyName: 'Test Key',
}),
createServiceClientNoCookies: vi.fn(() => ({ from: () => chain, rpc: () => chain })),
}
})
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
return { ...actual, hasCapability: vi.fn() }
})
import { handleMcpRequest } from '../server'
import { hasCapability } from '@/lib/entitlements/has-capability'
const mockHasCapability = vi.mocked(hasCapability)
function mcpToolCall(name: string, args: Record<string, unknown> = {}): Request {
return new Request('http://localhost:3000/api/extensions/ext/mcp-server/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test-token' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
})
}
interface ToolCalledEvent {
tool: string
success: boolean
isError: boolean
errorKind: string | null
errorCode: string | null
latencyMs: number
}
function captureNextToolCalled(): Promise<ToolCalledEvent> {
return new Promise((resolve) => {
const off = eventBus.on('mcp.tool_called', (payload) => {
off()
resolve(payload as unknown as ToolCalledEvent)
})
})
}
async function parsedToolResult(response: Response): Promise<{ isError: boolean; payload: Record<string, unknown> }> {
const json = await response.json()
const result = json.result as { isError?: boolean; content: { text: string }[] }
return { isError: result.isError === true, payload: JSON.parse(result.content[0].text) }
}
describe('MCP capability gate', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
it('blocks gnubok_send_invoice when email_send is not entitled — before execute()', async () => {
mockHasCapability.mockResolvedValue(false)
const eventPromise = captureNextToolCalled()
const response = await handleMcpRequest(mcpToolCall('gnubok_send_invoice', { invoice_id: 'inv-1' }))
const { isError, payload } = await parsedToolResult(response)
expect(isError).toBe(true)
expect((payload.error as Record<string, unknown>).capability_blocked).toBe(true)
expect((payload.error as Record<string, unknown>).capability).toBe('email_send')
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'email_send')
const event = await eventPromise
expect(event.errorKind).toBe('capability_denied')
expect(event.errorCode).toBe('capability_blocked')
expect(event.success).toBe(false)
// The gate exits before tool.execute(), exactly like scope denial.
expect(event.latencyMs).toBe(0)
})
it('blocks gnubok_agi_submit when skatteverket is not entitled', async () => {
mockHasCapability.mockResolvedValue(false)
const response = await handleMcpRequest(mcpToolCall('gnubok_agi_submit', { salary_run_id: 'sr-1' }))
const { isError, payload } = await parsedToolResult(response)
expect(isError).toBe(true)
expect((payload.error as Record<string, unknown>).capability).toBe('skatteverket')
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'skatteverket')
})
it('lets a free tool through without consulting the capability gate', async () => {
mockHasCapability.mockResolvedValue(false)
await handleMcpRequest(mcpToolCall('gnubok_list_skills', {}))
// gnubok_list_skills has no MCP_TOOL_CAPABILITY_MAP entry — the gate is skipped entirely.
expect(mockHasCapability).not.toHaveBeenCalled()
})
it('proceeds to execute() when the company IS entitled (no capability_blocked)', async () => {
mockHasCapability.mockResolvedValue(true)
const eventPromise = captureNextToolCalled()
const response = await handleMcpRequest(mcpToolCall('gnubok_send_invoice', { invoice_id: 'inv-1' }))
const { payload } = await parsedToolResult(response)
// Gate passed → execute() runs (and fails for an unrelated reason: email not
// configured / invoice not found). The point is it is NOT capability_blocked.
expect((payload.error as Record<string, unknown> | undefined)?.capability_blocked).toBeUndefined()
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'email_send')
const event = await eventPromise
expect(event.errorKind).not.toBe('capability_denied')
})
})
+32 -1
View File
@@ -71,6 +71,8 @@ import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplica
import { renderToBuffer } from '@react-pdf/renderer'
import { InvoicePDF } from '@/lib/invoices/pdf-template'
import { getEmailService } from '@/lib/email/service'
import { hasCapability, capabilityBlockedError } from '@/lib/entitlements/has-capability'
import { MCP_TOOL_CAPABILITY_MAP } from '@/lib/entitlements/keys'
import {
generateInvoiceEmailHtml,
generateInvoiceEmailText,
@@ -9982,7 +9984,7 @@ function emitToolCallTelemetry(payload: {
success: boolean
isError: boolean
errorCode: string | null
errorKind: 'execution' | 'scope_denied' | 'unknown_tool' | null
errorKind: 'execution' | 'scope_denied' | 'capability_denied' | 'unknown_tool' | null
errorMessage: string | null
requestId: string | number | null
userId: string
@@ -10437,6 +10439,35 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
)
}
// Enforce the capability paywall — the MCP/agent path is a paid chokepoint
// just like the HTTP routes (send_invoice → email_send, the two SKV
// submissions → skatteverket). Fail-closed; self-hosted short-circuits to
// all-on inside hasCapability. Blocks before any pending op is staged.
const requiredCapability = MCP_TOOL_CAPABILITY_MAP[toolName]
if (requiredCapability && !(await hasCapability(supabase, companyId, requiredCapability))) {
const capError = { error: capabilityBlockedError(requiredCapability) }
emitToolCallTelemetry({
tool: toolName,
requiredScope,
actor,
latencyMs: 0,
success: false,
isError: true,
errorCode: capError.error.code,
errorKind: 'capability_denied',
errorMessage: capError.error.message_sv,
requestId: id ?? null,
userId,
companyId,
})
return NextResponse.json(
jsonRpc(id ?? null, {
content: [{ type: 'text', text: JSON.stringify(capError, null, 2) }],
isError: true,
})
)
}
// Detect if THIS call follows the previous call's `next` hint — must
// run before execute() so we don't double-store on this call. Emits
// mcp.next_hint_followed when the agent's behaviour matches the hint.