Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/sdk/error-handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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;
}
Expand Down
4 changes: 3 additions & 1 deletion docs/sdk/reference/client/classes/RateLimitError.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand All @@ -41,6 +42,7 @@ Thrown when the API rate limit has been exceeded (HTTP 429). The SDK retries aut
| <a id="property-details"></a> `details?` | `public` | `unknown` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`details`](/sdk/reference/client/classes/Terminal49Error#property-details) |
| <a id="property-message"></a> `message` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`message`](/sdk/reference/client/classes/Terminal49Error#property-message) |
| <a id="property-name"></a> `name` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`name`](/sdk/reference/client/classes/Terminal49Error#property-name) |
| <a id="property-retryafterms"></a> `retryAfterMs?` | `public` | `number` | How long the API asked the caller to wait, from its `Retry-After` header. Undefined when it sent none. | - |
| <a id="property-stack"></a> `stack?` | `public` | `string` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`stack`](/sdk/reference/client/classes/Terminal49Error#property-stack) |
| <a id="property-status"></a> `status?` | `public` | `number` | - | [`Terminal49Error`](/sdk/reference/client/classes/Terminal49Error).[`status`](/sdk/reference/client/classes/Terminal49Error#property-status) |
| <a id="property-stacktracelimit"></a> `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) |
Expand Down
16 changes: 16 additions & 0 deletions packages/mcp/src/logging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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',
Expand Down
6 changes: 3 additions & 3 deletions packages/mcp/src/logging.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { redactSignedUrls } from './signed-urls.js';
import { redactSecrets } from './redaction.js';

const REDACTED_VALUE = '[REDACTED]';

Expand Down Expand Up @@ -68,15 +68,15 @@ function sanitizeValue(value: unknown): unknown {
}

if (typeof value === 'string') {
return redactSignedUrls(value);
return redactSecrets(value);
}

return value;
}

/**
* 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<string, unknown>,
Expand Down
17 changes: 17 additions & 0 deletions packages/mcp/src/posthog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<string, unknown> };

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',
Expand Down
35 changes: 32 additions & 3 deletions packages/mcp/src/posthog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -175,7 +175,7 @@ const redactSensitiveProperties: BeforeSendFn = (event) => {
}
}

event.properties = redactSignedUrlsDeep(event.properties);
event.properties = redactSecretsDeep(event.properties);
return event;
};

Expand Down Expand Up @@ -278,6 +278,35 @@ export function instrumentMcpServerWithPostHog<TServer extends McpServer>(
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<string, string | null>,
): 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<void>,
Expand Down
65 changes: 65 additions & 0 deletions packages/mcp/src/redaction.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
54 changes: 54 additions & 0 deletions packages/mcp/src/redaction.ts
Original file line number Diff line number Diff line change
@@ -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<T>(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;
}
34 changes: 34 additions & 0 deletions packages/mcp/src/sentry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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',
Expand Down
Loading
Loading