diff --git a/docs/sdk/error-handling.mdx b/docs/sdk/error-handling.mdx index 0a832a3d..00ecd927 100644 --- a/docs/sdk/error-handling.mdx +++ b/docs/sdk/error-handling.mdx @@ -20,7 +20,7 @@ The SDK throws typed errors you can catch and handle based on the error type. | `AuthorizationError` | HTTP 403. The API key is valid but lacks permission for the request. | | `NotFoundError` | Resource doesn't exist or isn't accessible | | `ValidationError` | Invalid request parameters | -| `RateLimitError` | Too many requests | +| `RateLimitError` | HTTP 429. Too many requests. `error.retryAfterMs` is the wait the API asked for, when it sent a `Retry-After` header. | | `FeatureNotEnabledError` | Feature is not enabled for the account, for example trade intelligence or routing data | | `UpstreamError` | Carrier or terminal API is unavailable | | `Terminal49Error` | Generic error fallback | @@ -47,8 +47,9 @@ try { } else if (error instanceof NotFoundError) { console.error('Container not found'); } else if (error instanceof RateLimitError) { - console.error('Rate limited, retrying in 60s'); - await new Promise((resolve) => setTimeout(resolve, 60000)); + const waitMs = error.retryAfterMs ?? 60000; + console.error(`Rate limited, retrying in ${waitMs / 1000}s`); + await new Promise((resolve) => setTimeout(resolve, waitMs)); } else { throw error; } diff --git a/docs/sdk/reference/client/classes/RateLimitError.mdx b/docs/sdk/reference/client/classes/RateLimitError.mdx index 4d31432a..172f20f4 100644 --- a/docs/sdk/reference/client/classes/RateLimitError.mdx +++ b/docs/sdk/reference/client/classes/RateLimitError.mdx @@ -15,7 +15,7 @@ Thrown when the API rate limit has been exceeded (HTTP 429). The SDK retries aut ### Constructor -> **new RateLimitError**(`message`, `status?`, `details?`): `RateLimitError` +> **new RateLimitError**(`message`, `status?`, `details?`, `retryAfterMs?`): `RateLimitError` #### Parameters @@ -24,6 +24,7 @@ Thrown when the API rate limit has been exceeded (HTTP 429). The SDK retries aut | `message` | `string` | `undefined` | | `status?` | `number` | `429` | | `details?` | `unknown` | `undefined` | +| `retryAfterMs?` | `number` | `undefined` | #### Returns @@ -41,6 +42,7 @@ Thrown when the API rate limit has been exceeded (HTTP 429). The SDK retries aut | `details?` | `public` | `unknown` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`details`](/sdk/reference/client/classes/Terminal49Error#property-details) | | `message` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`message`](/sdk/reference/client/classes/Terminal49Error#property-message) | | `name` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`name`](/sdk/reference/client/classes/Terminal49Error#property-name) | +| `retryAfterMs?` | `public` | `number` | How long the API asked the caller to wait, from its `Retry-After` header. Undefined when it sent none. | - | | `stack?` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`stack`](/sdk/reference/client/classes/Terminal49Error#property-stack) | | `status?` | `public` | `number` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`status`](/sdk/reference/client/classes/Terminal49Error#property-status) | | `stackTraceLimit` | `static` | `number` | The `Error.stackTraceLimit` property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`stackTraceLimit`](/sdk/reference/client/classes/Terminal49Error#property-stacktracelimit) | diff --git a/packages/mcp/src/logging.test.ts b/packages/mcp/src/logging.test.ts index 1ca73e07..97a42c49 100644 --- a/packages/mcp/src/logging.test.ts +++ b/packages/mcp/src/logging.test.ts @@ -8,6 +8,8 @@ import { } from 'vite-plus/test'; import { sanitizeMcpLogEvent, logMcpEvent } from './logging.js'; +const CONFIRMATION_TOKEN = `t49ct1.k9x2m1.${'A'.repeat(43)}.${'B'.repeat(43)}`; + describe('sanitizeMcpLogEvent', () => { it('redacts sensitive keys', () => { const input = { @@ -127,6 +129,20 @@ describe('sanitizeMcpLogEvent', () => { }); }); + it('redacts confirmation tokens from values under any key', () => { + const result = sanitizeMcpLogEvent({ + event: 'test', + detail: `sent ${CONFIRMATION_TOKEN}`, + nested: { tokens: [CONFIRMATION_TOKEN] }, + }); + + expect(result).toEqual({ + event: 'test', + detail: 'sent [REDACTED_CONFIRMATION_TOKEN]', + nested: { tokens: ['[REDACTED_CONFIRMATION_TOKEN]'] }, + }); + }); + it('preserves non-sensitive operational fields', () => { const input = { event: 'tool.execute.complete', diff --git a/packages/mcp/src/logging.ts b/packages/mcp/src/logging.ts index 9a6b092c..82f30742 100644 --- a/packages/mcp/src/logging.ts +++ b/packages/mcp/src/logging.ts @@ -1,4 +1,4 @@ -import { redactSignedUrls } from './signed-urls.js'; +import { redactSecrets } from './redaction.js'; const REDACTED_VALUE = '[REDACTED]'; @@ -68,7 +68,7 @@ function sanitizeValue(value: unknown): unknown { } if (typeof value === 'string') { - return redactSignedUrls(value); + return redactSecrets(value); } return value; @@ -76,7 +76,7 @@ function sanitizeValue(value: unknown): unknown { /** * Removes customer identifiers, request inputs, credentials, signed URLs, - * and upstream messages before an operational MCP event is serialized to stderr. + * confirmation tokens and upstream messages before an operational MCP event is serialized to stderr. */ export function sanitizeMcpLogEvent( event: Record, diff --git a/packages/mcp/src/posthog.test.ts b/packages/mcp/src/posthog.test.ts index 7f881e06..085b2e27 100644 --- a/packages/mcp/src/posthog.test.ts +++ b/packages/mcp/src/posthog.test.ts @@ -25,6 +25,8 @@ vi.mock('@posthog/mcp', async () => { return { ...actual, instrument: instrumentMock, PostHog: FakePostHog }; }); +const CONFIRMATION_TOKEN = `t49ct1.k9x2m1.${'A'.repeat(43)}.${'B'.repeat(43)}`; + /** Re-import with fresh module state, since the client is a module-level singleton. */ async function loadPostHogModule() { vi.resetModules(); @@ -333,6 +335,21 @@ describe('PostHog MCP analytics', () => { }); }); + it('redacts confirmation tokens from the properties it keeps', async () => { + const result = (await redact({ + event: '$mcp_tool_call', + properties: { + $mcp_tool_name: 'stop_shipment_tracking', + $mcp_result_note: `token ${CONFIRMATION_TOKEN}`, + }, + })) as { properties: Record }; + + expect(result.properties).toEqual({ + $mcp_tool_name: 'stop_shipment_tracking', + $mcp_result_note: 'token [REDACTED_CONFIRMATION_TOKEN]', + }); + }); + it('leaves an event with nothing sensitive unchanged', async () => { const result = (await redact({ event: '$mcp_initialize', diff --git a/packages/mcp/src/posthog.ts b/packages/mcp/src/posthog.ts index 0c512069..223185d3 100644 --- a/packages/mcp/src/posthog.ts +++ b/packages/mcp/src/posthog.ts @@ -18,7 +18,7 @@ */ import type { McpServer } from '@modelcontextprotocol/server'; import type { BeforeSendFn, UserIdentity } from '@posthog/mcp'; -import { redactSignedUrlsDeep } from './signed-urls.js'; +import { redactSecretsDeep } from './redaction.js'; // `PostHog` is imported from `@posthog/mcp`'s re-export rather than from // `posthog-node` directly, and deliberately so. `posthog-node` is a *peer* // dependency of `@posthog/mcp`, and this monorepo also carries a transitive @@ -158,7 +158,7 @@ export function initializePostHogFromEnv( /** * `beforeSend` hook. Drops `$exception` events wholesale, strips * customer-identifying properties from everything else, and redacts signed - * URLs from what remains. + * URLs and confirmation tokens from what remains. */ const redactSensitiveProperties: BeforeSendFn = (event) => { // `enableExceptionAutocapture: false` below should mean these never appear. @@ -175,7 +175,7 @@ const redactSensitiveProperties: BeforeSendFn = (event) => { } } - event.properties = redactSignedUrlsDeep(event.properties); + event.properties = redactSecretsDeep(event.properties); return event; }; @@ -278,6 +278,35 @@ export function instrumentMcpServerWithPostHog( return server; } +/** + * Capture one server-side event for an account. The caller passes only + * properties it has already scrubbed. No-op when PostHog is not configured. + */ +export function captureMcpEvent( + event: string, + accountId: string, + properties: Record, +): void { + if (!client) { + return; + } + + try { + client.capture({ + distinctId: accountId, + event, + properties: { + ...properties, + mcp_server_name: SERVER_NAME, + mcp_server_version: SERVER_VERSION, + }, + groups: { account: accountId }, + }); + } catch { + // Analytics must never fail a tool call. + } +} + /** Bound a promise so a slow/unreachable PostHog host cannot stall a request. */ async function withTimeout( work: Promise, diff --git a/packages/mcp/src/redaction.test.ts b/packages/mcp/src/redaction.test.ts new file mode 100644 index 00000000..3a459d06 --- /dev/null +++ b/packages/mcp/src/redaction.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + REDACTED_CONFIRMATION_TOKEN, + redactSecrets, + redactSecretsDeep, +} from './redaction.js'; +import { REDACTED_URL } from './signed-urls.js'; +import { issueConfirmationToken } from './tools/write-kit.js'; + +const S3_URL = + 'https://t49-documents-prod.s3.amazonaws.com/abc/invoice.pdf?X-Amz-Date=20261017T120000Z&X-Amz-Expires=3600&X-Amz-Signature=deadbeef'; + +const { confirmation_token: TOKEN } = issueConfirmationToken( + 'a-test-secret-that-is-long-enough-to-sign', + { + tool: 'stop_shipment_tracking', + args: { shipment_id: '1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a' }, + accountId: 'b7e2c9a1-5d3f-4e8b-9c0a-1f2e3d4c5b6a', + credentialHash: 'hash', + channel: 'token', + }, + 'fingerprint', +); + +describe('redactSecrets', () => { + it('replaces a confirmation token inside text and JSON', () => { + expect(redactSecrets(`token ${TOKEN} sent`)).toBe( + `token ${REDACTED_CONFIRMATION_TOKEN} sent`, + ); + expect(redactSecrets(JSON.stringify({ confirmation_token: TOKEN }))).toBe( + JSON.stringify({ confirmation_token: REDACTED_CONFIRMATION_TOKEN }), + ); + }); + + it('replaces signed URLs too', () => { + expect(redactSecrets(`see ${S3_URL}`)).toBe(`see ${REDACTED_URL}`); + }); + + it('keeps text without secrets', () => { + const text = 'Stopped tracking shipment MAEU123456789 at 2026-10-17'; + expect(redactSecrets(text)).toBe(text); + }); +}); + +describe('redactSecretsDeep', () => { + it('redacts strings at any depth and keeps everything else', () => { + const input = { + count: 2, + ok: true, + empty: null, + nested: [{ uri: S3_URL, name: 'invoice.pdf' }, TOKEN], + }; + + expect(redactSecretsDeep(input)).toEqual({ + count: 2, + ok: true, + empty: null, + nested: [ + { uri: REDACTED_URL, name: 'invoice.pdf' }, + REDACTED_CONFIRMATION_TOKEN, + ], + }); + expect(input.nested[1]).toBe(TOKEN); + }); +}); diff --git a/packages/mcp/src/redaction.ts b/packages/mcp/src/redaction.ts new file mode 100644 index 00000000..1a066e59 --- /dev/null +++ b/packages/mcp/src/redaction.ts @@ -0,0 +1,54 @@ +/** + * Removes secrets that can appear inside tool payloads, such as presigned + * download URLs and write confirmation tokens, before text reaches logs, + * Sentry or PostHog. + */ +import { redactSignedUrls } from './signed-urls.js'; + +/** Starts every confirmation token, so telemetry can find and drop them. */ +export const CONFIRMATION_TOKEN_PREFIX = 't49ct1'; + +export const REDACTED_CONFIRMATION_TOKEN = '[REDACTED_CONFIRMATION_TOKEN]'; + +const CONFIRMATION_TOKEN_PATTERN = new RegExp( + `\\b${CONFIRMATION_TOKEN_PREFIX}\\.[0-9a-z]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+`, + 'g', +); + +/** Replaces signed URLs and confirmation tokens in `text`. */ +export function redactSecrets(text: string): string { + return redactSignedUrls(text).replace( + CONFIRMATION_TOKEN_PATTERN, + REDACTED_CONFIRMATION_TOKEN, + ); +} + +/** + * A copy of `value` with {@link redactSecrets} applied to every string in it. + * Only arrays and plain objects are walked; other objects are returned as + * they are. + */ +export function redactSecretsDeep(value: T): T { + if (typeof value === 'string') { + // SAFETY: a string input yields a string output. + return redactSecrets(value) as T; + } + if (Array.isArray(value)) { + // SAFETY: mapping an array element-wise keeps its type. + return value.map((item) => redactSecretsDeep(item)) as T; + } + const prototype = + value !== null && typeof value === 'object' + ? Object.getPrototypeOf(value) + : undefined; + if (prototype === Object.prototype || prototype === null) { + // SAFETY: the copy has the same keys, with each value redacted in place. + return Object.fromEntries( + Object.entries(value as object).map(([key, nested]) => [ + key, + redactSecretsDeep(nested), + ]), + ) as T; + } + return value; +} diff --git a/packages/mcp/src/sentry.test.ts b/packages/mcp/src/sentry.test.ts index 87d79f29..a348fe9e 100644 --- a/packages/mcp/src/sentry.test.ts +++ b/packages/mcp/src/sentry.test.ts @@ -13,6 +13,8 @@ const SECRET_VALUES = [ 'BYPASS-SENTINEL-0000', ]; +const CONFIRMATION_TOKEN = `t49ct1.k9x2m1.${'A'.repeat(43)}.${'B'.repeat(43)}`; + const CREDENTIAL_HEADERS = { authorization: `Token ${SECRET_VALUES[0]}`, // `prefs` is not a cookie name Sentry recognizes as sensitive. @@ -105,6 +107,38 @@ describe('scrubSensitiveRequestData', () => { }); }); + it('redacts confirmation tokens from recorded tool arguments and results', () => { + const event = scrubSensitiveRequestData({ + breadcrumbs: [{ category: 'console', message: CONFIRMATION_TOKEN }], + spans: [ + { + span_id: 'c', + trace_id: 't', + start_timestamp: 0, + data: { + 'mcp.tool.name': 'stop_shipment_tracking', + 'mcp.request.argument.confirmation_token': + JSON.stringify(CONFIRMATION_TOKEN), + 'mcp.tool.result.content': JSON.stringify({ + confirmation_token: CONFIRMATION_TOKEN, + }), + }, + }, + ], + }); + + expect(event.breadcrumbs?.[0]?.message).toBe( + '[REDACTED_CONFIRMATION_TOKEN]', + ); + expect(event.spans?.[0]?.data).toEqual({ + 'mcp.tool.name': 'stop_shipment_tracking', + 'mcp.request.argument.confirmation_token': + '"[REDACTED_CONFIRMATION_TOKEN]"', + 'mcp.tool.result.content': + '{"confirmation_token":"[REDACTED_CONFIRMATION_TOKEN]"}', + }); + }); + it('leaves events without request or span data untouched', () => { expect(scrubSensitiveRequestData({ message: 'no request' })).toEqual({ message: 'no request', diff --git a/packages/mcp/src/sentry.ts b/packages/mcp/src/sentry.ts index 5e2a028f..005095af 100644 --- a/packages/mcp/src/sentry.ts +++ b/packages/mcp/src/sentry.ts @@ -1,6 +1,6 @@ import type { McpServer } from '@modelcontextprotocol/server'; import * as Sentry from '@sentry/node'; -import { redactSignedUrlsDeep } from './signed-urls.js'; +import { redactSecretsDeep } from './redaction.js'; type Environment = NodeJS.ProcessEnv; @@ -107,9 +107,10 @@ export function scrubSensitiveRequestData(event: T): T { scrubSpanData(span.data); } - // A tool result can carry a presigned download URL, which Sentry's MCP - // integration records as a span attribute when outputs are recorded. - return redactSignedUrlsDeep(event); + // A tool result can carry a presigned download URL or a confirmation + // token, which Sentry's MCP integration records as span attributes when + // outputs are recorded. + return redactSecretsDeep(event); } export function buildSentryOptions( @@ -178,6 +179,16 @@ export function captureMcpException(error: unknown): void { } } +/** Records a breadcrumb that later Sentry events in this request carry. */ +export function addMcpBreadcrumb( + category: string, + data: Record, +): void { + if (Sentry.isInitialized()) { + Sentry.addBreadcrumb({ category, level: 'info', data }); + } +} + export async function flushMcpEvents(timeoutMs = 2000): Promise { if (!Sentry.isInitialized()) { return; diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index d564d51f..9798d051 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -2,6 +2,7 @@ * Terminal49 MCP Server * Implementation using the MCP TypeScript SDK v2 McpServer API */ +import { credentialHash } from './tools/write-kit.js'; import { serveStdio } from '@modelcontextprotocol/server/stdio'; import { completable, @@ -1219,6 +1220,7 @@ export function createTerminal49McpServer( readOnly: options.readOnly ?? false, }); const session: ToolSession = { + credentialHash: credentialHash(apiToken), credentialType: options.credentialType ?? 'api_key', toolsets, writeToolsAvailable: selectedTools.some( diff --git a/packages/mcp/src/signed-urls.test.ts b/packages/mcp/src/signed-urls.test.ts index 32735c8a..ac69f29e 100644 --- a/packages/mcp/src/signed-urls.test.ts +++ b/packages/mcp/src/signed-urls.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vite-plus/test'; -import { - REDACTED_URL, - redactSignedUrls, - redactSignedUrlsDeep, -} from './signed-urls.js'; +import { REDACTED_URL, redactSignedUrls } from './signed-urls.js'; const S3_URL = 'https://t49-documents-prod.s3.amazonaws.com/abc/invoice.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA%2F20261017&X-Amz-Date=20261017T120000Z&X-Amz-Expires=3600&X-Amz-Signature=deadbeef'; @@ -39,22 +35,3 @@ describe('redactSignedUrls', () => { ); }); }); - -describe('redactSignedUrlsDeep', () => { - it('redacts strings at any depth and keeps everything else', () => { - const input = { - count: 2, - ok: true, - empty: null, - nested: [{ uri: S3_URL, name: 'invoice.pdf' }, S3_URL], - }; - - expect(redactSignedUrlsDeep(input)).toEqual({ - count: 2, - ok: true, - empty: null, - nested: [{ uri: REDACTED_URL, name: 'invoice.pdf' }, REDACTED_URL], - }); - expect(input.nested[1]).toBe(S3_URL); - }); -}); diff --git a/packages/mcp/src/signed-urls.ts b/packages/mcp/src/signed-urls.ts index a57465ba..74dd79fe 100644 --- a/packages/mcp/src/signed-urls.ts +++ b/packages/mcp/src/signed-urls.ts @@ -22,32 +22,3 @@ export function redactSignedUrls(text: string): string { isSignedUrl(url) ? REDACTED_URL : url, ); } - -/** - * A copy of `value` with signed URLs redacted from every string in it. Only - * arrays and plain objects are walked; other objects are returned as they are. - */ -export function redactSignedUrlsDeep(value: T): T { - if (typeof value === 'string') { - // SAFETY: a string input yields a string output. - return redactSignedUrls(value) as T; - } - if (Array.isArray(value)) { - // SAFETY: mapping an array element-wise keeps its type. - return value.map((item) => redactSignedUrlsDeep(item)) as T; - } - const prototype = - value !== null && typeof value === 'object' - ? Object.getPrototypeOf(value) - : undefined; - if (prototype === Object.prototype || prototype === null) { - // SAFETY: the copy has the same keys, with each value redacted in place. - return Object.fromEntries( - Object.entries(value as object).map(([key, nested]) => [ - key, - redactSignedUrlsDeep(nested), - ]), - ) as T; - } - return value; -} diff --git a/packages/mcp/src/tools/context.test.ts b/packages/mcp/src/tools/context.test.ts index dc58e17b..eb097f8d 100644 --- a/packages/mcp/src/tools/context.test.ts +++ b/packages/mcp/src/tools/context.test.ts @@ -7,10 +7,16 @@ const session = ( credentialType, toolsets: ['core'], writeToolsAvailable: false, + credentialHash: 'hash', }); +const ACCOUNT_ID = 'b7e2c9a1-5d3f-4e8b-9c0a-1f2e3d4c5b6a'; +const GATEWAY_ACCOUNT_ID = 'c8f3d0b2-6e4a-4f9c-8d1b-2a3f4e5d6c7b'; + function stubClient() { - const me = vi.fn().mockResolvedValue({ id: 'key-1' }); + const me = vi + .fn() + .mockResolvedValue({ id: 'key-1', account: { id: ACCOUNT_ID } }); return { client: { me }, me }; } @@ -21,7 +27,7 @@ describe('createToolContext', () => { const [first, second] = await Promise.all([context.me(), context.me()]); - expect(first).toEqual({ id: 'key-1' }); + expect(first).toEqual({ id: 'key-1', account: { id: ACCOUNT_ID } }); expect(second).toBe(first); expect(me).toHaveBeenCalledOnce(); expect(me).toHaveBeenCalledWith({ format: 'mapped' }); @@ -44,6 +50,7 @@ describe('createToolContext', () => { credentialType: 'agent', toolsets: ['core', 'documents'], writeToolsAvailable: true, + credentialHash: 'hash', }), ).toMatchObject({ credentialType: 'agent', @@ -51,4 +58,63 @@ describe('createToolContext', () => { writeToolsAvailable: true, }); }); + + it('acts on the account the gateway resolved without reading /me', async () => { + const { client, me } = stubClient(); + const context = createToolContext(client, { + ...session('user'), + gatewayAccountId: GATEWAY_ACCOUNT_ID, + }); + + await expect(context.accountId()).resolves.toBe(GATEWAY_ACCOUNT_ID); + expect(me).not.toHaveBeenCalled(); + }); + + it('takes the account from /me when the gateway resolved none', async () => { + const { client, me } = stubClient(); + const context = createToolContext(client, session('api_key')); + + await expect(context.accountId()).resolves.toBe(ACCOUNT_ID); + await context.me(); + expect(me).toHaveBeenCalledOnce(); + }); + + it('keys an API key session by its token hash without reading /me', async () => { + const { client, me } = stubClient(); + + await expect( + createToolContext(client, session('api_key')).credentialKey(), + ).resolves.toBe('hash'); + await expect( + createToolContext(client, session('shared_token')).credentialKey(), + ).resolves.toBe('hash'); + expect(me).not.toHaveBeenCalled(); + }); + + it.each(['user', 'agent'] as const)( + 'keys a %s session by the credential /me names, not its bearer token', + async (credentialType) => { + const me = vi.fn().mockResolvedValue({ + id: 'user-1', + kind: 'user', + account: { id: ACCOUNT_ID }, + }); + const key = (credentialHash: string) => + createToolContext( + { me }, + { ...session(credentialType), credentialHash }, + ).credentialKey(); + + const first = await key('bearer-1'); + expect(first).toMatch(/^[0-9a-f]{64}$/); + await expect(key('bearer-2')).resolves.toBe(first); + + me.mockResolvedValueOnce({ + id: 'user-2', + kind: 'user', + account: { id: ACCOUNT_ID }, + }); + await expect(key('bearer-1')).resolves.not.toBe(first); + }, + ); }); diff --git a/packages/mcp/src/tools/context.ts b/packages/mcp/src/tools/context.ts index 37ea8bff..e3c434bb 100644 --- a/packages/mcp/src/tools/context.ts +++ b/packages/mcp/src/tools/context.ts @@ -1,4 +1,7 @@ +import { createHash } from 'node:crypto'; +import { CLIENT_CAPABILITIES_META_KEY } from '@modelcontextprotocol/server'; import type { CurrentCredential, Terminal49Client } from '@terminal49/sdk'; +import { z } from 'zod'; import type { Toolset } from './registry.js'; /** @@ -21,25 +24,140 @@ export interface ToolSession { toolsets: readonly Toolset[]; /** Whether any registered tool can change account data. */ writeToolsAvailable: boolean; + /** sha256 of the API token the session calls Terminal49 with. */ + credentialHash: string; + /** Signs confirmation tokens. Undefined when the server has no usable secret. */ + confirmationSecret?: string; + /** The account the gateway resolved for the credential, when it resolved one. */ + gatewayAccountId?: string; + /** + * Epoch ms by which a batch write stops waiting on records. The HTTP + * gateway sets it from the request start so sign-in time counts against + * the function limit; without it each call budgets from its own start. + */ + writeDeadlineAt?: number; +} + +/** What the user answered when the client asked them to confirm a preview. */ +export type ElicitationAnswer = + | { action: 'accept'; confirm: boolean } + | { action: 'decline' } + | { action: 'cancel' }; + +/** + * How a tier C call gets the user's approval of its preview. A request that + * declares form elicitation (the 2026-07-28 `_meta` envelope) lets the client + * ask the user itself, so the model never handles a confirmation token. Any + * other request gets the preview and a token to pass back. + */ +export type ConfirmationChannel = + | { kind: 'token' } + | { + kind: 'elicitation'; + /** The requestState the client echoed from the previous round. */ + requestState: string | undefined; + /** The client's answer to the confirm request, on a retried call. */ + answer: ElicitationAnswer | undefined; + }; + +/** The key of the one input request a tier C tool embeds. */ +export const CONFIRM_REQUEST_KEY = 'confirm'; + +/** A bare `elicitation: {}` declares form mode, as the SDK reads it. */ +const formElicitationSchema = z.object({ + elicitation: z + .object({ form: z.unknown().optional(), url: z.unknown().optional() }) + .refine((modes) => modes.form !== undefined || modes.url === undefined), +}); + +const answerSchema = z.union([ + z.object({ + action: z.literal('accept'), + content: z.object({ confirm: z.boolean().catch(false) }).catch({ + confirm: false, + }), + }), + z.object({ action: z.literal('decline') }), + z.object({ action: z.literal('cancel') }), +]); + +/** The parts of the MCP request context a confirmation channel is read from. */ +export interface ConfirmationRequest { + envelope?: Record; + inputResponses?: Record; + requestState: () => T | undefined; +} + +/** + * Reads the confirmation channel of one request from its MCP context. A + * request with no context, or no 2026-07-28 envelope, uses the token channel. + */ +export function confirmationChannel( + request: Partial | undefined, +): ConfirmationChannel { + const capabilities = request?.envelope?.[CLIENT_CAPABILITIES_META_KEY]; + if (!request || !formElicitationSchema.safeParse(capabilities).success) { + return { kind: 'token' }; + } + const state = request.requestState?.(); + const answer = answerSchema.safeParse( + request.inputResponses?.[CONFIRM_REQUEST_KEY], + ); + return { + kind: 'elicitation', + requestState: typeof state === 'string' ? state : undefined, + answer: answer.success + ? answer.data.action === 'accept' + ? { action: 'accept', confirm: answer.data.content.confirm } + : { action: answer.data.action } + : undefined, + }; } /** State shared by everything one tool call does. */ export interface ToolContext extends ToolSession { + /** How this call gets the user's approval of a tier C preview. */ + confirmation: ConfirmationChannel; /** GET /me, fetched at most once per tool call. */ me(): Promise; + /** The account this call acts on: the gateway's, else the one /me names. */ + accountId(): Promise; + /** + * The credential confirmation tokens are bound to. A user or agent session + * uses the credential /me names, because the gateway can call Terminal49 + * with a new bearer token on every request. Other sessions use the API + * token hash. + */ + credentialKey(): Promise; } export function createToolContext( client: Pick, session: ToolSession, + confirmation: ConfirmationChannel = { kind: 'token' }, ): ToolContext { let me: Promise | undefined; - return { + const context: ToolContext = { ...session, + confirmation, me() { // SAFETY: `format: 'mapped'` makes the SDK return mapCurrentCredential's result. me ??= client.me({ format: 'mapped' }) as Promise; return me; }, + async accountId() { + return session.gatewayAccountId ?? (await context.me()).account.id; + }, + async credentialKey() { + if ( + session.credentialType === 'api_key' || + session.credentialType === 'shared_token' + ) { + return session.credentialHash; + } + const { kind, id } = await context.me(); + return createHash('sha256').update(`${kind}:${id}`).digest('hex'); + }, }; + return context; } diff --git a/packages/mcp/src/tools/whoami.test.ts b/packages/mcp/src/tools/whoami.test.ts index 5602ba8d..724cef26 100644 --- a/packages/mcp/src/tools/whoami.test.ts +++ b/packages/mcp/src/tools/whoami.test.ts @@ -15,8 +15,12 @@ function contextReturning( credentialType: 'api_key', toolsets: ['core', 'documents'], writeToolsAvailable: true, + credentialHash: 'hash', + confirmation: { kind: 'token' }, ...session, me: meFn, + accountId: async () => me.account.id, + credentialKey: async () => 'hash', }; return { context, me: meFn }; } diff --git a/packages/mcp/src/tools/write-audit.test.ts b/packages/mcp/src/tools/write-audit.test.ts new file mode 100644 index 00000000..794f4d3b --- /dev/null +++ b/packages/mcp/src/tools/write-audit.test.ts @@ -0,0 +1,176 @@ +/** + * Proves a write's audit event reaches the log, Sentry and PostHog with only + * the fields it names, and that no value, reference number, party name, + * signed URL, confirmation token or API token can ride along. + */ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vite-plus/test'; + +const breadcrumbs = vi.hoisted(() => [] as unknown[]); +const captured = vi.hoisted(() => [] as unknown[]); + +vi.mock('@sentry/node', () => ({ + isInitialized: () => true, + addBreadcrumb: (breadcrumb: unknown) => breadcrumbs.push(breadcrumb), + captureException: vi.fn(), + flush: vi.fn().mockResolvedValue(true), + wrapMcpServerWithSentry: (server: unknown) => server, +})); + +vi.mock('@posthog/mcp', async () => { + const actual = + await vi.importActual('@posthog/mcp'); + class FakePostHog { + capture(message: unknown) { + captured.push(message); + } + flush = vi.fn().mockResolvedValue(undefined); + shutdown = vi.fn().mockResolvedValue(undefined); + } + return { ...actual, PostHog: FakePostHog }; +}); + +import { initializePostHogFromEnv } from '../posthog.js'; +import { + buildWriteAuditEvent, + emitWriteAudit, + issueConfirmationToken, + type WriteAuditInput, +} from './write-kit.js'; + +const ACCOUNT_ID = 'b7e2c9a1-5d3f-4e8b-9c0a-1f2e3d4c5b6a'; +const REQUEST_ID = '1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a'; +const TOKEN = issueConfirmationToken( + 'a-test-secret-that-is-long-enough-to-sign', + { + tool: 'stop_shipment_tracking', + args: {}, + accountId: ACCOUNT_ID, + credentialHash: 'hash', + channel: 'token', + }, + 'fingerprint', +).confirmation_token; + +const FORBIDDEN = [ + 'PO-SENTINEL-77', + 'Acme Party Sentinel', + 'CUSTOM-VALUE-SENTINEL', + 'X-Amz-Signature=SIG-SENTINEL', + TOKEN, + 'API-TOKEN-SENTINEL', +]; + +const input: WriteAuditInput = { + tool: 'track_container', + tier: 'A', + phase: 'execute', + outcome: 'created', + entityType: 'tracking_request', + entityId: REQUEST_ID, + accountId: ACCOUNT_ID, + credentialType: 'user', +}; + +/** An input carrying extra fields and unsafe values, as a buggy caller might pass. */ +const polluted = { + ...input, + outcome: `created ${FORBIDDEN[2]}`, + entityId: FORBIDDEN[0], + accountId: `https://x.test/a?${FORBIDDEN[3]}`, + ref_numbers: [FORBIDDEN[0]], + party_name: FORBIDDEN[1], + value: FORBIDDEN[2], + confirmation_token: TOKEN, + apiToken: FORBIDDEN[5], +} as unknown as WriteAuditInput; + +describe('write audit event', () => { + let logged: string[]; + + beforeAll(() => { + vi.stubEnv('POSTHOG_PROJECT_API_KEY', 'phc_test'); + initializePostHogFromEnv(); + }); + + afterAll(() => { + vi.unstubAllEnvs(); + }); + + beforeEach(() => { + logged = []; + breadcrumbs.length = 0; + captured.length = 0; + vi.spyOn(console, 'error').mockImplementation((line: string) => { + logged.push(line); + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('names the tool, tier, phase, outcome, entity, account and credential type', () => { + expect(buildWriteAuditEvent(input)).toEqual({ + tool: 'track_container', + tier: 'A', + phase: 'execute', + outcome: 'created', + entity_type: 'tracking_request', + entity_id: REQUEST_ID, + account_id: ACCOUNT_ID, + credential_type: 'user', + }); + }); + + it('sends the same event to the log, Sentry and PostHog', () => { + emitWriteAudit(input); + const audit = buildWriteAuditEvent(input); + + expect(logged).toHaveLength(1); + expect(JSON.parse(logged[0]!)).toMatchObject({ + event: 'mcp.write.audit', + ...audit, + }); + expect(breadcrumbs).toEqual([ + { category: 'mcp.write.audit', level: 'info', data: audit }, + ]); + expect(captured).toEqual([ + expect.objectContaining({ + distinctId: ACCOUNT_ID, + event: 'mcp_write', + properties: expect.objectContaining(audit), + }), + ]); + }); + + it('keeps every unsafe value and extra field out of every sink', () => { + emitWriteAudit(polluted); + + const sinks = JSON.stringify({ logged, breadcrumbs, captured }); + for (const value of FORBIDDEN) { + expect(sinks).not.toContain(value); + } + expect(buildWriteAuditEvent(polluted)).toEqual({ + ...buildWriteAuditEvent(input), + outcome: 'unknown', + entity_id: null, + account_id: null, + }); + }); + + it('skips PostHog when the account is not known', () => { + emitWriteAudit({ ...input, accountId: undefined }); + + expect(logged).toHaveLength(1); + expect(captured).toEqual([]); + }); +}); diff --git a/packages/mcp/src/tools/write-flow.test.ts b/packages/mcp/src/tools/write-flow.test.ts new file mode 100644 index 00000000..16fe4108 --- /dev/null +++ b/packages/mcp/src/tools/write-flow.test.ts @@ -0,0 +1,794 @@ +import { + afterEach, + beforeEach, + describe, + expect, + it, + vi, +} from 'vite-plus/test'; +import { CLIENT_CAPABILITIES_META_KEY } from '@modelcontextprotocol/server'; +import { + CONFIRM_REQUEST_KEY, + type ConfirmationChannel, + confirmationChannel, + createToolContext, + type ToolSession, +} from './context.js'; + +const captureMcpEvent = vi.hoisted(() => vi.fn()); +vi.mock('../posthog.js', async (importOriginal) => ({ + ...(await importOriginal()), + captureMcpEvent, +})); + +import { + CONFIRMATION_TTL_MS, + runConfirmedWrite, + runWrite, + type ConfirmedWriteRead, +} from './write-kit.js'; + +const SECRET = 'a-test-secret-that-is-long-enough-to-sign'; +const ACCOUNT_ID = 'b7e2c9a1-5d3f-4e8b-9c0a-1f2e3d4c5b6a'; +const OTHER_ACCOUNT_ID = 'c8f3d0b2-6e4a-4f9c-8d1b-2a3f4e5d6c7b'; +const RECORD_ID = '1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a'; + +function context( + session: Partial = {}, + me = vi.fn().mockResolvedValue({ account: { id: ACCOUNT_ID } }), + confirmation: ConfirmationChannel = { kind: 'token' }, +) { + return createToolContext( + { me }, + { + credentialType: 'api_key', + toolsets: ['core'], + writeToolsAvailable: true, + credentialHash: 'credential-1', + confirmationSecret: SECRET, + ...session, + }, + confirmation, + ); +} + +/** A context for a request that declared form elicitation. */ +function elicitingContext( + round: Partial> = {}, + session: Partial = {}, +) { + return context(session, undefined, { + kind: 'elicitation', + requestState: undefined, + answer: undefined, + ...round, + }); +} + +/** The requestState an input_required result carries. */ +function stateOf(result: unknown): string { + const state = (result as { requestState?: unknown }).requestState; + if (typeof state !== 'string') { + throw new Error(`no requestState in ${JSON.stringify(result)}`); + } + return state; +} + +type Preview = { status: string }; +type Read = ConfirmedWriteRead; + +/** A record whose status the test can change between calls. */ +function record(initial = 'active') { + let status = initial; + const write = vi.fn(async () => { + status = 'changed'; + return { status: 'done' as const }; + }); + return { + write, + setStatus: (next: string) => { + status = next; + }, + plan: (args: Record) => ({ + tool: 'track_container' as const, + entityType: 'tracking_request' as const, + entityId: RECORD_ID, + args: { id: RECORD_ID, ...args }, + read: async (): Promise => + status === 'idle' + ? { stop: { status: 'nothing_to_do' } } + : status === 'additive' + ? { additive: { status } } + : { state: { status }, preview: { status } }, + write, + }), + }; +} + +/** Changes the first character of the token's state tag. */ +function flipStateTag(token: string): string { + const parts = token.split('.'); + const tag = parts[2] ?? ''; + parts[2] = (tag.startsWith('A') ? 'B' : 'A') + tag.slice(1); + return parts.join('.'); +} + +function auditLines(lines: string[]) { + return lines + .map((line) => JSON.parse(line)) + .filter((event) => event.event === 'mcp.write.audit'); +} + +describe('runConfirmedWrite', () => { + let logged: string[]; + + beforeEach(() => { + logged = []; + vi.spyOn(console, 'error').mockImplementation((line: string) => { + logged.push(line); + }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('previews without writing, then writes with the token', async () => { + const target = record(); + const ctx = context(); + + const preview = await runConfirmedWrite(ctx, target.plan({})); + expect(preview).toMatchObject({ + status: 'confirmation_required', + preview: { status: 'active' }, + confirmation_token: expect.stringMatching(/^t49ct1\./), + expires_at: expect.any(String), + }); + expect(target.write).not.toHaveBeenCalled(); + + const token = (preview as { confirmation_token: string }) + .confirmation_token; + await expect( + runConfirmedWrite(ctx, target.plan({ confirmation_token: token })), + ).resolves.toEqual({ status: 'done' }); + expect(target.write).toHaveBeenCalledOnce(); + expect(auditLines(logged)).toEqual([ + expect.objectContaining({ + phase: 'preview', + outcome: 'confirmation_required', + account_id: ACCOUNT_ID, + }), + expect.objectContaining({ phase: 'execute', outcome: 'done' }), + ]); + }); + + it('returns a new preview and does not write when the record changed', async () => { + const target = record(); + const ctx = context(); + const preview = await runConfirmedWrite(ctx, target.plan({})); + target.setStatus('paused'); + + const result = await runConfirmedWrite( + ctx, + target.plan({ + confirmation_token: (preview as { confirmation_token: string }) + .confirmation_token, + }), + ); + + expect(result).toMatchObject({ + status: 'stale_preview', + preview: { status: 'paused' }, + confirmation_token: expect.stringMatching(/^t49ct1\./), + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it.each([ + ['with an edited state tag', flipStateTag, {}], + ['for other arguments', (token: string) => token, { extra: true }], + ])( + 'refuses a token %s', + async (_label, edit, extraArgs: Record) => { + const target = record(); + const ctx = context(); + const preview = (await runConfirmedWrite(ctx, target.plan({}))) as { + confirmation_token: string; + }; + + const result = await runConfirmedWrite( + ctx, + target.plan({ + ...extraArgs, + confirmation_token: edit(preview.confirmation_token), + }), + ); + + expect(result).toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + expect(target.write).not.toHaveBeenCalled(); + }, + ); + + it('refuses a token from another account or credential', async () => { + const target = record(); + const preview = (await runConfirmedWrite(context(), target.plan({}))) as { + confirmation_token: string; + }; + const plan = target.plan({ + confirmation_token: preview.confirmation_token, + }); + + await expect( + runConfirmedWrite(context({ gatewayAccountId: OTHER_ACCOUNT_ID }), plan), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + await expect( + runConfirmedWrite(context({ credentialHash: 'credential-2' }), plan), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it('refuses an expired token', async () => { + vi.useFakeTimers({ now: Date.parse('2026-10-17T12:00:00Z') }); + const target = record(); + const ctx = context(); + const preview = (await runConfirmedWrite(ctx, target.plan({}))) as { + confirmation_token: string; + }; + vi.advanceTimersByTime(CONFIRMATION_TTL_MS); + + await expect( + runConfirmedWrite( + ctx, + target.plan({ confirmation_token: preview.confirmation_token }), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'expired', + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it('runs a change that needs no approval without a secret', async () => { + const target = record('additive'); + + await expect( + runConfirmedWrite( + context({ confirmationSecret: undefined }), + target.plan({}), + ), + ).resolves.toEqual({ status: 'done' }); + expect(target.write).toHaveBeenCalledTimes(1); + expect(logged.map((line) => JSON.parse(line).event)).not.toContain( + 'mcp.config.error', + ); + }); + + it('refuses to preview or write a change that needs approval without a secret, and logs why', async () => { + const target = record(); + const plan = target.plan({}); + const read = vi.spyOn(plan, 'read'); + const ctx = context({ confirmationSecret: undefined }); + + const result = await runConfirmedWrite(ctx, plan); + + expect(result).toMatchObject({ + error: 'not_permitted', + message: expect.stringContaining('T49_MCP_CONFIRMATION_SECRET'), + }); + expect(target.write).not.toHaveBeenCalled(); + expect(read).toHaveBeenCalledTimes(1); + expect(logged.map((line) => JSON.parse(line).event)).toContain( + 'mcp.config.error', + ); + expect(auditLines(logged)).toEqual([ + expect.objectContaining({ + outcome: 'not_permitted', + account_id: ACCOUNT_ID, + }), + ]); + }); + + it('returns the read result when there is nothing to confirm', async () => { + const target = record('idle'); + + await expect( + runConfirmedWrite(context(), target.plan({})), + ).resolves.toEqual({ status: 'nothing_to_do' }); + expect(target.write).not.toHaveBeenCalled(); + expect(auditLines(logged)).toEqual([ + expect.objectContaining({ + outcome: 'nothing_to_do', + account_id: ACCOUNT_ID, + }), + ]); + }); + + it('audits a write that throws and rethrows it', async () => { + const target = record(); + const ctx = context(); + target.write.mockRejectedValueOnce(new Error('upstream failed')); + const preview = (await runConfirmedWrite(ctx, target.plan({}))) as { + confirmation_token: string; + }; + + await expect( + runConfirmedWrite( + ctx, + target.plan({ confirmation_token: preview.confirmation_token }), + ), + ).rejects.toThrow('upstream failed'); + expect(auditLines(logged).at(-1)).toMatchObject({ outcome: 'error' }); + }); +}); + +describe('runConfirmedWrite on a request that can ask the user', () => { + let logged: string[]; + + beforeEach(() => { + logged = []; + vi.spyOn(console, 'error').mockImplementation((line: string) => { + logged.push(line); + }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('asks the client to confirm the preview and writes nothing', async () => { + const target = record(); + + const result = await runConfirmedWrite(elicitingContext(), target.plan({})); + + expect(result).toEqual({ + resultType: 'input_required', + inputRequests: { + confirm: { + method: 'elicitation/create', + params: { + mode: 'form', + message: + 'track_container on tracking_request 1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a\nstatus: "active"', + requestedSchema: { + type: 'object', + properties: { + confirm: { + type: 'boolean', + title: 'Confirm', + description: 'Make this change', + }, + }, + required: ['confirm'], + }, + }, + }, + }, + requestState: expect.stringMatching(/^t49ct1\./), + }); + expect(target.write).not.toHaveBeenCalled(); + expect(auditLines(logged)).toEqual([ + expect.objectContaining({ + phase: 'preview', + outcome: 'elicitation_required', + account_id: ACCOUNT_ID, + }), + ]); + }); + + it('writes once when the user accepts', async () => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + + const result = await runConfirmedWrite( + elicitingContext({ + requestState: stateOf(asked), + answer: { action: 'accept', confirm: true }, + }), + target.plan({}), + ); + + expect(result).toEqual({ status: 'done' }); + expect(target.write).toHaveBeenCalledOnce(); + expect(auditLines(logged).at(-1)).toMatchObject({ + phase: 'execute', + outcome: 'done', + }); + }); + + it.each([ + [ + 'declines', + { action: 'decline' } as const, + 'The user declined this change. Nothing was changed.', + ], + [ + 'cancels', + { action: 'cancel' } as const, + 'The user dismissed the confirmation without answering. Nothing was changed.', + ], + [ + 'accepts without ticking confirm', + { action: 'accept', confirm: false } as const, + 'The user declined this change. Nothing was changed.', + ], + ])('writes nothing when the user %s', async (_label, answer, message) => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + + const result = await runConfirmedWrite( + elicitingContext({ requestState: stateOf(asked), answer }), + target.plan({}), + ); + + expect(result).toEqual({ status: 'declined', message }); + expect(target.write).not.toHaveBeenCalled(); + expect(auditLines(logged).at(-1)).toMatchObject({ + phase: 'execute', + outcome: 'declined', + }); + }); + + it('leaves the confirmation unspent when the user declines', async () => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + const requestState = stateOf(asked); + await runConfirmedWrite( + elicitingContext({ requestState, answer: { action: 'decline' } }), + target.plan({}), + ); + + const result = await runConfirmedWrite( + elicitingContext({ + requestState, + answer: { action: 'accept', confirm: true }, + }), + target.plan({}), + ); + + expect(result).toEqual({ status: 'done' }); + expect(target.write).toHaveBeenCalledOnce(); + }); + + /** A context whose channel is parsed from what a client sent. */ + function answeredContext( + requestState: string | undefined, + response: unknown, + ) { + return context( + {}, + undefined, + confirmationChannel({ + envelope: { [CLIENT_CAPABILITIES_META_KEY]: { elicitation: {} } }, + inputResponses: { [CONFIRM_REQUEST_KEY]: response }, + requestState: () => requestState as T, + }), + ); + } + + it.each([ + ['no content', { action: 'accept' }], + ['null content', { action: 'accept', content: null }], + ['confirm "true"', { action: 'accept', content: { confirm: 'true' } }], + ['confirm 1', { action: 'accept', content: { confirm: 1 } }], + ])( + 'reads an accept with %s as a decline and writes nothing', + async (_label, response) => { + const target = record(); + const asked = await runConfirmedWrite( + elicitingContext(), + target.plan({}), + ); + + const result = await runConfirmedWrite( + answeredContext(stateOf(asked), response), + target.plan({}), + ); + + expect(result).toEqual({ + status: 'declined', + message: 'The user declined this change. Nothing was changed.', + }); + expect(target.write).not.toHaveBeenCalled(); + }, + ); + + it('asks again when an answer comes back without its requestState', async () => { + const target = record(); + + const result = await runConfirmedWrite( + answeredContext(undefined, { + action: 'accept', + content: { confirm: true }, + }), + target.plan({}), + ); + + expect(result).toMatchObject({ requestState: expect.any(String) }); + expect(target.write).not.toHaveBeenCalled(); + expect(auditLines(logged).at(-1)).toMatchObject({ + phase: 'preview', + outcome: 'elicitation_required', + }); + }); + + it('asks again, with a note, when the record changed before the user answered', async () => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + target.setStatus('paused'); + + const result = await runConfirmedWrite( + elicitingContext({ + requestState: stateOf(asked), + answer: { action: 'accept', confirm: true }, + }), + target.plan({}), + ); + + expect(result).toMatchObject({ + resultType: 'input_required', + inputRequests: { + confirm: { + params: { + message: + 'The record changed after you last saw it. Here is its current state.\n' + + 'track_container on tracking_request 1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a\n' + + 'status: "paused"', + }, + }, + }, + }); + expect(stateOf(result)).not.toBe(stateOf(asked)); + expect(target.write).not.toHaveBeenCalled(); + }); + + it.each([ + ['edited', (state: string) => flipStateTag(state), {}, 'mismatch'], + [ + 'sent with other arguments', + (state: string) => state, + { extra: true }, + 'mismatch', + ], + ['not one the server issued', () => 'not-a-state', {}, 'malformed'], + ])( + 'refuses a requestState that is %s', + async (_label, edit, extraArgs: Record, reason) => { + const target = record(); + const asked = await runConfirmedWrite( + elicitingContext(), + target.plan({}), + ); + + const result = await runConfirmedWrite( + elicitingContext({ + requestState: edit(stateOf(asked)), + answer: { action: 'accept', confirm: true }, + }), + target.plan(extraArgs), + ); + + expect(result).toEqual({ + error: 'invalid_confirmation', + reason, + message: expect.stringContaining('Nothing was changed.'), + alternative: + 'Call track_container again with the same arguments. The client will ask the user to confirm the current state.', + }); + expect(target.write).not.toHaveBeenCalled(); + }, + ); + + it('refuses a requestState from another account or credential', async () => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + const round = { + requestState: stateOf(asked), + answer: { action: 'accept', confirm: true } as const, + }; + + await expect( + runConfirmedWrite( + elicitingContext(round, { gatewayAccountId: OTHER_ACCOUNT_ID }), + target.plan({}), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + await expect( + runConfirmedWrite( + elicitingContext(round, { credentialHash: 'credential-2' }), + target.plan({}), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it('refuses an expired requestState', async () => { + vi.useFakeTimers({ now: Date.parse('2026-10-17T12:00:00Z') }); + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + vi.advanceTimersByTime(CONFIRMATION_TTL_MS); + + await expect( + runConfirmedWrite( + elicitingContext({ + requestState: stateOf(asked), + answer: { action: 'accept', confirm: true }, + }), + target.plan({}), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'expired', + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it('refuses a confirmation_token without reading the record', async () => { + const target = record(); + const plan = target.plan({ confirmation_token: 't49ct1.x.y.z' }); + const read = vi.spyOn(plan, 'read'); + + const result = await runConfirmedWrite(elicitingContext(), plan); + + expect(result).toEqual({ + error: 'token_not_accepted', + message: + 'This client asks the user to confirm changes itself, so a confirmation_token is not accepted here. Nothing was changed.', + alternative: + 'Call track_container again with the same arguments and no confirmation_token. The client will show the user the preview and ask them to confirm.', + }); + expect(read).not.toHaveBeenCalled(); + expect(target.write).not.toHaveBeenCalled(); + expect(auditLines(logged)).toEqual([ + expect.objectContaining({ + phase: 'execute', + outcome: 'token_not_accepted', + }), + ]); + }); + + it('never accepts a requestState as a confirmation_token, or a token as a requestState', async () => { + const target = record(); + const asked = await runConfirmedWrite(elicitingContext(), target.plan({})); + const preview = await runConfirmedWrite(context(), target.plan({})); + const token = (preview as { confirmation_token: string }) + .confirmation_token; + + await expect( + runConfirmedWrite( + context(), + target.plan({ confirmation_token: stateOf(asked) }), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + await expect( + runConfirmedWrite( + elicitingContext({ + requestState: token, + answer: { action: 'accept', confirm: true }, + }), + target.plan({}), + ), + ).resolves.toMatchObject({ + error: 'invalid_confirmation', + reason: 'mismatch', + }); + expect(target.write).not.toHaveBeenCalled(); + }); + + it('refuses to ask without a secret', async () => { + const target = record(); + + await expect( + runConfirmedWrite( + elicitingContext({}, { confirmationSecret: undefined }), + target.plan({}), + ), + ).resolves.toMatchObject({ error: 'not_permitted' }); + expect(target.write).not.toHaveBeenCalled(); + }); +}); + +describe('runWrite', () => { + let lines: string[]; + const target = { + tool: 'track_container' as const, + entityType: 'tracking_request' as const, + entityId: RECORD_ID, + }; + + beforeEach(() => { + lines = []; + captureMcpEvent.mockClear(); + vi.spyOn(console, 'error').mockImplementation((line: string) => { + lines.push(line); + }); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('audits the outcome of a tier A write', async () => { + await expect( + runWrite(context({ gatewayAccountId: ACCOUNT_ID }), target, async () => ({ + status: 'created', + })), + ).resolves.toEqual({ status: 'created' }); + expect(auditLines(lines)).toEqual([ + expect.objectContaining({ + tier: 'A', + phase: 'execute', + outcome: 'created', + account_id: ACCOUNT_ID, + }), + ]); + }); + + it('names the /me account and sends the event to PostHog when the gateway named none', async () => { + await runWrite(context(), target, async () => ({ status: 'created' })); + + expect(auditLines(lines)).toEqual([ + expect.objectContaining({ outcome: 'created', account_id: ACCOUNT_ID }), + ]); + expect(captureMcpEvent).toHaveBeenCalledWith( + 'mcp_write', + ACCOUNT_ID, + expect.objectContaining({ + tool: 'track_container', + outcome: 'created', + account_id: ACCOUNT_ID, + }), + ); + }); + + it('returns a write within seconds when /me hangs, and audits without an account', async () => { + vi.useFakeTimers(); + try { + const me = vi.fn(() => new Promise(() => {})); + const settled = vi.fn(); + void runWrite(context({}, me), target, async () => ({ + status: 'created', + })).then(settled); + + await vi.advanceTimersByTimeAsync(5_000); + + expect(settled).toHaveBeenCalledWith({ status: 'created' }); + expect(auditLines(lines)).toEqual([ + expect.objectContaining({ outcome: 'created', account_id: null }), + ]); + } finally { + vi.useRealTimers(); + } + }); + + it('still returns the result when /me fails, and audits without an account', async () => { + const me = vi.fn().mockRejectedValue(new Error('me failed')); + + await expect( + runWrite(context({}, me), target, async () => ({ status: 'created' })), + ).resolves.toEqual({ status: 'created' }); + expect(auditLines(lines)).toEqual([ + expect.objectContaining({ outcome: 'created', account_id: null }), + ]); + expect(captureMcpEvent).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/mcp/src/tools/write-kit.test.ts b/packages/mcp/src/tools/write-kit.test.ts new file mode 100644 index 00000000..8a893c81 --- /dev/null +++ b/packages/mcp/src/tools/write-kit.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { + canonicalJson, + checkConfirmationToken, + CONFIRMATION_TTL_MS, + type ConfirmationBinding, + credentialHash, + issueConfirmationToken, + stateFingerprint, + usableConfirmationSecret, +} from './write-kit.js'; + +const SECRET = 'a-test-secret-that-is-long-enough-to-sign'; +const NOW = Date.parse('2026-10-17T12:00:00Z'); +const ACCOUNT_ID = 'b7e2c9a1-5d3f-4e8b-9c0a-1f2e3d4c5b6a'; +const OTHER_ACCOUNT_ID = 'c8f3d0b2-6e4a-4f9c-8d1b-2a3f4e5d6c7b'; +const SHIPMENT_ID = '1f0e8a52-3c4d-4b6e-9f7a-8b9c0d1e2f3a'; + +const binding: ConfirmationBinding = { + tool: 'stop_shipment_tracking', + args: { shipment_id: SHIPMENT_ID }, + accountId: ACCOUNT_ID, + credentialHash: credentialHash('Token key-1'), + channel: 'token', +}; +const fingerprint = stateFingerprint({ tracking_stopped: false }); + +function issue(at = NOW) { + return issueConfirmationToken(SECRET, binding, fingerprint, at) + .confirmation_token; +} + +function check( + token: string, + overrides: Partial = {}, + options: { at?: number; fingerprint?: string; secret?: string } = {}, +) { + return checkConfirmationToken( + options.secret ?? SECRET, + token, + { ...binding, ...overrides }, + options.fingerprint ?? fingerprint, + options.at ?? NOW + 1000, + ); +} + +describe('confirmation token', () => { + it('accepts a token for the same call, account, credential and state', () => { + expect(check(issue())).toEqual({ ok: true }); + }); + + it('expires five minutes after it was issued', () => { + const issued = issueConfirmationToken(SECRET, binding, fingerprint, NOW); + + expect(issued.expires_at).toBe('2026-10-17T12:05:00.000Z'); + expect(check(issue(), {}, { at: NOW + CONFIRMATION_TTL_MS - 1 })).toEqual({ + ok: true, + }); + expect(check(issue(), {}, { at: NOW + CONFIRMATION_TTL_MS })).toEqual({ + ok: false, + reason: 'expired', + }); + }); + + it('rejects a token whose expiry was moved forward', () => { + const [prefix, issued = '', state, signature] = issue().split('.'); + const nonce = issued.slice(-8); + const later = `${(NOW + 60 * CONFIRMATION_TTL_MS).toString(36)}${nonce}`; + + expect( + check( + [prefix, later, state, signature].join('.'), + {}, + { + at: NOW + 2 * CONFIRMATION_TTL_MS, + }, + ), + ).toEqual({ ok: false, reason: 'mismatch' }); + }); + + it.each([ + ['the state tag', 2], + ['the signature', 3], + ])('reports a flipped character in %s as a mismatch', (_label, part) => { + const parts = issue().split('.'); + const mac = parts[part]!; + parts[part] = (mac[0] === 'A' ? 'B' : 'A') + mac.slice(1); + + expect(check(parts.join('.'))).toEqual({ ok: false, reason: 'mismatch' }); + }); + + it.each(['0', '00', '0000'])( + 'rejects a token whose expiry is padded with %j', + (padding) => { + const [prefix, issued, state, signature] = issue().split('.'); + + expect( + check([prefix, `${padding}${issued}`, state, signature].join('.')), + ).toEqual({ ok: false, reason: 'malformed' }); + }, + ); + + it.each(['', 'not-a-token', 't49ct1.x.y.z', `${issue()}extra`])( + 'rejects a malformed token %j', + (token) => { + expect(check(token)).toEqual({ ok: false, reason: 'malformed' }); + }, + ); + + it('rejects a token issued for another account', () => { + expect(check(issue(), { accountId: OTHER_ACCOUNT_ID })).toEqual({ + ok: false, + reason: 'mismatch', + }); + }); + + it('rejects a token issued for another credential', () => { + expect( + check(issue(), { credentialHash: credentialHash('Token key-2') }), + ).toEqual({ ok: false, reason: 'mismatch' }); + }); + + it('rejects a token issued for other arguments or another tool', () => { + expect( + check(issue(), { + args: { shipment_id: '2a1f9b63-4d5e-4c7f-8a0b-9c1d2e3f4a5b' }, + }), + ).toEqual({ ok: false, reason: 'mismatch' }); + expect(check(issue(), { tool: 'resume_shipment_tracking' })).toEqual({ + ok: false, + reason: 'mismatch', + }); + }); + + it('rejects a token signed with another secret', () => { + expect( + check(issue(), {}, { secret: 'another-secret-that-is-also-long-enough' }), + ).toEqual({ ok: false, reason: 'mismatch' }); + }); + + it('reports stale state separately from a bad token', () => { + expect( + check( + issue(), + {}, + { + fingerprint: stateFingerprint({ tracking_stopped: true }), + }, + ), + ).toEqual({ ok: false, reason: 'stale' }); + }); + + it('binds the arguments regardless of key order', () => { + const token = issueConfirmationToken( + SECRET, + { ...binding, args: { a: 1, b: { c: 2, d: 3 } } }, + fingerprint, + NOW, + ).confirmation_token; + + expect(check(token, { args: { b: { d: 3, c: 2 }, a: 1 } }).ok).toBe(true); + }); +}); + +describe('usableConfirmationSecret', () => { + it.each([undefined, '', ' ', 'short-secret'])( + 'treats %j as missing', + (value) => { + expect(usableConfirmationSecret(value)).toBeUndefined(); + }, + ); + + it('keeps a secret of at least 32 characters, trimmed', () => { + expect(usableConfirmationSecret(` ${SECRET} `)).toBe(SECRET); + }); +}); + +describe('canonicalJson', () => { + it('sorts keys at every level and drops undefined values', () => { + expect(canonicalJson({ b: [{ z: 1, y: undefined, x: 2 }], a: null })).toBe( + '{"a":null,"b":[{"x":2,"z":1}]}', + ); + }); +}); diff --git a/packages/mcp/src/tools/write-kit.ts b/packages/mcp/src/tools/write-kit.ts new file mode 100644 index 00000000..69c21eaf --- /dev/null +++ b/packages/mcp/src/tools/write-kit.ts @@ -0,0 +1,890 @@ +/** + * Shared pieces for tools that change account data: the confirmed preview + * that tier C writes need, and the soft results those writes return. + * + * A tier C tool's first call changes nothing. It reads the record and builds + * a preview and a token: an HMAC over the tool, its arguments, the account, + * the credential, an expiry and a fingerprint of the record state the preview + * showed. The write runs only when a later call brings back a token that + * still matches all of them. + * + * Who holds the token depends on the client. A request that declares form + * elicitation (MCP 2026-07-28) gets an input_required result: the client + * shows the user the preview and asks them to confirm, and echoes the token + * as requestState. The model never sees a token it could pass back, so the + * human decides. Any other request gets the preview and the token in the + * result, and the model passes the token back after the user approves. That + * token is not a security boundary: a model can make both calls itself. The + * backend still decides what the credential may do. + */ +import { + createHash, + createHmac, + randomBytes, + timingSafeEqual, +} from 'node:crypto'; +import { + inputRequired, + type InputRequiredResult, +} from '@modelcontextprotocol/server'; +import { z } from 'zod'; +import { httpStatus, type SoftResult } from './soft-results.js'; +import { CONFIRMATION_TOKEN_PREFIX } from '../redaction.js'; +import { addMcpBreadcrumb } from '../sentry.js'; +import { captureMcpEvent } from '../posthog.js'; +import { + CONFIRM_REQUEST_KEY, + MCP_CREDENTIAL_TYPES, + type ConfirmationChannel, + type McpCredentialType, + type ToolContext, +} from './context.js'; +import { logMcpEvent } from '../logging.js'; +import { TOOL_REGISTRY, type ToolName } from './registry.js'; + +/** How long a confirmation token stays valid. */ +export const CONFIRMATION_TTL_MS = 5 * 60 * 1000; + +/** Shorter secrets are treated as missing, so tier C writes fail closed. */ +export const MIN_CONFIRMATION_SECRET_LENGTH = 32; + +/** The secret to sign with, or undefined when it is unset or too short. */ +export function usableConfirmationSecret( + value: string | undefined, +): string | undefined { + const secret = value?.trim(); + return secret && secret.length >= MIN_CONFIRMATION_SECRET_LENGTH + ? secret + : undefined; +} + +/** JSON with object keys sorted at every level and undefined values dropped. */ +export function canonicalJson(value: unknown): string { + return JSON.stringify(sortKeys(value)) ?? 'null'; +} + +function sortKeys(value: unknown): unknown { + if (Array.isArray(value)) return value.map(sortKeys); + if (value === null || typeof value !== 'object') return value; + return Object.fromEntries( + Object.entries(value) + .filter(([, nested]) => nested !== undefined) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, nested]) => [key, sortKeys(nested)]), + ); +} + +function sha256(text: string): string { + return createHash('sha256').update(text).digest('hex'); +} + +/** A keyed tag of the high-entropy API credential; never a stored password hash. */ +export function credentialHash(apiToken: string): string { + return createHmac('sha256', apiToken) + .update('terminal49-mcp-confirmation-credential-v1') + .digest('hex'); +} + +/** A hash of the record fields a write reads or changes. */ +export function stateFingerprint(state: unknown): string { + return sha256(canonicalJson(state)); +} + +/** Everything a confirmation token is bound to except the record state. */ +export interface ConfirmationBinding { + tool: string; + /** The tool arguments without confirmation_token. */ + args: Record; + accountId: string; + credentialHash: string; + /** + * Which channel carries the token, so a requestState the client echoes + * never works as a confirmation_token, and the other way round. + */ + channel: ConfirmationChannel['kind']; +} + +function mac(secret: string, parts: unknown[]): string { + return createHmac('sha256', secret) + .update(canonicalJson(parts)) + .digest('base64url'); +} + +/** Stands for the record state inside a token without revealing it. */ +function stateTag(secret: string, fingerprint: string): string { + return mac(secret, [CONFIRMATION_TOKEN_PREFIX, 'state', fingerprint]); +} + +/** Signs everything else the token carries or is bound to. */ +function tokenMac( + secret: string, + binding: ConfirmationBinding, + expiresAt: number, + nonce: string, + state: string, +): string { + return mac(secret, [ + CONFIRMATION_TOKEN_PREFIX, + binding.channel, + binding.tool, + binding.args, + binding.accountId, + binding.credentialHash, + expiresAt, + nonce, + state, + ]); +} + +export interface IssuedConfirmation { + confirmation_token: string; + expires_at: string; +} + +export function issueConfirmationToken( + secret: string, + binding: ConfirmationBinding, + fingerprint: string, + now: number = Date.now(), +): IssuedConfirmation { + const expiresAt = now + CONFIRMATION_TTL_MS; + // Makes every preview's token unique, so one approval confirms one write. + const nonce = randomBytes(4).toString('hex'); + const state = stateTag(secret, fingerprint); + return { + confirmation_token: [ + CONFIRMATION_TOKEN_PREFIX, + `${expiresAt.toString(36)}${nonce}`, + state, + tokenMac(secret, binding, expiresAt, nonce, state), + ].join('.'), + expires_at: new Date(expiresAt).toISOString(), + }; +} + +/** + * Why a token was refused. `malformed`, `mismatch` and `expired` mean the + * caller must start over. `stale` means the token was right for this call but + * the record changed after the preview. + */ +export type ConfirmationRejection = + | 'malformed' + | 'mismatch' + | 'expired' + | 'stale'; + +export type ConfirmationCheck = + | { ok: true } + | { ok: false; reason: ConfirmationRejection }; + +function sameMac(a: string, b: string): boolean { + const left = Buffer.from(a); + const right = Buffer.from(b); + return left.length === right.length && timingSafeEqual(left, right); +} + +const TOKEN_PATTERN = new RegExp( + `^${CONFIRMATION_TOKEN_PREFIX}\\.([0-9a-z]{1,12})([0-9a-f]{8})\\.([A-Za-z0-9_-]{43})\\.([A-Za-z0-9_-]{43})$`, +); + +export function checkConfirmationToken( + secret: string, + token: string, + binding: ConfirmationBinding, + fingerprint: string, + now: number = Date.now(), +): ConfirmationCheck { + const match = TOKEN_PATTERN.exec(token); + if (!match) return { ok: false, reason: 'malformed' }; + const [, encodedExpiry = '', nonce = '', state = '', signature = ''] = match; + const expiresAt = Number.parseInt(encodedExpiry, 36); + // The MAC covers the expiry as a number, so a zero-padded copy of a token + // would verify too and count as a different, unspent confirmation. + if (expiresAt.toString(36) !== encodedExpiry) { + return { ok: false, reason: 'malformed' }; + } + // The MAC covers the expiry, the nonce and the state tag, so an edit to any + // of them is a mismatch, never a stale preview. + if (!sameMac(signature, tokenMac(secret, binding, expiresAt, nonce, state))) { + return { ok: false, reason: 'mismatch' }; + } + if (now >= expiresAt) return { ok: false, reason: 'expired' }; + if (!sameMac(state, stateTag(secret, fingerprint))) { + return { ok: false, reason: 'stale' }; + } + return { ok: true }; +} + +// ==================== Soft results ==================== + +export type NotPermittedResult = SoftResult<'not_permitted'>; + +/** + * Returned by a tier C tool when the change needs the user's approval and the + * server has no confirmation secret to sign it with. A change that needs no + * approval still runs without the secret. + */ +export const CONFIRMATION_NOT_CONFIGURED: NotPermittedResult = { + error: 'not_permitted', + message: + "This change needs the user's approval, and this Terminal49 MCP server has no T49_MCP_CONFIRMATION_SECRET to sign approvals with, so it cannot make the change. Nothing was changed.", + alternative: + 'Ask whoever runs this MCP server to set T49_MCP_CONFIRMATION_SECRET, or make this change in the Terminal49 dashboard.', +}; + +export interface InvalidConfirmationResult extends SoftResult<'invalid_confirmation'> { + reason: Exclude | 'used'; +} + +const INVALID_CONFIRMATION_MESSAGES = { + malformed: 'The confirmation_token is not a token this server issued.', + mismatch: + 'The confirmation_token was issued for a different call, account or credential.', + expired: 'The confirmation_token has expired.', + used: 'The confirmation_token was already used to make this change.', +} satisfies Record; + +const INVALID_REQUEST_STATE_MESSAGES = { + malformed: + 'The confirmation state the client sent back is not one this server issued.', + mismatch: + 'The confirmation state the client sent back was issued for a different call, account or credential.', + expired: 'The confirmation the user gave has expired.', + used: 'The confirmation the user gave was already used to make this change.', +} satisfies Record; + +export function invalidConfirmation( + tool: string, + reason: InvalidConfirmationResult['reason'], + channel: ConfirmationChannel['kind'] = 'token', +): InvalidConfirmationResult { + return channel === 'token' + ? { + error: 'invalid_confirmation', + reason, + message: `${INVALID_CONFIRMATION_MESSAGES[reason]} Nothing was changed.`, + alternative: `Call ${tool} again with the same arguments and no confirmation_token to get a new preview, and show it to the user.`, + } + : { + error: 'invalid_confirmation', + reason, + message: `${INVALID_REQUEST_STATE_MESSAGES[reason]} Nothing was changed.`, + alternative: `Call ${tool} again with the same arguments. The client will ask the user to confirm the current state.`, + }; +} + +export type TokenNotAcceptedResult = SoftResult<'token_not_accepted'>; + +/** Returned when a request that can ask the user carries a confirmation_token. */ +export function tokenNotAccepted(tool: string): TokenNotAcceptedResult { + return { + error: 'token_not_accepted', + message: + 'This client asks the user to confirm changes itself, so a confirmation_token is not accepted here. Nothing was changed.', + alternative: `Call ${tool} again with the same arguments and no confirmation_token. The client will show the user the preview and ask them to confirm.`, + }; +} + +export interface DeclinedResult { + status: 'declined'; + message: string; +} + +/** Returned when the user did not confirm the preview the client showed. */ +export function declined(action: 'decline' | 'cancel'): DeclinedResult { + return { + status: 'declined', + message: + action === 'decline' + ? 'The user declined this change. Nothing was changed.' + : 'The user dismissed the confirmation without answering. Nothing was changed.', + }; +} + +export interface ConfirmationRequiredResult< + Preview, +> extends IssuedConfirmation { + status: 'confirmation_required'; + message: string; + preview: Preview; +} + +export function confirmationRequired( + tool: string, + preview: Preview, + issued: IssuedConfirmation, +): ConfirmationRequiredResult { + return { + status: 'confirmation_required', + message: `Nothing was changed. Show this preview to the user. If the user approves it, call ${tool} again with the same arguments and this confirmation_token before expires_at.`, + preview, + ...issued, + }; +} + +export interface StalePreviewResult extends IssuedConfirmation { + status: 'stale_preview'; + message: string; + preview: Preview; +} + +export function stalePreview( + tool: string, + preview: Preview, + issued: IssuedConfirmation, +): StalePreviewResult { + return { + status: 'stale_preview', + message: `The record changed after the preview, so nothing was changed. Show this new preview to the user. If the user approves it, call ${tool} again with the new confirmation_token.`, + preview, + ...issued, + }; +} + +const softResultFields = { + status: z.string().optional(), + error: z.string().optional(), + reason: z.string().optional(), + message: z.string().optional(), + alternative: z.string().optional(), + retry_after_s: z.number().optional(), +}; + +/** + * The output schema of a tier A write tool: its own fields plus the + * soft-result fields. Every field is optional because one schema covers every + * outcome. + */ +export function writeResultSchema( + fields: Fields, +) { + return z.object({ ...softResultFields, ...fields }); +} + +/** The output schema of a tier C write tool, with its preview and token. */ +export function confirmedWriteResultSchema( + preview: z.ZodType, + fields: Fields, +) { + return z.object({ + ...softResultFields, + preview: preview.optional(), + confirmation_token: z.string().optional(), + expires_at: z.string().optional(), + ...fields, + }); +} + +export interface WriteRateLimited extends SoftResult<'rate_limited'> { + /** Seconds Terminal49 asked the caller to wait, when it said. */ + retry_after_s?: number; +} + +const retryAfterSchema = z.object({ retryAfterMs: z.number().nonnegative() }); + +/** Returned when Terminal49 answers a write with 429. */ +export function writeRateLimited(error: unknown): WriteRateLimited { + const parsed = retryAfterSchema.safeParse(error); + const retryAfterS = parsed.success + ? Math.ceil(parsed.data.retryAfterMs / 1000) + : undefined; + return { + error: 'rate_limited', + message: + 'Terminal49 is limiting how often this change can be made. Nothing was changed.', + alternative: + retryAfterS === undefined + ? 'Wait a minute and try again.' + : `Wait ${retryAfterS} seconds and try again.`, + ...(retryAfterS === undefined ? {} : { retry_after_s: retryAfterS }), + }; +} + +/** The confirmation_token input every tier C tool takes. */ +export const confirmationTokenInput = z + .string() + .trim() + .min(1) + .max(256) + .optional() + .describe( + 'Only for a client that cannot ask the user itself: leave this out on the first call to get a preview and a token, and pass the token back only after the user approves that preview in this turn. A client that asks the user itself never needs it.', + ); + +// ==================== Audit ==================== + +export const AUDIT_ENTITY_TYPES = [ + 'container', + 'shipment', + 'tracking_request', + 'document', +] as const; + +export type AuditEntityType = (typeof AUDIT_ENTITY_TYPES)[number]; + +/** + * `preview` is a tier C call without a token. `execute` is a tier C call + * with a token, or any tier A call. + */ +export type WritePhase = 'preview' | 'execute'; + +export interface WriteAuditInput { + tool: ToolName; + tier: 'A' | 'C'; + phase: WritePhase; + /** The result's status or soft-result code, or `error` for a thrown call. */ + outcome: string; + entityType: AuditEntityType; + /** Undefined when the call created no record, or failed before it did. */ + entityId: string | undefined; + accountId: string | undefined; + credentialType: McpCredentialType; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const writeAuditEventSchema = z.object({ + tool: z + .enum([...TOOL_REGISTRY.map((tool) => tool.name), 'unknown']) + .catch('unknown'), + tier: z.enum(['A', 'C']).catch('C'), + phase: z.enum(['preview', 'execute']).catch('execute'), + outcome: z + .string() + .regex(/^[A-Za-z][A-Za-z_]{0,39}$/) + .catch('unknown'), + entity_type: z.enum([...AUDIT_ENTITY_TYPES, 'unknown']).catch('unknown'), + entity_id: z.string().regex(UUID).nullable().catch(null), + account_id: z.string().regex(UUID).nullable().catch(null), + credential_type: z + .enum([...MCP_CREDENTIAL_TYPES, 'unknown']) + .catch('unknown'), +}); + +export type WriteAuditEvent = z.infer; + +/** + * The audit event for one write call. It is built from named fields only and + * each value must match its expected form, so values, reference numbers, + * party names, URLs, tokens and payloads cannot reach a sink through it. + */ +export function buildWriteAuditEvent(input: WriteAuditInput): WriteAuditEvent { + return writeAuditEventSchema.parse({ + tool: input.tool, + tier: input.tier, + phase: input.phase, + outcome: input.outcome, + entity_type: input.entityType, + entity_id: input.entityId, + account_id: input.accountId ?? null, + credential_type: input.credentialType, + }); +} + +export const WRITE_AUDIT_EVENT = 'mcp.write.audit'; + +/** Sends the audit event to the log, a Sentry breadcrumb and PostHog. */ +export function emitWriteAudit(input: WriteAuditInput): void { + const audit = buildWriteAuditEvent(input); + // logMcpEvent redacts every *_id key, and this event needs the entity and + // account ids, which the schema above has already checked are UUIDs. + console.error( + JSON.stringify({ + event: WRITE_AUDIT_EVENT, + ...audit, + timestamp: new Date().toISOString(), + }), + ); + addMcpBreadcrumb(WRITE_AUDIT_EVENT, audit); + if (audit.account_id) { + captureMcpEvent('mcp_write', audit.account_id, audit); + } +} + +/** The audit outcome for a result: its status, else its soft-result code. */ +export function auditOutcome(result: unknown): string { + const parsed = z + .object({ status: z.string() }) + .or(z.object({ error: z.string() })) + .safeParse(result); + if (!parsed.success) return 'done'; + return 'status' in parsed.data ? parsed.data.status : parsed.data.error; +} + +// ==================== Write flows ==================== + +interface WriteTarget { + tool: ToolName; + entityType: AuditEntityType; + entityId: string | undefined; +} + +/** How long an audit waits for /me before naming no account. */ +const AUDIT_ACCOUNT_DEADLINE_MS = 2_000; + +/** + * The account an audit event names. The lookup can call /me, and a failed or + * slow lookup leaves the account out rather than holding up the write. + */ +async function auditAccountId( + context: ToolContext, +): Promise { + let timer: ReturnType | undefined; + const deadline = new Promise((resolve) => { + timer = setTimeout(resolve, AUDIT_ACCOUNT_DEADLINE_MS, undefined); + }); + try { + return await Promise.race([ + context.accountId().catch(() => undefined), + deadline, + ]); + } finally { + clearTimeout(timer); + } +} + +function auditor(context: ToolContext, target: WriteTarget, tier: 'A' | 'C') { + return async ( + phase: WritePhase, + outcome: string, + entityId = target.entityId, + ) => + emitWriteAudit({ + ...target, + entityId, + tier, + phase, + outcome, + accountId: await auditAccountId(context), + credentialType: context.credentialType, + }); +} + +/** The audit outcome and record of a tier A write, read from its result. */ +export interface WriteAuditSummary { + outcome: string; + entityId?: string; +} + +/** + * Audits a write that threw. A 429 from any of its requests, reads included, + * becomes the rate_limited soft result; anything else is rethrown. + */ +async function failedWrite( + error: unknown, + audit: (outcome: string) => Promise, +): Promise { + if (httpStatus(error) === 429) { + await audit('rate_limited'); + return writeRateLimited(error); + } + await audit('error'); + throw error; +} + +/** + * Runs a tier A write and emits its audit event. `summarize` reads the + * outcome and record from the result, for a write whose record id is known + * only after it runs. + */ +export async function runWrite( + context: ToolContext, + target: WriteTarget, + run: () => Promise, + summarize: (result: Result) => WriteAuditSummary = (result) => ({ + outcome: auditOutcome(result), + }), +): Promise { + const audit = auditor(context, target, 'A'); + try { + const result = await run(); + const summary = summarize(result); + await audit( + 'execute', + summary.outcome, + summary.entityId ?? target.entityId, + ); + return result; + } catch (error) { + return failedWrite(error, (outcome) => audit('execute', outcome)); + } +} + +/** + * What a tier C read found: a reason to stop, the state to confirm, or, for + * a tool that asks only when a record would lose data, a change that is + * additive throughout and so writes without asking. + */ +export type ConfirmedWriteRead = + | { stop: Stop } + | { + /** The exact fields the write reads or changes. */ + state: unknown; + preview: Preview; + } + | { additive: Preview }; + +export interface ConfirmedWrite extends WriteTarget { + /** The tool arguments, with confirmation_token when the caller sent one. */ + args: Record & { confirmation_token?: string }; + /** Reads the record. Called on every call, before any token is checked. */ + read(): Promise>; + /** + * Changes the record. Called only with a token that matches, and given the + * preview of the state the token was checked against. A 4xx it throws + * goes to `refused`, not caught here, so the kit releases the token first. + */ + write(preview: Preview): Promise; + /** + * The result for a 4xx the write threw, after the token is released. A + * 4xx means Terminal49 changed nothing. Undefined lets the error fail the + * call. + */ + refused?(error: unknown, preview: Preview): Promise; + /** + * The preview as text for the confirmation dialog. Defaults to one line + * per preview field; a batch tool lists its records instead. + */ + describe?(preview: Preview): string; +} + +export type ConfirmedWriteResult = + | Stop + | Done + | ConfirmationRequiredResult + | StalePreviewResult + | InvalidConfirmationResult + | NotPermittedResult + | WriteRateLimited + | InputRequiredResult + | DeclinedResult + | TokenNotAcceptedResult; + +const previewTextSchema = z + .object({ reach: z.string().optional() }) + .passthrough(); + +/** + * The preview as text for the confirmation dialog: what the change reaches, + * then each preview field, so the user sees the record now and after. + */ +export function describeChange(target: WriteTarget, preview: unknown): string { + const { reach, ...fields } = previewTextSchema.parse(preview); + const lines = [ + `${target.tool} on ${target.entityType} ${target.entityId ?? ''}`.trim(), + ...(reach ? [reach] : []), + ...Object.entries(fields).map( + ([key, value]) => `${key}: ${canonicalJson(value)}`, + ), + ]; + return lines.join('\n'); +} + +/** Asks the client to show the preview and get the user's yes or no. */ +function elicitConfirmation( + plan: Pick< + ConfirmedWrite, + keyof WriteTarget | 'describe' + >, + preview: Preview, + issued: IssuedConfirmation, + note?: string, +): InputRequiredResult { + const text = plan.describe + ? plan.describe(preview) + : describeChange(plan, preview); + return inputRequired({ + inputRequests: { + [CONFIRM_REQUEST_KEY]: inputRequired.elicit({ + message: note ? `${note}\n${text}` : text, + requestedSchema: { + type: 'object', + properties: { + confirm: { + type: 'boolean', + title: 'Confirm', + description: 'Make this change', + }, + }, + required: ['confirm'], + }, + }), + }, + requestState: issued.confirmation_token, + }); +} + +/** + * Tokens that confirmed a write, kept until they expire. A token is reserved + * before its write runs, so two concurrent calls cannot both use it. A token is + * bound to the record's state, and a tier A inverse such as + * resume_shipment_tracking can restore that state, so without this one + * approval could confirm the same write twice. It lives in process memory, so + * on a multi-instance deployment another instance can still accept the token + * once more before it expires. + */ +const spentTokens = new Map(); + +/** + * The key a spent token is remembered by: its signature, which a checked + * token cannot change without failing the check, rather than its text. + */ +function spentKey(token: string): string { + return token.slice(token.lastIndexOf('.') + 1); +} + +/** Marks a token used. False when it already confirmed a write. */ +function spendToken(token: string, now: number = Date.now()): boolean { + for (const [spent, expiresAt] of spentTokens) { + if (expiresAt <= now) spentTokens.delete(spent); + } + const key = spentKey(token); + if (spentTokens.has(key)) return false; + spentTokens.set(key, now + CONFIRMATION_TTL_MS); + return true; +} + +const RECORD_CHANGED_NOTE = + 'The record changed after you last saw it. Here is its current state.'; + +/** + * Runs a tier C write. The first call never writes: it reads the record and + * either asks the client to confirm the preview with the user (a request that + * declares form elicitation) or returns the preview with a token for the + * model to pass back. The write runs only when the confirmation that comes + * back matches this call and the record has not changed since the preview. + */ +export async function runConfirmedWrite( + context: ToolContext, + plan: ConfirmedWrite, +): Promise> { + const audit = auditor(context, plan, 'C'); + const { confirmation_token: token, ...args } = plan.args; + const channel = context.confirmation; + const confirming = + channel.kind === 'token' + ? token !== undefined + : channel.requestState !== undefined; + const phase: WritePhase = confirming ? 'execute' : 'preview'; + const secret = context.confirmationSecret; + if (channel.kind === 'elicitation' && token !== undefined) { + await audit('execute', 'token_not_accepted'); + return tokenNotAccepted(plan.tool); + } + // A no ends the call whatever the confirmation's state: it writes nothing, + // so there is no preview to keep fresh and no token to spend. + const answer = channel.kind === 'elicitation' ? channel.answer : undefined; + if (answer && !(answer.action === 'accept' && answer.confirm)) { + await audit(phase, 'declined'); + return declined(answer.action === 'cancel' ? 'cancel' : 'decline'); + } + + // Runs the write. A 4xx means Terminal49 refused the request and changed + // nothing, so the approval still stands and the token is released. A 5xx + // or a lost response may hide a write, so the error fails the call. + const commit = async ( + preview: Preview, + confirmation: string | undefined, + ): Promise => { + try { + return await plan.write(preview); + } catch (error) { + const status = httpStatus(error); + if (status === undefined || status < 400 || status >= 500) throw error; + if (confirmation) spentTokens.delete(spentKey(confirmation)); + const answer = await plan.refused?.(error, preview); + if (answer === undefined) throw error; + return answer; + } + }; + + try { + const read = await plan.read(); + if ('stop' in read) { + await audit(phase, auditOutcome(read.stop)); + return read.stop; + } + if ('additive' in read) { + const done = await commit(read.additive, undefined); + await audit('execute', auditOutcome(done)); + return done; + } + if (!secret) { + logMcpEvent({ + event: 'mcp.config.error', + error: 'ConfirmationSecretMissing', + reason: + 'T49_MCP_CONFIRMATION_SECRET is unset or shorter than 32 characters, so changes that need approval are refused.', + tool: plan.tool, + timestamp: new Date().toISOString(), + }); + await audit(phase, CONFIRMATION_NOT_CONFIGURED.error); + return { ...CONFIRMATION_NOT_CONFIGURED }; + } + const binding: ConfirmationBinding = { + tool: plan.tool, + args, + accountId: await context.accountId(), + credentialHash: await context.credentialKey(), + channel: channel.kind, + }; + const fingerprint = stateFingerprint(read.state); + const issue = () => issueConfirmationToken(secret, binding, fingerprint); + + if (channel.kind === 'token') { + if (!token) { + await audit(phase, 'confirmation_required'); + return confirmationRequired(plan.tool, read.preview, issue()); + } + const check = checkConfirmationToken(secret, token, binding, fingerprint); + if (!check.ok) { + if (check.reason === 'stale') { + await audit(phase, 'stale_preview'); + return stalePreview(plan.tool, read.preview, issue()); + } + await audit(phase, 'invalid_confirmation'); + return invalidConfirmation(plan.tool, check.reason); + } + } else { + if (channel.requestState === undefined) { + await audit(phase, 'elicitation_required'); + return elicitConfirmation(plan, read.preview, issue()); + } + const check = checkConfirmationToken( + secret, + channel.requestState, + binding, + fingerprint, + ); + if (!check.ok) { + if (check.reason === 'stale') { + await audit(phase, 'stale_preview'); + return elicitConfirmation( + plan, + read.preview, + issue(), + RECORD_CHANGED_NOTE, + ); + } + await audit(phase, 'invalid_confirmation'); + return invalidConfirmation(plan.tool, check.reason, 'elicitation'); + } + if (answer === undefined) { + await audit(phase, 'elicitation_required'); + return elicitConfirmation(plan, read.preview, issue()); + } + } + + const confirmation = + channel.kind === 'token' ? token : channel.requestState; + if (confirmation && !spendToken(confirmation)) { + await audit(phase, 'invalid_confirmation'); + return invalidConfirmation(plan.tool, 'used', channel.kind); + } + const done = await commit(read.preview, confirmation); + await audit(phase, auditOutcome(done)); + return done; + } catch (error) { + return failedWrite(error, (outcome) => audit(phase, outcome)); + } +} diff --git a/sdks/typescript-sdk/src/client.transport.test.ts b/sdks/typescript-sdk/src/client.transport.test.ts index af8dc2a0..07f1da0e 100644 --- a/sdks/typescript-sdk/src/client.transport.test.ts +++ b/sdks/typescript-sdk/src/client.transport.test.ts @@ -256,6 +256,51 @@ describe('Terminal49Client transport resilience', () => { expect(attempt).toBe(1); }); + it('carries the Retry-After wait on a RateLimitError, uncapped', async () => { + const client = new Terminal49Client({ + apiToken: 'token-123', + apiBaseUrl: baseUrl, + fetchImpl: (async () => + new Response(JSON.stringify({ errors: [{ detail: 'slow down' }] }), { + status: 429, + headers: { + 'Content-Type': 'application/vnd.api+json', + 'Retry-After': '120', + }, + })) as unknown as typeof fetch, + maxRetries: 0, + }); + + await expect( + client.createTrackingRequest({ + requestType: 'container', + requestNumber: 'MSCU1234567', + }), + ).rejects.toMatchObject({ name: 'RateLimitError', retryAfterMs: 120_000 }); + }); + + it('leaves retryAfterMs undefined when a 429 has no Retry-After', async () => { + const client = new Terminal49Client({ + apiToken: 'token-123', + apiBaseUrl: baseUrl, + fetchImpl: (async () => + jsonResponse( + { errors: [{ detail: 'slow down' }] }, + 429, + )) as unknown as typeof fetch, + maxRetries: 0, + }); + + const error = await client + .createTrackingRequest({ + requestType: 'container', + requestNumber: 'MSCU1234567', + }) + .catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(RateLimitError); + expect((error as RateLimitError).retryAfterMs).toBeUndefined(); + }); + it('stops iterate() at the safety page bound even when next never ends', async () => { // A misconfigured/no-op filter where the server always advertises a // `next` link would otherwise walk the entire dataset forever. The diff --git a/sdks/typescript-sdk/src/client/errors.ts b/sdks/typescript-sdk/src/client/errors.ts index f7865253..02299917 100644 --- a/sdks/typescript-sdk/src/client/errors.ts +++ b/sdks/typescript-sdk/src/client/errors.ts @@ -53,9 +53,18 @@ export class ValidationError extends Terminal49Error { /** Thrown when the API rate limit has been exceeded (HTTP 429). The SDK retries automatically. */ export class RateLimitError extends Terminal49Error { - constructor(message: string, status = 429, details?: unknown) { + /** How long the API asked the caller to wait, from its `Retry-After` header. Undefined when it sent none. */ + retryAfterMs?: number; + + constructor( + message: string, + status = 429, + details?: unknown, + retryAfterMs?: number, + ) { super(message, status, details); this.name = 'RateLimitError'; + this.retryAfterMs = retryAfterMs; } } @@ -156,6 +165,7 @@ export function toTerminal49Error( status: number, message: string, details?: unknown, + retryAfterMs?: number, ): Terminal49Error { switch (status) { case 400: @@ -189,6 +199,7 @@ export function toTerminal49Error( message || 'Rate limit exceeded', status, details, + retryAfterMs, ); case 500: case 502: diff --git a/sdks/typescript-sdk/src/client/interceptors.ts b/sdks/typescript-sdk/src/client/interceptors.ts index 1c18282e..4bf7876a 100644 --- a/sdks/typescript-sdk/src/client/interceptors.ts +++ b/sdks/typescript-sdk/src/client/interceptors.ts @@ -240,6 +240,13 @@ export class ErrorMappingInterceptor { response.status, extractErrorMessage(errorBody), errorBody, + // The caller decides how long to wait, so the retry sleep cap does not + // apply here. + parseRetryAfterMs( + response.headers.get('Retry-After'), + Date.now(), + Number.POSITIVE_INFINITY, + ), ); } } diff --git a/sdks/typescript-sdk/src/client/retry-policy.ts b/sdks/typescript-sdk/src/client/retry-policy.ts index 0573c3c1..0d5a39b6 100644 --- a/sdks/typescript-sdk/src/client/retry-policy.ts +++ b/sdks/typescript-sdk/src/client/retry-policy.ts @@ -105,26 +105,29 @@ const MAX_RETRY_AFTER_MS = 60_000; /** * Parse a `Retry-After` header into milliseconds. Supports both delta-seconds * (`"120"`) and an HTTP-date. Returns `undefined` when absent/unparseable, never - * returns a negative delay, and clamps the result to {@link MAX_RETRY_AFTER_MS}. + * returns a negative delay, and clamps the result to `maxMs`. * * @param now - Reference time (ms since epoch) used for HTTP-date math; defaults * to `Date.now()` and is injectable for deterministic tests. + * @param maxMs - Upper bound; defaults to {@link MAX_RETRY_AFTER_MS}, the cap on + * a retry sleep. */ export function parseRetryAfterMs( value: string | null | undefined, now: number = Date.now(), + maxMs: number = MAX_RETRY_AFTER_MS, ): number | undefined { if (value == null) return undefined; const trimmed = value.trim(); if (trimmed === '') return undefined; if (/^\d+$/.test(trimmed)) { - return Math.min(Number(trimmed) * 1000, MAX_RETRY_AFTER_MS); + return Math.min(Number(trimmed) * 1000, maxMs); } const dateMs = Date.parse(trimmed); if (Number.isNaN(dateMs)) return undefined; - return Math.min(Math.max(0, dateMs - now), MAX_RETRY_AFTER_MS); + return Math.min(Math.max(0, dateMs - now), maxMs); } /** Base unit (ms) for exponential backoff: attempt 0 -> 500ms, 1 -> 1000ms, ... */