diff --git a/README.md b/README.md index ad0a572b6..e014c6c2e 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,10 @@ The stdio server uses the saved browser OAuth session. A `SOCKET_API_TOKEN` envi Audit-event destinations and record behavior are documented in the [service reference](docs/service.md#audit-events). +### Error reporting + +HTTP mode can report server-side failures to Sentry. It is off unless `SOCKET_MCP_SENTRY_DSN` is set, and `SOCKET_MCP_SENTRY_ENVIRONMENT` names the environment. stdio mode never reports. What is sent, and what is scrubbed, is documented in the [service reference](docs/service.md#error-reporting). + ### Health check endpoint The HTTP health response is documented in the [service reference](docs/service.md#health-check-endpoint). diff --git a/docs/commands.md b/docs/commands.md index 453e4a43a..c15fcc615 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -65,20 +65,22 @@ The transport is stateless. Each `POST /` is self-contained, with no session to Environment variables for HTTP mode: -| Variable | Required | Default | Description | -| ------------------------------------------ | ----------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `MCP_HTTP_MODE` | Yes, unless you pass `--http` | `false` | Set to `true` to serve HTTP instead of stdio. The `--http` CLI flag does the same thing. | -| `MCP_PORT` | No | `3000` | Port to bind the HTTP server to. | -| `SOCKET_API_TOKEN` | Optional | None | API token for outbound API calls. Use it only as a fallback for local stdio. `socket-mcp login` is the recommended local sign-in. HTTP OAuth does not need a startup token. See the alias list below. | -| `SOCKET_OAUTH_ISSUER` | With OAuth | None | OAuth issuer URL. Must be `https` on a public host. See "Enabling OAuth" below. | -| `SOCKET_OAUTH_INTROSPECTION_CLIENT_ID` | With OAuth | None | Client ID used for RFC 7662 token introspection. | -| `SOCKET_OAUTH_INTROSPECTION_CLIENT_SECRET` | With OAuth | None | Client secret used for RFC 7662 token introspection. | -| `SOCKET_OAUTH_REQUIRED_SCOPES` | No | None | Scopes required on incoming access tokens, separated by spaces or commas. When unset, any active token passes. | -| `SOCKET_API_BASE_URL` | No | None | Override the upstream Socket API endpoint. Falls back to `https://api.socket.dev` when unset. | -| `SOCKET_MCP_OAUTH_BASE_URL` | No | API URL | Override the issuer used by local stdio OAuth. By default, OAuth follows `SOCKET_API_BASE_URL`; an `api.` hostname maps to its matching `mcp.` resource host. Non-loopback URLs must use HTTPS. | -| `SOCKET_DEBUG` | No | `false` | Turns on verbose request and cache tracing on stderr, points `depscore` at `http://localhost:8866`, and permits a local OAuth issuer. | -| `SOCKET_MCP_APPS_CHALLENGE_TOKEN` | For domain verification | None | Token the OpenAI plugin portal issues for domain verification. When set, `GET /.well-known/openai-apps-challenge` returns it as plain text; when unset, that path returns `404`. | -| `TRUST_PROXY` | No | `false` | Trust `X-Forwarded-Host` and `X-Forwarded-Proto` when building OAuth metadata URLs. Enable only behind a reverse proxy that rewrites them. | +| Variable | Required | Default | Description | +| ------------------------------------------ | ----------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `MCP_HTTP_MODE` | Yes, unless you pass `--http` | `false` | Set to `true` to serve HTTP instead of stdio. The `--http` CLI flag does the same thing. | +| `MCP_PORT` | No | `3000` | Port to bind the HTTP server to. | +| `SOCKET_API_TOKEN` | Optional | None | API token for outbound API calls. Use it only as a fallback for local stdio. `socket-mcp login` is the recommended local sign-in. HTTP OAuth does not need a startup token. See the alias list below. | +| `SOCKET_OAUTH_ISSUER` | With OAuth | None | OAuth issuer URL. Must be `https` on a public host. See "Enabling OAuth" below. | +| `SOCKET_OAUTH_INTROSPECTION_CLIENT_ID` | With OAuth | None | Client ID used for RFC 7662 token introspection. | +| `SOCKET_OAUTH_INTROSPECTION_CLIENT_SECRET` | With OAuth | None | Client secret used for RFC 7662 token introspection. | +| `SOCKET_OAUTH_REQUIRED_SCOPES` | No | None | Scopes required on incoming access tokens, separated by spaces or commas. When unset, any active token passes. | +| `SOCKET_API_BASE_URL` | No | None | Override the upstream Socket API endpoint. Falls back to `https://api.socket.dev` when unset. | +| `SOCKET_MCP_OAUTH_BASE_URL` | No | API URL | Override the issuer used by local stdio OAuth. By default, OAuth follows `SOCKET_API_BASE_URL`; an `api.` hostname maps to its matching `mcp.` resource host. Non-loopback URLs must use HTTPS. | +| `SOCKET_DEBUG` | No | `false` | Turns on verbose request and cache tracing on stderr, points `depscore` at `http://localhost:8866`, and permits a local OAuth issuer. | +| `SOCKET_MCP_APPS_CHALLENGE_TOKEN` | For domain verification | None | Token the OpenAI plugin portal issues for domain verification. When set, `GET /.well-known/openai-apps-challenge` returns it as plain text; when unset, that path returns `404`. | +| `SOCKET_MCP_SENTRY_DSN` | No | None | Sentry DSN for error reporting; it must use HTTPS. When unset, reporting is off: the Sentry SDK is never loaded and nothing is sent. When set, HTTP mode sends scrubbed events for server-side failures. See [Error reporting](service.md#error-reporting). | +| `SOCKET_MCP_SENTRY_ENVIRONMENT` | No | `production` | Sentry `environment` reported events carry, such as `staging`. Read only when `SOCKET_MCP_SENTRY_DSN` is set. | +| `TRUST_PROXY` | No | `false` | Trust `X-Forwarded-Host` and `X-Forwarded-Proto` when building OAuth metadata URLs. Enable only behind a reverse proxy that rewrites them. | The three OAuth variables are a set: configure all three or none. Setting only some of them makes the server print `Incomplete OAuth configuration for HTTP mode` and exit `1`, rather than quietly start unauthenticated. diff --git a/docs/service.md b/docs/service.md index 10a76ca5b..5b90c275d 100644 --- a/docs/service.md +++ b/docs/service.md @@ -234,6 +234,40 @@ Tool results use text content. `organizations`, `alerts`, and `threat_feed` seri Each tool call produces a bounded, versioned audit event. By default, the server appends JSONL records to `~/.socket/mcp-audit.jsonl`. Set `SOCKET_MCP_AUDIT_LOG` to choose another file or `SOCKET_MCP_AUDIT_SINK=stderr` to write records to stderr. The default sink is JSONL. Unknown sink values produce a diagnostic and fall back to JSONL. Existing records are left in place. +### Error reporting + +Error reporting is off by default. Set `SOCKET_MCP_SENTRY_DSN` in HTTP mode to send errors to Sentry, and `SOCKET_MCP_SENTRY_ENVIRONMENT` to name the environment (Sentry's default is `production`). Without the DSN, the Sentry SDK is never loaded and nothing is sent. stdio mode never reports, even when the DSN is set. The DSN must use HTTPS; cleartext HTTP is accepted only for a loopback host, for local testing. A DSN that does not parse, or uses HTTP elsewhere, logs one line, and the server starts without reporting. + +Events are sent only for failures on the server's side: + +- A tool handler throws. +- A tool call fails because the Socket API answered with a 5xx, the connection failed, the request timed out, or the response could not be handled. +- An anonymous call falls back to the deployment's `SOCKET_API_TOKEN`, and the Socket API rejects that token with 401 or 403. +- The MCP handler or the Node adapter reports a serving failure, request routing or body reading throws, or OAuth token verification throws. + +Invalid arguments, unknown tools, a caller's missing or rejected token, other upstream 4xx answers, and clients that disconnect are the caller's doing. They send no event; each adds a breadcrumb to the next one. + +Every event carries these tags: + +| Tag | Values | +| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `mcp.tool` | A registered tool name, or `unknown` | +| `mcp.client` | The request's `clientInfo.name` (2026-07-28 requests), else the first product token of the `User-Agent`, else `unknown`. Lowercased and capped at 64 characters. | +| `mcp.client_version` | The matching version, when it looks like one and fits in 32 characters | +| `auth.outcome` | `anonymous`, `bearer_ok`, `bearer_denied`, `operator_denied` (the deployment's own token was rejected), or `unknown` for errors outside a tool call | +| `tool.outcome` | `failure` or `denied`, on tool-call events | +| `failure.cause` | `thrown`, `upstream_5xx`, `network`, `timeout`, `exception`, or `upstream_denied`, on tool-call events | +| `upstream.status` | The upstream HTTP status, when there was one | +| `error.code` | A Node error code such as `ECONNREFUSED`, when there was one | +| `error.source` | `mcp_handler`, `mcp_adapter`, `mcp_request`, `http_route`, `http_body`, or `oauth_verify`, on events outside a tool call | +| `transport` | `http` | + +The event's `release` is the package version. Tool-call events are grouped by tool, outcome, auth outcome and failure cause, and other events by source and error type, never by message text. + +Before an event leaves the process, it is rebuilt from an allowlist. The exception message is replaced with a summary built from the tags, such as `alerts upstream_5xx 502`, because upstream errors embed request URLs and response bodies. Stack frames keep only the function name, the file's basename, the line and the column. Events carry no tokens or token hashes, no request headers (including `Authorization`, `Cookie` and `Mcp-Session-Id`), no query strings, no tool arguments or results, no user data and no host name. Only errors are sent; there is no performance tracing. + +On `SIGINT` or `SIGTERM`, the server waits up to two seconds for queued events, then exits. An unreachable Sentry never blocks or fails a request: each send gives up after five seconds. + ### Health check endpoint In HTTP mode, `GET /health` returns a JSON object with `status`, `service`, `version`, and `timestamp`. The endpoint skips origin validation so a health probe can omit `Origin`. diff --git a/lib/blob.mts b/lib/blob.mts index 42930de63..ff20dd88d 100644 --- a/lib/blob.mts +++ b/lib/blob.mts @@ -202,7 +202,9 @@ export async function fetchRawBytes( try { res = await httpRequest(url, { headers }) } catch (e) { - throw new Error(`blob request to ${url} failed: ${errorMessage(e)}`) + throw new Error(`blob request to ${url} failed: ${errorMessage(e)}`, { + cause: e, + }) } if (!res.ok) { throw new UpstreamHttpError( diff --git a/lib/cli.mts b/lib/cli.mts index be1c01e19..60afc7eea 100644 --- a/lib/cli.mts +++ b/lib/cli.mts @@ -11,7 +11,14 @@ import { serveStdio } from '@modelcontextprotocol/server/stdio' import { errorMessage } from '@socketsecurity/lib/errors/message' -import { getMcpHttpMode, getMcpPort, getSocketApiToken } from './env.mts' +import { + getMcpHttpMode, + getMcpPort, + getSocketApiToken, + getSocketMcpSentryDsn, + getSocketMcpSentryEnvironment, +} from './env.mts' +import { startErrorReporting } from './error-reporting.mts' import { getApiKeyInteractively } from './http.mts' import { startHttpServer } from './http-server.mts' import { logger } from './logger.mts' @@ -45,9 +52,14 @@ export interface SocketMcpCliDeps { readonly resolveLocalOAuthSession?: () => Promise< LocalOAuthSession | undefined > + // SOCKET_MCP_SENTRY_DSN and SOCKET_MCP_SENTRY_ENVIRONMENT. HTTP mode turns + // error reporting on only when the DSN is set; stdio mode ignores both. + readonly sentryDsn: string | undefined + readonly sentryEnvironment: string | undefined readonly serveStdio: typeof serveStdio readonly setOauthEnabled: () => { issuer: string } | undefined readonly setStaticApiKey: typeof setStaticApiKey + readonly startErrorReporting: typeof startErrorReporting readonly startHttpServer: typeof startHttpServer } @@ -68,9 +80,12 @@ export function createSocketMcpCliDeps(): SocketMcpCliDeps { promptForApiKey: getApiKeyInteractively, refreshLocalOAuthSession, resolveLocalOAuthSession, + sentryDsn: getSocketMcpSentryDsn(), + sentryEnvironment: getSocketMcpSentryEnvironment(), serveStdio, setOauthEnabled, setStaticApiKey, + startErrorReporting, startHttpServer, } } @@ -186,6 +201,15 @@ export async function runSocketMcpCli(deps: SocketMcpCliDeps): Promise { } if (useHttp) { + // Opt-in and HTTP-only: without a DSN nothing is loaded. A DSN that fails + // to start reporting is logged and the server starts anyway. + if (deps.sentryDsn) { + await deps.startErrorReporting({ + dsn: deps.sentryDsn, + environment: deps.sentryEnvironment, + mode: 'http', + }) + } deps.startHttpServer(deps.port) return 0 } diff --git a/lib/env.mts b/lib/env.mts index 0321687bd..2c9736adb 100644 --- a/lib/env.mts +++ b/lib/env.mts @@ -137,6 +137,18 @@ export function getSocketMcpAuditSink(): 'jsonl' | 'stderr' | 'unknown' { return sink === 'stderr' ? 'stderr' : 'unknown' } +// The Sentry DSN for HTTP-mode error reporting. Unset by default, which keeps +// reporting off: the Sentry SDK is never loaded and nothing leaves the +// process. stdio mode ignores it. +export function getSocketMcpSentryDsn(): string | undefined { + return envString('SOCKET_MCP_SENTRY_DSN') +} + +// The Sentry `environment` reported events carry, e.g. `production`. +export function getSocketMcpSentryEnvironment(): string | undefined { + return envString('SOCKET_MCP_SENTRY_ENVIRONMENT') +} + // OAuth getters — not yet in the canonical lib surface. These read // the same env vars that the future lib getters will read. Once // lib ships them, this file's OAuth section can be replaced with diff --git a/lib/error-reporting-sentry.mts b/lib/error-reporting-sentry.mts new file mode 100644 index 000000000..4703f14fd --- /dev/null +++ b/lib/error-reporting-sentry.mts @@ -0,0 +1,364 @@ +/** + * @file The Sentry client behind error reporting. `error-reporting.mts` loads + * this module with a dynamic import, and only when SOCKET_MCP_SENTRY_DSN is + * set in HTTP mode. The client comes from `@sentry/core` alone: no + * OpenTelemetry, no module patching, no default integrations and no + * tracing. Envelopes go out through the shared `httpRequest` helper (Node's + * own HTTP and HTTPS modules), to an HTTPS DSN. + * Every event is rebuilt from an allowlist in `beforeSend`, so nothing the + * SDK or an error happens to carry leaves the process unless it is named + * here. Exception messages are replaced with a summary built from the + * bounded tags, because upstream errors embed request URLs (org slugs, + * package names, query strings) and response bodies. Stack frames keep + * their function, file basename and position. Request data, users, extra + * context and the host name are dropped. + */ + +import process from 'node:process' + +import { + createStackParser, + createTransport, + linkedErrorsIntegration, + Scope, +} from '@sentry/core' +import type { + BaseTransportOptions, + Breadcrumb, + ErrorEvent, + Exception, + StackFrame, + Transport, +} from '@sentry/core' +import { nodeStackLineParser, ServerRuntimeClient } from '@sentry/core/server' +import { httpRequest } from '@socketsecurity/lib/http-request/request' + +import type { ErrorReporter } from './error-reporting.mts' +import { isSecureOrLoopback } from './http.mts' + +export interface SentryReporterOptions { + readonly dsn: string + readonly environment?: string | undefined + readonly makeTransport?: + | ((options: BaseTransportOptions) => Transport) + | undefined + readonly release: string +} + +// Tags an event may carry. Values are re-checked against TAG_VALUE_PATTERN. +export const ALLOWED_TAG_KEYS: ReadonlySet = new Set([ + 'auth.outcome', + 'error.code', + 'error.source', + 'failure.cause', + 'mcp.client', + 'mcp.client_version', + 'mcp.tool', + 'tool.outcome', + 'transport', + 'upstream.status', +]) + +const MAX_BREADCRUMBS = 20 +const REDACTED = '[redacted]' +const TAG_VALUE_PATTERN = /^[\w.:+-]{1,64}$/u +const TRANSPORT_TIMEOUT_MS = 5000 + +/** + * Build a reporter, or answer undefined when the DSN does not parse. The + * client and its scope are private to the reporter rather than installed as + * Sentry's global client. + */ +export function createSentryReporter( + options: SentryReporterOptions, +): ErrorReporter | undefined { + // The SDK prints a DSN it cannot parse to the console, so a malformed one + // is turned away here first. + if (!isPlausibleDsn(options.dsn)) { + return undefined + } + const client = new ServerRuntimeClient({ + dsn: options.dsn, + ...(options.environment ? { environment: options.environment } : {}), + release: options.release, + transport: options.makeTransport ?? makeHttpTransport, + stackParser: createStackParser(nodeStackLineParser()), + integrations: [linkedErrorsIntegration({ limit: 3 })], + beforeSend: event => sanitizeEvent(event), + // Errors only: no span streaming, no request, header, cookie, body or + // variable capture. + traceLifecycle: 'static', + dataCollection: { + cookies: false, + databaseQueryData: false, + frameContextLines: 0, + genAI: { inputs: false, outputs: false }, + graphQL: { document: false, variables: false }, + httpBodies: [], + httpHeaders: false, + mcp: { inputs: false, outputs: false }, + queues: false, + stackFrameVariables: false, + urlQueryParams: false, + userInfo: false, + }, + maxBreadcrumbs: MAX_BREADCRUMBS, + sendClientReports: false, + platform: 'node', + runtime: { name: 'node', version: process.version }, + }) + if (!client.getDsn()) { + return undefined + } + const scope = new Scope() + scope.setClient(client) + client.init() + return { + addBreadcrumb(breadcrumb) { + scope.addBreadcrumb( + { + category: 'mcp', + level: 'info', + message: breadcrumb.message, + data: { ...breadcrumb.data }, + }, + MAX_BREADCRUMBS, + ) + }, + capture(error, context) { + const eventScope = scope.clone() + eventScope.setLevel('error') + eventScope.setTags({ ...context.tags }) + eventScope.setFingerprint([...context.fingerprint]) + eventScope.captureException(error ?? new Error(REDACTED), { + mechanism: { type: 'socket-mcp', handled: true }, + }) + }, + close: timeoutMs => client.close(timeoutMs), + flush: timeoutMs => client.flush(timeoutMs), + } +} + +// Post each envelope once, without following redirects. A request that hangs +// past five seconds is aborted; the SDK records the loss and the server +// carries on. +export function makeHttpTransport(options: BaseTransportOptions): Transport { + return createTransport(options, async request => { + const response = await httpRequest(options.url, { + method: 'POST', + body: + typeof request.body === 'string' + ? request.body + : Buffer.from(request.body), + ...(options.headers ? { headers: options.headers } : {}), + timeout: TRANSPORT_TIMEOUT_MS, + retries: 0, + followRedirects: false, + }) + return { + statusCode: response.status, + headers: { + 'retry-after': response.headers['retry-after']?.toString() ?? null, + 'x-sentry-rate-limits': + response.headers['x-sentry-rate-limits']?.toString() ?? null, + }, + } + }) +} + +/** + * Rebuild an event from the fields error reporting means to send: ids, + * level, release and environment, the SDK name, allowlisted tags, the + * fingerprint, exception types with message-free stack frames, our own + * breadcrumbs and the Node version. Everything else is dropped. + */ +export function sanitizeEvent(event: ErrorEvent): ErrorEvent { + const tags = sanitizeTags(event.tags) + const values = event.exception?.values ?? [] + const lastIndex = values.length - 1 + const safe: ErrorEvent = { + type: undefined, + contexts: { runtime: { name: 'node', version: process.version } }, + exception: { + values: values.map((value, index) => + // Sentry lists causes first and the reported error last; only the + // last one gets the readable summary. + sanitizeException( + value, + index === lastIndex ? summarize(tags) : REDACTED, + ), + ), + }, + tags, + } + if (event.event_id) { + safe.event_id = event.event_id + } + if (event.timestamp !== undefined) { + safe.timestamp = event.timestamp + } + if (event.level) { + safe.level = event.level + } + if (event.platform) { + safe.platform = event.platform + } + const release = boundedTagValue(event.release) + if (release) { + safe.release = release + } + const environment = boundedTagValue(event.environment) + if (environment) { + safe.environment = environment + } + if (event.sdk?.name && event.sdk.version) { + safe.sdk = { name: event.sdk.name, version: event.sdk.version } + } + const fingerprint = event.fingerprint + ?.map(boundedTagValue) + .filter(part => part !== undefined) + if (fingerprint?.length) { + safe.fingerprint = fingerprint + } + const breadcrumbs = event.breadcrumbs + ?.filter(breadcrumb => breadcrumb.category === 'mcp') + .map(sanitizeBreadcrumb) + if (breadcrumbs?.length) { + safe.breadcrumbs = breadcrumbs + } + return safe +} + +// An HTTPS URL with a public key and a numeric project id, the shape the SDK +// accepts. Cleartext HTTP is accepted only for a recorder on this machine. +export function isPlausibleDsn(dsn: string): boolean { + try { + const url = new URL(dsn) + return ( + isSecureOrLoopback(url) && + url.username !== '' && + /\/\d+$/u.test(url.pathname) + ) + } catch { + return false + } +} + +function boundedTagValue(value: unknown): string | undefined { + const text = typeof value === 'number' ? String(value) : value + return typeof text === 'string' && TAG_VALUE_PATTERN.test(text) + ? text + : undefined +} + +function sanitizeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb { + const data: Record = {} + for (const [key, value] of Object.entries(breadcrumb.data ?? {})) { + const safeValue = boundedTagValue(value) + if (/^[\w.]{1,32}$/u.test(key) && safeValue) { + data[key] = safeValue + } + } + return { + category: 'mcp', + ...(breadcrumb.level ? { level: breadcrumb.level } : {}), + ...(breadcrumb.timestamp !== undefined + ? { timestamp: breadcrumb.timestamp } + : {}), + message: boundedMessage(breadcrumb.message), + data, + } +} + +function boundedMessage(value: unknown): string { + return typeof value === 'string' && /^[\w .:-]{1,64}$/u.test(value) + ? value + : REDACTED +} + +function sanitizeException(value: Exception, summary: string): Exception { + const type = + typeof value.type === 'string' && + /^[A-Za-z_$][\w$]{0,63}$/u.test(value.type) + ? value.type + : 'Error' + const safe: Exception = { type, value: summary } + if (value.mechanism) { + const { exception_id, handled, parent_id, source } = value.mechanism + safe.mechanism = { + type: boundedTagValue(value.mechanism.type) ?? 'generic', + ...(handled !== undefined ? { handled } : {}), + ...(exception_id !== undefined ? { exception_id } : {}), + ...(parent_id !== undefined ? { parent_id } : {}), + ...(typeof source === 'string' && /^[\w.[\]]{1,32}$/u.test(source) + ? { source } + : {}), + } + } + const frames = value.stacktrace?.frames + if (frames?.length) { + safe.stacktrace = { frames: frames.map(sanitizeFrame) } + } + return safe +} + +// Keep where a frame ran, never what it held: function name, file basename, +// line, column and the in-app flag. +function sanitizeFrame(frame: StackFrame): StackFrame { + const safe: StackFrame = {} + if ( + typeof frame.function === 'string' && + /^[\w$.<>[\] -]{1,128}$/u.test(frame.function) + ) { + safe.function = frame.function + } + const filename = safeFilename(frame.filename) + if (filename) { + safe.filename = filename + } + if (frame.lineno !== undefined) { + safe.lineno = frame.lineno + } + if (frame.colno !== undefined) { + safe.colno = frame.colno + } + if (frame.in_app !== undefined) { + safe.in_app = frame.in_app + } + return safe +} + +function safeFilename(filename: string | undefined): string | undefined { + if (!filename) { + return undefined + } + if (/^node:[\w/.-]{1,120}$/u.test(filename)) { + return filename + } + // A basename, so no install path (and no user's home directory) is sent. + const base = filename.split(/[/\\]/u).pop() + return base && /^[\w.-]{1,128}$/u.test(base) ? base : undefined +} + +function sanitizeTags(tags: ErrorEvent['tags']): Record { + const safe: Record = {} + for (const [key, value] of Object.entries(tags ?? {})) { + const safeValue = boundedTagValue(value) + if (ALLOWED_TAG_KEYS.has(key) && safeValue) { + safe[key] = safeValue + } + } + return safe +} + +// A readable event title from bounded tags alone, e.g. `alerts upstream_5xx +// 502` or `mcp_handler`. +function summarize(tags: Readonly>): string { + const parts = + tags['error.source'] !== undefined + ? [tags['error.source']] + : [tags['mcp.tool'], tags['failure.cause'] ?? tags['tool.outcome']] + parts.push(tags['upstream.status'], tags['error.code']) + const summary = parts.filter(part => part !== undefined).join(' ') + return summary || REDACTED +} diff --git a/lib/error-reporting.mts b/lib/error-reporting.mts new file mode 100644 index 000000000..da37b6fa1 --- /dev/null +++ b/lib/error-reporting.mts @@ -0,0 +1,437 @@ +/** + * @file Opt-in error reporting for the HTTP server. It is off unless + * SOCKET_MCP_SENTRY_DSN is set, and stdio mode never turns it on. This module + * decides which tool calls and server errors are worth an event and which + * bounded tags each one carries. It loads the Sentry client + * (`error-reporting-sentry.mts`) with a dynamic import only once reporting + * is on, so a default start never evaluates the Sentry SDK and sends + * nothing. + * Events are for real failures: a tool handler throwing, an upstream 5xx, + * network error or timeout behind a tool, an unexpected exception while + * serving a request. Invalid input, unknown tools, a caller's denied token + * and upstream 4xx answers are the caller's doing, so they leave at most a + * breadcrumb. + */ + +import process from 'node:process' + +import type { BaseTransportOptions, Transport } from '@sentry/core' + +import { logger } from './logger.mts' +import type { + ToolAuditIdentity, + ToolAuditOutcome, +} from './tool-audit-event.mts' +import { classifyToolFailure, errorCode } from './tool-outcome.mts' +import type { ToolFailureCause } from './tool-outcome.mts' +import { VERSION } from './version.mts' + +// How a tool call's credentials fared, as far as this server can tell: +// `operator` is the local stdio user, `anonymous` an HTTP caller without a +// token, `operator_denied` an anonymous call whose fallback to the deploy's +// shared token was rejected upstream, `bearer_ok` a caller token upstream did +// not reject, and `bearer_denied` one it answered 401 or 403. `unknown` marks +// server errors raised outside any one tool call. +export type AuthOutcome = + | 'anonymous' + | 'bearer_denied' + | 'bearer_ok' + | 'operator' + | 'operator_denied' + | 'unknown' + +export type FailureCause = ToolFailureCause | 'thrown' + +// Where a server error surfaced outside a tool handler. +export type ServerErrorSource = + | 'http_body' + | 'http_route' + | 'mcp_adapter' + | 'mcp_handler' + | 'mcp_request' + | 'oauth_verify' + +export interface ErrorReportingConfig { + readonly dsn: string | undefined + readonly environment?: string | undefined + // Builds the Sentry transport. Tests pass a recording transport; the default + // posts envelopes with the global `fetch`. + readonly makeTransport?: + | ((options: BaseTransportOptions) => Transport) + | undefined + readonly mode: 'http' | 'stdio' +} + +export interface ErrorReportContext { + readonly fingerprint: readonly string[] + readonly tags: Readonly> +} + +export interface ErrorReportBreadcrumb { + readonly data: Readonly> + readonly message: string +} + +// The client side of reporting, which the lazily loaded Sentry module builds. +export interface ErrorReporter { + addBreadcrumb(breadcrumb: ErrorReportBreadcrumb): void + capture(error: unknown, context: ErrorReportContext): void + close(timeoutMs: number): PromiseLike + flush(timeoutMs: number): PromiseLike +} + +export interface ToolCallReport { + // `clientInfo` from the request's 2026-07-28 `_meta` envelope, unvalidated. + readonly clientInfo: unknown + readonly error?: unknown + readonly identity: ToolAuditIdentity + readonly outcome: ToolAuditOutcome + // The handler's result, which carries the upstream failure cause. + readonly result?: object | undefined + readonly threw: boolean + // A registered tool name, or `unknown`. + readonly tool: string + readonly transport: string + readonly userAgent: string | undefined +} + +export interface ServerErrorReport { + readonly hasBearer?: boolean | undefined + readonly source: ServerErrorSource + readonly userAgent?: string | undefined +} + +export const SHUTDOWN_FLUSH_TIMEOUT_MS = 2000 + +const CLIENT_NAME_MAX_LENGTH = 64 + +// Failure causes that point at the server side of an upstream call rather than +// at the caller's request. +const REPORTED_FAILURE_CAUSES: ReadonlySet = new Set([ + 'exception', + 'network', + 'thrown', + 'timeout', + 'upstream_5xx', +]) + +let reporter: ErrorReporter | undefined + +export async function closeErrorReporting(timeoutMs = 0): Promise { + const active = reporter + reporter = undefined + if (active) { + await Promise.resolve(active.close(timeoutMs)).catch(() => false) + } +} + +// A bounded `error.code` tag value, e.g. `ECONNREFUSED`. +export function errorCodeTag(error: unknown): string | undefined { + const code = errorCode(error) + return code !== undefined && /^[A-Z][A-Z0-9_]{1,39}$/u.test(code) + ? code + : undefined +} + +// The error's constructor name when it reads as an identifier, for grouping. +export function errorTypeName(error: unknown): string { + if (error instanceof Error && /^[A-Za-z_$][\w$]{0,63}$/u.test(error.name)) { + return error.name + } + return error instanceof Error ? 'Error' : typeof error +} + +// Wait up to `timeoutMs` for queued events to send. Never rejects, and answers +// true when reporting is off. +export async function flushErrorReporting(timeoutMs: number): Promise { + const active = reporter + if (!active) { + return true + } + try { + return await active.flush(timeoutMs) + } catch { + return false + } +} + +// Flush queued events when the process is asked to stop, then let the signal +// take its default course. Only the CLI installs this, once reporting is on. +export function flushErrorReportingOnSignals( + signals: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM'], +): void { + for (const signal of signals) { + process.once(signal, () => { + void flushErrorReporting(SHUTDOWN_FLUSH_TIMEOUT_MS).finally(() => { + process.kill(process.pid, signal) + }) + }) + } +} + +/** + * Turn reporting on when a DSN is set in HTTP mode. Answers whether it is on. + * Without a DSN, or in stdio mode, it returns before loading the Sentry + * module. A broken DSN or a failed load logs one line and leaves the server + * running without reporting. + */ +export async function initErrorReporting( + config: ErrorReportingConfig, +): Promise { + if (reporter) { + return true + } + if (config.mode !== 'http' || !config.dsn) { + return false + } + try { + const { createSentryReporter } = + await import('./error-reporting-sentry.mts') + const created = createSentryReporter({ + dsn: config.dsn, + environment: config.environment, + makeTransport: config.makeTransport, + release: VERSION, + }) + if (!created) { + logger.warn( + 'SOCKET_MCP_SENTRY_DSN is not a valid HTTPS Sentry DSN; error reporting is off', + ) + return false + } + reporter = created + logger.info( + `Error reporting to Sentry is on${config.environment ? ` (environment ${config.environment})` : ''}`, + ) + return true + } catch (error) { + // The message could echo the DSN, so log only the error type. + logger.warn( + `Error reporting could not start (${errorTypeName(error)}); continuing without it`, + ) + return false + } +} + +// The CLI's entry: turn reporting on and, once it is on, flush queued events +// when the process is told to stop. +export async function startErrorReporting( + config: ErrorReportingConfig, +): Promise { + if (await initErrorReporting(config)) { + flushErrorReportingOnSignals() + } +} + +export function isErrorReportingEnabled(): boolean { + return reporter !== undefined +} + +// Whether a tool call deserves an event rather than at most a breadcrumb. +export function isReportableToolCall( + outcome: ToolAuditOutcome, + cause: FailureCause | undefined, + auth: AuthOutcome, +): boolean { + if (cause === 'thrown') { + return true + } + if (outcome === 'denied') { + return auth === 'operator_denied' + } + return ( + outcome === 'failure' && + cause !== undefined && + REPORTED_FAILURE_CAUSES.has(cause) + ) +} + +// Name the MCP client: `clientInfo.name` when the request carried one, +// otherwise the first product token of the User-Agent, otherwise `unknown`. +// Names are lowercased, reduced to [a-z0-9._-] and capped at 64 characters; a +// version is kept only when it looks like one and fits in 32. +export function resolveMcpClient( + clientInfo: unknown, + userAgent: string | undefined, +): { name: string; version?: string | undefined } { + if (typeof clientInfo === 'object' && clientInfo !== null) { + const name = normalizeClientName(Reflect.get(clientInfo, 'name')) + if (name) { + return { + name, + version: normalizeClientVersion(Reflect.get(clientInfo, 'version')), + } + } + } + const product = userAgent?.trim().split(/\s+/u)[0] + if (product) { + const slash = product.indexOf('/') + const name = normalizeClientName( + slash === -1 ? product : product.slice(0, slash), + ) + if (name) { + return { + name, + version: + slash === -1 + ? undefined + : normalizeClientVersion(product.slice(slash + 1)), + } + } + } + return { name: 'unknown' } +} + +export function resolveAuthOutcome( + identity: ToolAuditIdentity, + cause: FailureCause | undefined, +): AuthOutcome { + const deniedUpstream = cause === 'upstream_denied' + switch (identity.kind) { + case 'bearer': + return deniedUpstream ? 'bearer_denied' : 'bearer_ok' + case 'operator': + return deniedUpstream ? 'operator_denied' : 'operator' + case 'anonymous': + // An anonymous call reaches upstream only on the deploy's shared token, + // so a rejection there is the operator's credential failing. + return deniedUpstream ? 'operator_denied' : 'anonymous' + } +} + +// Report an error raised outside a tool handler: routing, the MCP handler or +// the Node adapter. A client hanging up mid-request is not a server failure. +export function reportServerError( + error: unknown, + report: ServerErrorReport, +): void { + const active = reporter + if (!active) { + return + } + try { + const code = errorCodeTag(error) + // Token verification talks to the OAuth issuer, so a reset there is an + // upstream failure, not the caller leaving. + if (report.source !== 'oauth_verify' && isClientDisconnect(error)) { + active.addBreadcrumb({ + message: 'client disconnected', + data: { source: report.source, ...(code ? { code } : {}) }, + }) + return + } + const client = resolveMcpClient(undefined, report.userAgent) + active.capture(error, { + fingerprint: [ + 'socket-mcp', + 'server', + report.source, + errorTypeName(error), + ], + tags: { + 'auth.outcome': report.hasBearer ? 'bearer_ok' : 'unknown', + 'error.source': report.source, + 'mcp.client': client.name, + ...(client.version ? { 'mcp.client_version': client.version } : {}), + 'mcp.tool': 'unknown', + transport: 'http', + ...(code ? { 'error.code': code } : {}), + }, + }) + } catch { + // Reporting never affects the request it describes. + } +} + +// Report one finished tool call. Successes are ignored; client-side outcomes +// leave a breadcrumb; real failures become one event grouped by tool, outcome, +// auth outcome and failure cause rather than by message text. +export function reportToolCall(report: ToolCallReport): void { + const active = reporter + if (!active || report.outcome === 'success') { + return + } + try { + const failure = report.result + ? classifyToolFailure(report.result) + : undefined + const cause: FailureCause | undefined = report.threw + ? 'thrown' + : failure?.cause + const auth = resolveAuthOutcome(report.identity, cause) + if (!isReportableToolCall(report.outcome, cause, auth)) { + active.addBreadcrumb({ + message: 'tool call', + data: { + 'auth.outcome': auth, + 'mcp.tool': report.tool, + 'tool.outcome': report.outcome, + ...(cause ? { 'failure.cause': cause } : {}), + }, + }) + return + } + const error = report.threw ? report.error : failure?.error + const client = resolveMcpClient(report.clientInfo, report.userAgent) + const code = errorCodeTag(error) + const status = failure?.status + active.capture(error, { + fingerprint: [ + 'socket-mcp', + 'tool', + report.tool, + report.outcome, + auth, + cause ?? 'none', + ], + tags: { + 'auth.outcome': auth, + 'mcp.client': client.name, + ...(client.version ? { 'mcp.client_version': client.version } : {}), + 'mcp.tool': report.tool, + 'tool.outcome': report.outcome, + transport: report.transport, + ...(cause ? { 'failure.cause': cause } : {}), + ...(code ? { 'error.code': code } : {}), + ...(status !== undefined && status >= 100 && status <= 599 + ? { 'upstream.status': String(status) } + : {}), + }, + }) + } catch { + // Reporting never affects the tool call it describes. + } +} + +function isClientDisconnect(error: unknown): boolean { + if (!(error instanceof Error)) { + return false + } + const code = errorCode(error) + return ( + error.name === 'AbortError' || + error.message === 'aborted' || + code === 'ECONNABORTED' || + code === 'ECONNRESET' || + code === 'EPIPE' || + code === 'ERR_STREAM_PREMATURE_CLOSE' + ) +} + +function normalizeClientName(value: unknown): string | undefined { + if (typeof value !== 'string') { + return undefined + } + const name = value + .toLowerCase() + .replace(/[^a-z0-9._-]+/gu, '-') + .slice(0, CLIENT_NAME_MAX_LENGTH) + .replace(/^[-.]+|[-.]+$/gu, '') + return name || undefined +} + +function normalizeClientVersion(value: unknown): string | undefined { + return typeof value === 'string' && /^\d[\w.+-]{0,31}$/u.test(value) + ? value + : undefined +} diff --git a/lib/files.mts b/lib/files.mts index 6fe362908..b42170779 100644 --- a/lib/files.mts +++ b/lib/files.mts @@ -136,7 +136,9 @@ export async function fetchFileList( try { res = await httpRequest(url, { headers }) } catch (e) { - throw new Error(`file-list request to ${url} failed: ${errorMessage(e)}`) + throw new Error(`file-list request to ${url} failed: ${errorMessage(e)}`, { + cause: e, + }) } if (!res.ok) { throw new UpstreamHttpError( diff --git a/lib/http-server.mts b/lib/http-server.mts index 560cf3042..ec8280629 100644 --- a/lib/http-server.mts +++ b/lib/http-server.mts @@ -5,10 +5,16 @@ // live in http-public-routes.mts. import { toNodeHandler } from '@modelcontextprotocol/node' import type { NodeMcpRequestHandler } from '@modelcontextprotocol/node' -import { createMcpHandler } from '@modelcontextprotocol/server' +import { + createMcpHandler, + MissingRequiredClientCapabilityError, + UnsupportedProtocolVersionError, +} from '@modelcontextprotocol/server' import { errorMessage } from '@socketsecurity/lib/errors/message' import { createServer } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http' +import { reportServerError } from './error-reporting.mts' +import type { ServerErrorReport } from './error-reporting.mts' import { createConfiguredServer } from './server.mts' import { getRequestBaseUrl, getRequestHeaderValue, writeJson } from './http.mts' import { @@ -67,9 +73,14 @@ export function applyClientApiKey(req: AuthenticatedRequest): void { // the only move left is closing the response. export function createRouteFailureHandler( res: ServerResponse, + req?: AuthenticatedRequest | undefined, ): (error: unknown) => void { return error => { logger.error(`Unhandled request failure: ${errorMessage(error)}`) + reportServerError(error, { + source: 'http_route', + ...requestReportContext(req), + }) if (!res.headersSent) { writeJson(res, 500, { jsonrpc: '2.0', @@ -87,12 +98,18 @@ export function createRouteFailureHandler( // error — rather than inside a tool. export function handleMcpAdapterError(error: unknown): void { logger.error(`MCP adapter failed: ${errorMessage(error)}`) + reportServerError(error, { source: 'mcp_adapter' }) } // The MCP handler's `onerror` sink. Reached when serving one exchange throws -// past the per-request handling in `handleMcpRequest`. +// past the per-request handling in `handleMcpRequest`, and also when the +// handler turns a request away for the client's own mistake, which is logged +// but not reported. export function handleMcpHandlerError(error: unknown): void { logger.error(`MCP request failed: ${errorMessage(error)}`) + if (!isMcpClientRejection(error)) { + reportServerError(error, { source: 'mcp_handler' }) + } } // Hand one request to the MCP handler. The adapter reads the request stream @@ -135,6 +152,10 @@ export async function handleMcpRequest( return } logger.error(`Error reading request body: ${errorMessage(error)}`) + reportServerError(error, { + source: 'http_body', + ...requestReportContext(req), + }) if (!res.headersSent) { writeJson(res, 500, { jsonrpc: '2.0', @@ -172,6 +193,10 @@ export async function handleMcpRequest( logger.error( `Error processing ${req.method} request: ${errorMessage(error)}`, ) + reportServerError(error, { + source: 'mcp_request', + ...requestReportContext(req), + }) if (!res.headersSent) { writeJson(res, 500, { jsonrpc: '2.0', @@ -182,6 +207,19 @@ export async function handleMcpRequest( } } +// The MCP handler hands its `onerror` the requests it rejects for the +// client's own mistake — an unsupported protocol revision, missing client +// capabilities, a wrong Content-Type, headers that contradict the body — +// alongside real serving failures. Only the latter are worth an event. +export function isMcpClientRejection(error: unknown): boolean { + return ( + error instanceof UnsupportedProtocolVersionError || + error instanceof MissingRequiredClientCapabilityError || + (error instanceof Error && + /^(?:Rejected |Unsupported Media Type\b)/u.test(error.message)) + ) +} + // Read and buffer the POST body to a string, capped at MAX_POST_BODY_BYTES. // Async iteration is modern stream consumption — equivalent to 'data' + // 'end' without the callback wiring. The running byte count is measured on @@ -212,6 +250,22 @@ export async function readPostBody(req: IncomingMessage): Promise { return body } +// What an error report may say about the request it came from: whether a +// caller token was attached and the client's User-Agent, which the reporter +// reduces to a product name. +function requestReportContext( + req: AuthenticatedRequest | undefined, +): Omit { + if (!req) { + return {} + } + const userAgent = getRequestHeaderValue(req.headers['user-agent']) + return { + hasBearer: Boolean(req.auth?.token), + ...(userAgent ? { userAgent } : {}), + } +} + // Routes a single request: health endpoint, origin validation, OAuth // metadata exposure, then dispatch to the MCP handler. export async function routeRequest( @@ -331,7 +385,7 @@ export function startHttpServer(port: number): void { let listeningPort = port const httpServer = createServer((req, res) => { routeRequest(mcpHandler, req, res, listeningPort).catch( - createRouteFailureHandler(res), + createRouteFailureHandler(res, req), ) }) diff --git a/lib/http.mts b/lib/http.mts index 0d7414ad8..60bddaa72 100644 --- a/lib/http.mts +++ b/lib/http.mts @@ -1,3 +1,4 @@ +import { isIP } from 'node:net' import readline from 'node:readline' import type { IncomingMessage, ServerResponse } from 'node:http' @@ -202,6 +203,14 @@ export function getRequestHeaderValue( return header || '' } +// HTTPS anywhere, or cleartext HTTP to this machine only (local test servers). +export function isSecureOrLoopback(url: URL): boolean { + return ( + url.protocol === 'https:' || + (url.protocol === 'http:' && isLoopbackHost(url.hostname)) + ) +} + // Parse a response body that must be a JSON object — not an array, not a // primitive. Throws a contextual error pointing at the upstream caller. export function parseJsonObject( @@ -294,3 +303,15 @@ export function writeOAuthError( }, ) } + +function isLoopbackHost(hostname: string): boolean { + const host = hostname.toLowerCase().replace(/\.$/u, '') + if (host === 'localhost' || host.endsWith('.localhost')) { + return true + } + const address = host.replace(/^\[|\]$/gu, '') + if (isIP(address) === 4) { + return Number.parseInt(address.split('.')[0]!, 10) === 127 + } + return address === '::1' +} diff --git a/lib/local-oauth.mts b/lib/local-oauth.mts index 02ebc8f59..bbfeeb139 100644 --- a/lib/local-oauth.mts +++ b/lib/local-oauth.mts @@ -7,7 +7,6 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto' import { promises as fs, readFileSync } from 'node:fs' import { createServer } from 'node:http' -import { isIP } from 'node:net' import { spawn } from 'node:child_process' import os from 'node:os' import path from 'node:path' @@ -15,7 +14,7 @@ import path from 'node:path' import { httpRequest } from '@socketsecurity/lib/http-request/request' import { getSocketApiUrl } from './env.mts' -import { parseJsonObject } from './http.mts' +import { isSecureOrLoopback, parseJsonObject } from './http.mts' import { logger } from './logger.mts' const DEFAULT_OAUTH_BASE_URL = 'https://api.socket.dev' @@ -89,25 +88,6 @@ function oauthError(message: string): Error { return new Error(`Socket MCP browser sign-in: ${message}`) } -function isLoopbackHost(hostname: string): boolean { - const host = hostname.toLowerCase().replace(/\.$/u, '') - if (host === 'localhost' || host.endsWith('.localhost')) { - return true - } - const address = host.replace(/^\[|\]$/gu, '') - if (isIP(address) === 4) { - return Number.parseInt(address.split('.')[0]!, 10) === 127 - } - return address === '::1' -} - -function isSecureOrLoopback(url: URL): boolean { - return ( - url.protocol === 'https:' || - (url.protocol === 'http:' && isLoopbackHost(url.hostname)) - ) -} - function configuredOAuthTarget(): { issuer: string; resource: string } { const configuredBaseUrl = process.env[OAUTH_BASE_URL_ENV] || diff --git a/lib/oauth.mts b/lib/oauth.mts index c3beabf73..9a9449060 100644 --- a/lib/oauth.mts +++ b/lib/oauth.mts @@ -15,6 +15,7 @@ import { errorMessage } from '@socketsecurity/lib/errors/message' import { httpRequest } from '@socketsecurity/lib/http-request/request' import type { IncomingMessage, ServerResponse } from 'node:http' +import { reportServerError } from './error-reporting.mts' import { assertSafeHttpUrl, getRequestHeaderValue, @@ -126,6 +127,7 @@ export async function authenticateRequest( authInfo = await verifyAccessToken(token, resourceIdentifier, options) } catch (e) { logger.error(`Token verification failed: ${errorMessage(e)}`) + reportServerError(e, { source: 'oauth_verify' }) writeJson(res, 500, { error: 'server_error', error_description: 'Token verification failed', diff --git a/lib/server.mts b/lib/server.mts index 01f18eb78..f4e8d44fb 100644 --- a/lib/server.mts +++ b/lib/server.mts @@ -1,7 +1,7 @@ import crypto from 'node:crypto' import { writeSync } from 'node:fs' -import { Server } from '@modelcontextprotocol/server' +import { CLIENT_INFO_META_KEY, Server } from '@modelcontextprotocol/server' import type { McpRequestContext, ServerContext, @@ -9,6 +9,7 @@ import type { import { isPlainObject } from '@socketsecurity/lib-stable/objects/predicates' import { getSocketApiUrl } from './env.mts' +import { reportToolCall } from './error-reporting.mts' import { buildToolAuditEvent } from './tool-audit-event.mts' import type { ToolAuditEventV1, @@ -195,6 +196,9 @@ export function createConfiguredServer( let outcome: ToolAuditOutcome = 'failure' let inputValidated = false let auditSnapshot: ToolAuditEventV1 | undefined + let handlerResult: object | undefined + let threw = false + let thrownError: unknown try { const spec = specsByName.get(name) const handler = handlers.get(name) @@ -234,8 +238,13 @@ export function createConfiguredServer( { inputValidated, requestId }, ) const result = await handler(args, toToolHandlerExtra(ctx, userAgent)) + handlerResult = result outcome = classifyToolOutcome(result) return result + } catch (error) { + threw = true + thrownError = error + throw error } finally { try { const snapshot = @@ -272,6 +281,20 @@ export function createConfiguredServer( } catch { reportToolAuditFailure('mcp audit event construction failed\n') } + // A no-op unless HTTP-mode error reporting is on. It reads the outcome + // and identity computed above rather than deriving its own. + reportToolCall({ + clientInfo: readEnvelopeClientInfo(ctx), + error: thrownError, + identity, + outcome, + result: handlerResult, + threw, + tool: specsByName.has(name) ? name : 'unknown', + transport, + userAgent: + requestContext?.requestInfo?.headers.get('user-agent') ?? undefined, + }) } }) @@ -345,6 +368,17 @@ export function isToolInputSchema(value: unknown): value is ToolInputSchema { return true } +// The `clientInfo` a 2026-07-28 request carries in its `_meta` envelope. A +// 2025-era request has no envelope: on the stateless legacy leg `initialize` +// is its own exchange, so the per-request `Server` never sees the client's +// name and this answers undefined. +export function readEnvelopeClientInfo(ctx: ServerContext): unknown { + const envelope: unknown = ctx.mcpReq.envelope + return typeof envelope === 'object' && envelope !== null + ? Reflect.get(envelope, CLIENT_INFO_META_KEY) + : undefined +} + // Resolve the access token a PUBLIC-data tool (depscore) should use: the // per-request token takes precedence, then the boot-time static key. Falling // back to a shared deploy key is fine here because package scores are not diff --git a/lib/tool-depscore.mts b/lib/tool-depscore.mts index 755a4c018..87c407c8b 100644 --- a/lib/tool-depscore.mts +++ b/lib/tool-depscore.mts @@ -11,7 +11,11 @@ import { getSocketApiUrl } from './env.mts' import { buildSocketHeaders } from './http.mts' import { logger } from './logger.mts' import { buildPurl } from './purl.mts' -import { markToolOutcome } from './tool-outcome.mts' +import { + markToolOutcome, + markUpstreamHttpOutcome, + UpstreamHttpError, +} from './tool-outcome.mts' import { AUTH_REQUIRED_MSG, errorResult, resolveAuthToken } from './server.mts' import type { ToolErrorResult, ToolOkResult } from './server.mts' import { buildSocketReportUrl } from './socket-url.mts' @@ -343,9 +347,12 @@ export async function handleDepscoreRequest( headers: buildSocketHeaders(accessToken, userAgent), body: JSON.stringify({ components }), }) - } catch { + } catch (e) { logger.error({ tool: 'depscore' }, 'upstream request failed') - return errorResult('Error connecting to Socket API') + return markUpstreamHttpOutcome( + errorResult('Error connecting to Socket API'), + e, + ) } const responseText = response.text() @@ -353,13 +360,19 @@ export async function handleDepscoreRequest( if (response.status === 401) { const errorMsg = `Socket authentication failed [401]. Re-authenticate and retry. ${responseText}` logger.error({ tool: 'depscore', status: 401 }, 'upstream request denied') - return markToolOutcome(errorResult(errorMsg), 'denied') + return markUpstreamHttpOutcome( + errorResult(errorMsg), + new UpstreamHttpError(401, 'depscore endpoint 401'), + ) } if (response.status === 403) { const errorMsg = `Socket denied access [403]. Re-authenticate with the correct organization or repository permissions and retry. ${responseText}` logger.error({ tool: 'depscore', status: 403 }, 'upstream request denied') - return markToolOutcome(errorResult(errorMsg), 'denied') + return markUpstreamHttpOutcome( + errorResult(errorMsg), + new UpstreamHttpError(403, 'depscore endpoint 403'), + ) } if (response.status !== 200) { @@ -368,7 +381,13 @@ export async function handleDepscoreRequest( { tool: 'depscore', status: response.status }, 'upstream request failed', ) - return errorResult(errorMsg) + return markUpstreamHttpOutcome( + errorResult(errorMsg), + new UpstreamHttpError( + response.status, + `depscore endpoint ${response.status}`, + ), + ) } if (!responseText.trim()) { @@ -392,7 +411,14 @@ export async function handleDepscoreRequest( : parseSinglePackageBody(responseText, alertMetadata) if (!Array.isArray(parseResult)) { - return errorResult(parseResult.error) + // Only control frames (every purl unresolved) is the caller's outcome; + // unparseable lines are a response this server could not handle. + return parseResult.malformed + ? markUpstreamHttpOutcome( + errorResult(parseResult.error), + new Error('depscore response had no parseable documents'), + ) + : errorResult(parseResult.error) } // Both parsers yield at least one line for a body that reached here: @@ -406,9 +432,12 @@ export async function handleDepscoreRequest( }, ], } - } catch { + } catch (e) { logger.error({ tool: 'depscore' }, 'response parse failed') - return errorResult('Error parsing response from Socket API') + return markUpstreamHttpOutcome( + errorResult('Error parsing response from Socket API'), + e, + ) } } @@ -419,11 +448,12 @@ export function parseNdjsonPackageBody( responseText: string, platform: string | undefined, alertMetadata?: ReadonlyMap, -): string[] | { error: string } { +): string[] | { error: string; malformed: boolean } { // Parse line-by-line so one malformed line doesn't discard the whole // batch — NDJSON is line-oriented, and a truncated/garbage line is skipped // (logged) rather than thrown. const jsonLines: Array> = [] + let malformed = false const lines = responseText.split(/\r?\n/) for (let i = 0, { length } = lines; i < length; i += 1) { const line = lines[i]!.trim() @@ -436,6 +466,7 @@ export function parseNdjsonPackageBody( obj = JSON.parse(line) as Record } catch { logger.error({ tool: 'depscore' }, 'skipping malformed NDJSON line') + malformed = true continue } if (!obj['_type']) { @@ -444,7 +475,10 @@ export function parseNdjsonPackageBody( } if (!jsonLines.length) { - return { error: 'No valid JSON objects found in NDJSON response' } + return { + error: 'No valid JSON objects found in NDJSON response', + malformed, + } } const deduplicated = deduplicateArtifacts(jsonLines, platform) diff --git a/lib/tool-outcome.mts b/lib/tool-outcome.mts index 0281ed65c..3f97d623a 100644 --- a/lib/tool-outcome.mts +++ b/lib/tool-outcome.mts @@ -1,5 +1,24 @@ export type ToolOutcome = 'success' | 'failure' | 'denied' | 'invalid' +// Why an upstream call behind a tool result went wrong. `upstream_denied` and +// `upstream_4xx` are answers about the caller's request; the rest are +// failures on the server side of the call. +export type ToolFailureCause = + | 'exception' + | 'network' + | 'timeout' + | 'upstream_4xx' + | 'upstream_5xx' + | 'upstream_denied' + +export interface ToolFailure { + readonly cause: ToolFailureCause + // The error the tool caught. Error reporting reads its stack and type, and + // never its message. + readonly error: unknown + readonly status?: number | undefined +} + export interface ToolResultOutcomeInput { content?: readonly unknown[] | undefined isError?: boolean | undefined @@ -16,6 +35,39 @@ export class UpstreamHttpError extends Error { } const exceptionalOutcomes = new WeakMap() +const toolFailures = new WeakMap() + +// Node and undici error codes for a connection that failed before an HTTP +// status came back. +const NETWORK_ERROR_CODES: ReadonlySet = new Set([ + 'CERT_HAS_EXPIRED', + 'DEPTH_ZERO_SELF_SIGNED_CERT', + 'EAI_AGAIN', + 'ECONNABORTED', + 'ECONNREFUSED', + 'ECONNRESET', + 'EHOSTUNREACH', + 'ENETDOWN', + 'ENETUNREACH', + 'ENOTFOUND', + 'EPIPE', + 'EPROTO', + 'ERR_TLS_CERT_ALTNAME_INVALID', + 'SELF_SIGNED_CERT_IN_CHAIN', + 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', + 'UND_ERR_SOCKET', +]) + +const TIMEOUT_ERROR_CODES: ReadonlySet = new Set([ + 'ESOCKETTIMEDOUT', + 'ETIMEDOUT', + 'UND_ERR_CONNECT_TIMEOUT', + 'UND_ERR_HEADERS_TIMEOUT', +]) + +export function classifyToolFailure(result: object): ToolFailure | undefined { + return toolFailures.get(result) +} export function classifyToolOutcome( result: ToolResultOutcomeInput, @@ -27,6 +79,34 @@ export function classifyToolOutcome( return result.isError === true ? 'failure' : 'success' } +export function classifyUpstreamFailure(error: unknown): ToolFailureCause { + if (error instanceof UpstreamHttpError) { + if (error.status === 401 || error.status === 403) { + return 'upstream_denied' + } + return error.status >= 500 ? 'upstream_5xx' : 'upstream_4xx' + } + // The shared HTTP client rejects a timeout with a plain Error that has no + // code, so its message is the only marker. Callers that wrap an error keep + // the original as `cause`, so walk a few links of the chain. + let current: unknown = error + for (let depth = 0; depth < 5 && current instanceof Error; depth += 1) { + const code = errorCode(current) + if ( + (code !== undefined && TIMEOUT_ERROR_CODES.has(code)) || + current.name === 'TimeoutError' || + /\btimed out\b/iu.test(current.message) + ) { + return 'timeout' + } + if (code !== undefined && NETWORK_ERROR_CODES.has(code)) { + return 'network' + } + current = current.cause + } + return 'exception' +} + export function classifyUpstreamHttpError( error: unknown, ): 'denied' | 'failure' { @@ -36,6 +116,19 @@ export function classifyUpstreamHttpError( : 'failure' } +// The first string `code` on an error or its causes, e.g. `ECONNREFUSED`. +export function errorCode(error: unknown): string | undefined { + let current: unknown = error + for (let depth = 0; depth < 5 && current instanceof Error; depth += 1) { + const code: unknown = Reflect.get(current, 'code') + if (typeof code === 'string' && code) { + return code + } + current = current.cause + } + return undefined +} + export function markToolOutcome( result: Result, outcome: 'denied' | 'invalid', @@ -44,10 +137,17 @@ export function markToolOutcome( return result } +// Record why an upstream call failed. A 401 or 403 also marks the result +// denied, which is what the audit outcome reads. export function markUpstreamHttpOutcome( result: Result, error: unknown, ): Result { + toolFailures.set(result, { + cause: classifyUpstreamFailure(error), + error, + ...(error instanceof UpstreamHttpError ? { status: error.status } : {}), + }) if (classifyUpstreamHttpError(error) === 'denied') { return markToolOutcome(result, 'denied') } diff --git a/package.json b/package.json index 8b8d6fbf8..a4c44e90f 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "@modelcontextprotocol/core": "catalog:", "@modelcontextprotocol/node": "catalog:", "@modelcontextprotocol/server": "catalog:", + "@sentry/core": "catalog:", "@sinclair/typebox": "catalog:", "@socketregistry/packageurl-js": "catalog:", "@socketregistry/packageurl-js-stable": "catalog:", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5583ad304..ab0b97c7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -179,6 +179,9 @@ catalogs: '@modelcontextprotocol/server': specifier: 2.0.0 version: 2.0.0 + '@sentry/core': + specifier: 11.13.0 + version: 11.13.0 '@socketregistry/packageurl-js-stable': specifier: npm:@socketregistry/packageurl-js@1.7.0 version: 1.7.0 @@ -328,6 +331,9 @@ importers: '@modelcontextprotocol/server': specifier: 'catalog:' version: 2.0.0 + '@sentry/core': + specifier: 'catalog:' + version: 11.13.0 '@sinclair/typebox': specifier: 0.34.52 version: 0.34.52 @@ -915,6 +921,14 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@sentry/conventions@0.33.0': + resolution: {integrity: sha512-5aa3g/VOnMoL8yHbfkYIWBYC3BLgMudgRNBTKNMrcMEj1mE9aKIt/CYCG7sasijhiSU4nTcSEzyM2voIVzLCng==} + engines: {node: '>=14'} + + '@sentry/core@11.13.0': + resolution: {integrity: sha512-dRJI8RwAZvtEtW62awlZdSt8EN6fuyb3cTED78A/IgIkhNcAhhR41x+B2GuMOOJ5lrb/dOCuWLBhZwwyHW2/pg==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + '@sinclair/typebox@0.34.52': resolution: {integrity: sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==} @@ -2233,6 +2247,12 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@sentry/conventions@0.33.0': {} + + '@sentry/core@11.13.0': + dependencies: + '@sentry/conventions': 0.33.0 + '@sinclair/typebox@0.34.52': {} '@socketregistry/packageurl-js@1.7.0': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index e95f87771..5b15994b7 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -19,6 +19,7 @@ catalog: "@modelcontextprotocol/node": 2.0.0 "@modelcontextprotocol/server": 2.0.0 "@mdn/browser-compat-data": 8.1.6 + "@sentry/core": 11.13.0 "@ultrathink/acorn.rs.wasm": 0.2.0 ata-validator: 1.56.0 "@sinclair/typebox": 0.34.52 diff --git a/test/e2e/sentry.test.mts b/test/e2e/sentry.test.mts new file mode 100644 index 000000000..7ac9f9b54 --- /dev/null +++ b/test/e2e/sentry.test.mts @@ -0,0 +1,301 @@ +/** + * @file Error reporting end to end against the built bin. A local fake Socket + * API answers every request with a 500, and a local recorder stands in for + * Sentry's envelope endpoint. The HTTP server started with a DSN must send + * one scrubbed event for a failing tool call and still stop promptly on + * SIGTERM; started without a DSN, or in stdio mode with one, it must send + * nothing. No real network is reached. + */ + +import { spawn } from 'node:child_process' +import type { ChildProcess } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { createServer } from 'node:http' +import type { IncomingMessage, Server, ServerResponse } from 'node:http' +import { tmpdir } from 'node:os' +import path from 'node:path' +import process from 'node:process' + +import { Client } from '@modelcontextprotocol/client' +import { StdioClientTransport } from '@modelcontextprotocol/client/stdio' +import { afterAll, beforeAll, describe, expect, test } from 'vitest' + +import { tokenIdentity } from '../../lib/tool-audit.mts' +import { SERVER_BIN } from '../../scripts/paths.mts' + +const CALLER_TOKEN = 'synthetic_e2e_caller_token' +const DEPLOY_TOKEN = 'synthetic_e2e_deploy_token' +const ORG_SLUG = 'synthetic-e2e-secret-org' +const BODY_CANARY = 'synthetic_e2e_upstream_body' +const NETWORK_FIXTURE = new URL('./fixture/network.mts', import.meta.url).href + +interface RunningServer { + child: ChildProcess + endpoint: string + output: () => string +} + +let fakeApi: Server +let recorder: Server +let apiBaseUrl = '' +let dsn = '' +let auditDirectory = '' +const envelopes: string[] = [] + +function listen(server: Server): Promise { + return new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + resolve( + typeof address === 'object' && address !== null ? address.port : 0, + ) + }) + }) +} + +function close(server: Server): Promise { + server.closeAllConnections() + return new Promise(resolve => server.close(() => resolve())) +} + +function serveFailingApi(request: IncomingMessage, response: ServerResponse) { + request.resume() + response.writeHead(500, { 'content-type': 'text/plain' }) + response.end(`${BODY_CANARY} ${request.url}`) +} + +function recordEnvelope(request: IncomingMessage, response: ServerResponse) { + let body = '' + request.setEncoding('utf8') + request.on('data', chunk => { + body += chunk + }) + request.on('end', () => { + envelopes.push(body) + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{}') + }) +} + +function serverEnv(extra: Record): NodeJS.ProcessEnv { + return { + PATH: process.env['PATH'] ?? '', + SOCKET_API_BASE_URL: apiBaseUrl, + SOCKET_API_TOKEN: DEPLOY_TOKEN, + SOCKET_MCP_AUDIT_LOG: path.join(auditDirectory, 'audit.jsonl'), + ...extra, + } +} + +// Start the built bin in HTTP mode and wait for its listening banner. +async function startHttpServer( + extra: Record, +): Promise { + const child = spawn( + process.execPath, + ['--import', NETWORK_FIXTURE, SERVER_BIN], + { + env: serverEnv({ MCP_HTTP_MODE: 'true', MCP_PORT: '0', ...extra }), + stdio: ['ignore', 'pipe', 'pipe'], + }, + ) + let output = '' + const port = await new Promise((resolve, reject) => { + const onData = (chunk: Buffer) => { + output += chunk.toString() + const match = /started successfully on port (\d+)/u.exec(output) + if (match) { + resolve(Number(match[1])) + } + } + child.stdout!.on('data', onData) + child.stderr!.on('data', onData) + child.once('exit', code => { + reject(new Error(`server exited early (${code}): ${output}`)) + }) + }) + return { + child, + endpoint: `http://127.0.0.1:${port}/`, + output: () => output, + } +} + +function stop(server: RunningServer): Promise { + return new Promise(resolve => { + if (server.child.exitCode !== null || server.child.signalCode !== null) { + resolve(server.child.signalCode) + return + } + server.child.once('exit', (_code, signal) => resolve(signal)) + server.child.kill('SIGTERM') + }) +} + +async function callFailingAlerts(endpoint: string): Promise { + const response = await fetch(endpoint, { + method: 'POST', + headers: { + accept: 'application/json, text/event-stream', + authorization: `Bearer ${CALLER_TOKEN}`, + 'content-type': 'application/json', + 'mcp-method': 'tools/call', + 'mcp-name': 'alerts', + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: 'alerts', + arguments: { org_slug: ORG_SLUG, per_page: 5 }, + _meta: { + 'io.modelcontextprotocol/clientCapabilities': {}, + 'io.modelcontextprotocol/clientInfo': { + name: 'e2e-client', + version: '9.9.9', + }, + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + }, + }, + }), + }) + expect(response.status).toBe(200) + return await response.text() +} + +async function waitForEnvelopes(count: number): Promise { + const deadline = Date.now() + 5000 + while (envelopes.length < count && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 50)) + } +} + +function eventPayloads(): Array> { + return envelopes.flatMap(envelope => { + const lines = envelope.split('\n').filter(Boolean) + const events: Array> = [] + for (let i = 1; i + 1 < lines.length; i += 2) { + if (lines[i]!.includes('"type":"event"')) { + events.push(JSON.parse(lines[i + 1]!)) + } + } + return events + }) +} + +beforeAll(async () => { + auditDirectory = mkdtempSync(path.join(tmpdir(), 'mcp-sentry-e2e-')) + fakeApi = createServer(serveFailingApi) + recorder = createServer(recordEnvelope) + apiBaseUrl = `http://127.0.0.1:${await listen(fakeApi)}` + dsn = `http://public@127.0.0.1:${await listen(recorder)}/1` +}) + +afterAll(async () => { + await close(fakeApi) + await close(recorder) + rmSync(auditDirectory, { recursive: true, force: true }) +}) + +describe('HTTP server with SOCKET_MCP_SENTRY_DSN', () => { + test('sends one scrubbed event for an upstream 500 and stops on SIGTERM', async () => { + envelopes.length = 0 + const server = await startHttpServer({ + SOCKET_MCP_SENTRY_DSN: dsn, + SOCKET_MCP_SENTRY_ENVIRONMENT: 'e2e', + }) + try { + expect(server.output()).toContain( + 'Error reporting to Sentry is on (environment e2e)', + ) + expect(await callFailingAlerts(server.endpoint)).toContain( + '"isError":true', + ) + await waitForEnvelopes(1) + } finally { + // SIGTERM runs the shutdown flush, then the default signal action. + const started = Date.now() + expect(await stop(server)).toBe('SIGTERM') + expect(Date.now() - started).toBeLessThan(3000) + } + + const events = eventPayloads() + expect(events).toHaveLength(1) + const event = events[0]! + expect(event['environment']).toBe('e2e') + expect(event['tags']).toEqual({ + 'auth.outcome': 'bearer_ok', + 'failure.cause': 'upstream_5xx', + 'mcp.client': 'e2e-client', + 'mcp.client_version': '9.9.9', + 'mcp.tool': 'alerts', + 'tool.outcome': 'failure', + transport: 'http', + 'upstream.status': '500', + }) + + const serialized = envelopes.join('\n') + for (const leak of [ + CALLER_TOKEN, + tokenIdentity(CALLER_TOKEN), + DEPLOY_TOKEN, + ORG_SLUG, + BODY_CANARY, + 'per_page', + apiBaseUrl, + SERVER_BIN, + ]) { + expect(serialized).not.toContain(leak) + } + }) +}) + +describe('without error reporting', () => { + test('an HTTP server without a DSN sends nothing', async () => { + envelopes.length = 0 + const server = await startHttpServer({}) + try { + expect(server.output()).not.toContain('Error reporting') + expect(await callFailingAlerts(server.endpoint)).toContain( + '"isError":true', + ) + await new Promise(resolve => setTimeout(resolve, 500)) + } finally { + await stop(server) + } + expect(envelopes).toEqual([]) + }) + + test('a stdio server ignores the DSN and sends nothing', async () => { + envelopes.length = 0 + const client = new Client( + { name: 'e2e-stdio-client', version: '1.0.0' }, + { capabilities: {} }, + ) + const transport = new StdioClientTransport({ + command: process.execPath, + args: ['--import', NETWORK_FIXTURE, SERVER_BIN], + env: serverEnv({ SOCKET_MCP_SENTRY_DSN: dsn }) as Record, + stderr: 'pipe', + }) + let stderr = '' + transport.stderr?.on('data', chunk => { + stderr += String(chunk) + }) + await client.connect(transport) + try { + const result = await client.callTool({ + name: 'alerts', + arguments: { org_slug: ORG_SLUG }, + }) + expect(result.isError).toBe(true) + await new Promise(resolve => setTimeout(resolve, 500)) + } finally { + await client.close().catch(() => {}) + } + expect(stderr).not.toContain('Error reporting') + expect(envelopes).toEqual([]) + }) +}) diff --git a/test/repo/integration/error-reporting.test.mts b/test/repo/integration/error-reporting.test.mts new file mode 100644 index 000000000..31e8baf80 --- /dev/null +++ b/test/repo/integration/error-reporting.test.mts @@ -0,0 +1,557 @@ +/** + * @file Error reporting through the real HTTP stack. A `node:http` server is + * wired exactly as `startHttpServer` wires one (both `onerror` sinks and the + * route-failure fallback), the Socket API is faked with nock, and Sentry + * sends into a recording transport. Each case asserts which calls produce + * exactly one event, with which tags, and that nothing from the caller's + * token, arguments or the upstream response reaches the envelope. + */ + +import { mkdtempSync, rmSync } from 'node:fs' +import { createServer } from 'node:http' +import type { IncomingMessage, Server } from 'node:http' +import { homedir, tmpdir } from 'node:os' +import path from 'node:path' +import process from 'node:process' + +import { toNodeHandler } from '@modelcontextprotocol/node' +import { createMcpHandler } from '@modelcontextprotocol/server' +import { createTransport } from '@sentry/core' +import type { BaseTransportOptions, Transport } from '@sentry/core' +import nock from 'nock' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' + +import { + closeErrorReporting, + flushErrorReporting, + initErrorReporting, + reportServerError, +} from '../../../lib/error-reporting.mts' +import { + createRouteFailureHandler, + handleMcpAdapterError, + handleMcpHandlerError, + routeRequest, +} from '../../../lib/http-server.mts' +import { logger } from '../../../lib/logger.mts' +import type { AuthenticatedRequest } from '../../../lib/oauth.mts' +import { + createConfiguredServer, + setStaticApiKey, +} from '../../../lib/server.mts' +import { tokenIdentity } from '../../../lib/tool-audit.mts' +import { VERSION } from '../../../lib/version.mts' +import { makeRes } from '../unit/http-server-fixtures.mts' + +const SOCKET_API = 'https://api.socket.dev' +const TEST_DSN = 'http://public@127.0.0.1:9/1' +const CALLER_TOKEN = 'synthetic_caller_bearer_token' +const DEPLOY_TOKEN = 'synthetic_shared_deploy_token' +const ORG_SLUG = 'synthetic-secret-org' +const PACKAGE_NAME = 'synthetic-secret-package' +const BODY_CANARY = 'synthetic_upstream_body_canary' +const MODERN_META = { + 'io.modelcontextprotocol/clientCapabilities': {}, + 'io.modelcontextprotocol/clientInfo': { + name: 'Synthetic Client', + version: '3.2.1', + }, + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', +} +const ORIGINAL_AUDIT_PATH = process.env['SOCKET_MCP_AUDIT_LOG'] +const ORIGINAL_AUDIT_SINK = process.env['SOCKET_MCP_AUDIT_SINK'] + +interface SentryEvent { + breadcrumbs?: Array<{ data?: Record; message?: string }> + exception?: { values?: Array<{ type?: string; value?: string }> } + fingerprint?: string[] + release?: string + tags?: Record +} + +let envelopes: string[] = [] +let httpServer: Server +let endpoint = '' +let auditTempDirectory = '' + +function recordingTransport(options: BaseTransportOptions): Transport { + return createTransport(options, request => { + envelopes.push( + typeof request.body === 'string' + ? request.body + : new TextDecoder().decode(request.body), + ) + return Promise.resolve({ statusCode: 200 }) + }) +} + +// Every event payload recorded so far, after the queue drains. +async function recordedEvents(): Promise { + await flushErrorReporting(2000) + const events: SentryEvent[] = [] + for (const envelope of envelopes) { + const lines = envelope.split('\n').filter(Boolean) + for (let i = 1; i + 1 < lines.length; i += 2) { + const header: unknown = JSON.parse(lines[i]!) + if ( + typeof header === 'object' && + header !== null && + Reflect.get(header, 'type') === 'event' + ) { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- envelope payloads are untyped JSON; the cases assert on the fields they read. + events.push(JSON.parse(lines[i + 1]!) as SentryEvent) + } + } + } + return events +} + +async function postToolCall( + name: string, + args: Record, + headers?: Record | undefined, +): Promise { + return await fetch(endpoint, { + method: 'POST', + headers: { + accept: 'application/json, text/event-stream', + 'content-type': 'application/json', + 'mcp-method': 'tools/call', + 'mcp-name': name, + ...headers, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name, arguments: args, _meta: MODERN_META }, + }), + }) +} + +const bearer = { authorization: `Bearer ${CALLER_TOKEN}` } + +// A socket-level failure as Node raises it. nock needs an Error instance: a +// plain object never reaches the request's error handler, so the call would +// hang until its timeout. +function socketError(code: string): Error { + return Object.assign(new Error(`connect ${code} ${ORG_SLUG}`), { code }) +} + +beforeEach(async () => { + envelopes = [] + auditTempDirectory = mkdtempSync(path.join(tmpdir(), 'mcp-error-reporting-')) + process.env['SOCKET_MCP_AUDIT_LOG'] = path.join( + auditTempDirectory, + 'audit.jsonl', + ) + process.env['SOCKET_MCP_AUDIT_SINK'] = 'jsonl' + nock.disableNetConnect() + nock.enableNetConnect(/^127\.0\.0\.1(?::\d+)?$/u) + setStaticApiKey(DEPLOY_TOKEN, { shared: true }) + vi.spyOn(logger, 'error').mockImplementation(() => logger) + vi.spyOn(logger, 'warn').mockImplementation(() => logger) + await expect( + initErrorReporting({ + dsn: TEST_DSN, + mode: 'http', + makeTransport: recordingTransport, + }), + ).resolves.toBe(true) + + // Wired as startHttpServer wires it. + const mcpHandler = toNodeHandler( + createMcpHandler(context => createConfiguredServer(context, 'http'), { + onerror: handleMcpHandlerError, + }), + { onerror: handleMcpAdapterError }, + ) + let port = 0 + httpServer = createServer((req, res) => { + routeRequest(mcpHandler, req, res, port).catch( + createRouteFailureHandler(res, req), + ) + }) + await new Promise(resolve => { + httpServer.listen(0, '127.0.0.1', resolve) + }) + const address = httpServer.address() + port = typeof address === 'object' && address !== null ? address.port : 0 + endpoint = `http://127.0.0.1:${port}/` +}) + +afterEach(async () => { + await closeErrorReporting() + vi.restoreAllMocks() + nock.cleanAll() + nock.enableNetConnect() + setStaticApiKey('') + httpServer.closeAllConnections() + await new Promise(resolve => { + httpServer.close(() => resolve()) + }) + if (ORIGINAL_AUDIT_PATH === undefined) { + delete process.env['SOCKET_MCP_AUDIT_LOG'] + } else { + process.env['SOCKET_MCP_AUDIT_LOG'] = ORIGINAL_AUDIT_PATH + } + if (ORIGINAL_AUDIT_SINK === undefined) { + delete process.env['SOCKET_MCP_AUDIT_SINK'] + } else { + process.env['SOCKET_MCP_AUDIT_SINK'] = ORIGINAL_AUDIT_SINK + } + rmSync(auditTempDirectory, { recursive: true, force: true }) +}) + +describe('tool calls that fail on the server side', () => { + test('a throwing handler sends one event tagged with tool, client and auth', async () => { + // depscore's first statement logs the request; make that dependency throw + // so the handler itself throws. + vi.spyOn(logger, 'info').mockImplementation((...args: unknown[]) => { + if (args[1] === 'request received') { + throw new TypeError(`synthetic handler bug near ${PACKAGE_NAME}`) + } + return logger + }) + const res = await postToolCall( + 'depscore', + { packages: [{ depname: PACKAGE_NAME, ecosystem: 'npm' }] }, + bearer, + ) + expect(res.status).toBe(200) + await res.text() + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toEqual({ + 'auth.outcome': 'bearer_ok', + 'failure.cause': 'thrown', + 'mcp.client': 'synthetic-client', + 'mcp.client_version': '3.2.1', + 'mcp.tool': 'depscore', + 'tool.outcome': 'failure', + transport: 'http', + }) + expect(events[0]!.fingerprint).toEqual([ + 'socket-mcp', + 'tool', + 'depscore', + 'failure', + 'bearer_ok', + 'thrown', + ]) + expect(events[0]!.release).toBe(VERSION) + expect(events[0]!.exception?.values?.at(-1)).toMatchObject({ + type: 'TypeError', + value: 'depscore thrown', + }) + expect(envelopes.join('\n')).not.toContain(PACKAGE_NAME) + }) + + test('an upstream 5xx sends one event and leaks nothing from the call', async () => { + const api = nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(502, `${BODY_CANARY} for ${ORG_SLUG}`) + const res = await postToolCall( + 'alerts', + { org_slug: ORG_SLUG, per_page: 7, cursor: 'synthetic-cursor-canary' }, + { ...bearer, cookie: 'session=synthetic-cookie-canary' }, + ) + expect(res.status).toBe(200) + expect(await res.text()).toContain('"isError":true') + expect(api.isDone()).toBe(true) + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'auth.outcome': 'bearer_ok', + 'failure.cause': 'upstream_5xx', + 'mcp.tool': 'alerts', + 'tool.outcome': 'failure', + 'upstream.status': '502', + }) + expect(events[0]!.exception?.values?.at(-1)).toMatchObject({ + type: 'UpstreamHttpError', + value: 'alerts upstream_5xx 502', + }) + + const serialized = envelopes.join('\n') + for (const leak of [ + CALLER_TOKEN, + tokenIdentity(CALLER_TOKEN), + DEPLOY_TOKEN, + ORG_SLUG, + BODY_CANARY, + 'synthetic-cursor-canary', + 'synthetic-cookie-canary', + 'per_page', + 'startAfterCursor', + 'Bearer', + 'authorization', + 'mcp-session-id', + homedir(), + ]) { + expect(serialized).not.toContain(leak) + } + }) + + test('a refused connection is tagged as a network failure', async () => { + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .replyWithError(socketError('ECONNREFUSED')) + const res = await postToolCall('alerts', { org_slug: ORG_SLUG }, bearer) + await res.text() + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'error.code': 'ECONNREFUSED', + 'failure.cause': 'network', + 'mcp.tool': 'alerts', + }) + }) + + test('a timed-out request is tagged as a timeout', async () => { + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .replyWithError(socketError('ETIMEDOUT')) + const res = await postToolCall('alerts', { org_slug: ORG_SLUG }, bearer) + await res.text() + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'error.code': 'ETIMEDOUT', + 'failure.cause': 'timeout', + }) + }) + + test('a rejected deploy token on an anonymous call is reported', async () => { + nock(SOCKET_API).post('/v0/purl').query(true).reply(401, BODY_CANARY) + const res = await postToolCall('depscore', { + packages: [{ depname: PACKAGE_NAME, ecosystem: 'npm', version: '1.0.0' }], + }) + await res.text() + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'auth.outcome': 'operator_denied', + 'failure.cause': 'upstream_denied', + 'mcp.tool': 'depscore', + 'tool.outcome': 'denied', + 'upstream.status': '401', + }) + expect(envelopes.join('\n')).not.toContain(DEPLOY_TOKEN) + }) + + test('a 2025-era call without clientInfo is named by its User-Agent', async () => { + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(503, BODY_CANARY) + const res = await fetch(endpoint, { + method: 'POST', + headers: { + accept: 'application/json, text/event-stream', + 'content-type': 'application/json', + 'user-agent': 'Synthetic-Legacy-Agent/4.5.6 (synthetic; os)', + ...bearer, + }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { name: 'alerts', arguments: { org_slug: ORG_SLUG } }, + }), + }) + expect(res.status).toBe(200) + await res.text() + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'failure.cause': 'upstream_5xx', + 'mcp.client': 'synthetic-legacy-agent', + 'mcp.client_version': '4.5.6', + }) + }) +}) + +describe('tool calls the caller got wrong', () => { + test('invalid, unknown, denied and 4xx calls leave breadcrumbs, not events', async () => { + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(401, BODY_CANARY) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(404, BODY_CANARY) + const unknownTool = 'synthetic_unknown_tool_name' + for (const [name, args, headers] of [ + ['alerts', { org_slug: 42 }, bearer], + [unknownTool, {}, bearer], + ['organizations', {}, {}], + ['alerts', { org_slug: ORG_SLUG }, bearer], + ['alerts', { org_slug: ORG_SLUG }, bearer], + ] as const) { + const res = await postToolCall(name, { ...args }, { ...headers }) + expect(res.status).toBe(200) + await res.text() + } + expect(await recordedEvents()).toEqual([]) + + // The next real failure carries them as context. + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(500, BODY_CANARY) + await (await postToolCall('alerts', { org_slug: ORG_SLUG }, bearer)).text() + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.breadcrumbs?.map(crumb => crumb.data)).toEqual([ + { + 'auth.outcome': 'bearer_ok', + 'mcp.tool': 'alerts', + 'tool.outcome': 'invalid', + }, + { + 'auth.outcome': 'bearer_ok', + 'mcp.tool': 'unknown', + 'tool.outcome': 'unknown', + }, + { + 'auth.outcome': 'anonymous', + 'mcp.tool': 'organizations', + 'tool.outcome': 'denied', + }, + { + 'auth.outcome': 'bearer_denied', + 'failure.cause': 'upstream_denied', + 'mcp.tool': 'alerts', + 'tool.outcome': 'denied', + }, + { + 'auth.outcome': 'bearer_ok', + 'failure.cause': 'upstream_4xx', + 'mcp.tool': 'alerts', + 'tool.outcome': 'failure', + }, + ]) + expect(envelopes.join('\n')).not.toContain(unknownTool) + }) +}) + +describe('server errors outside tool handlers', () => { + test('a serving failure in the MCP handler sends one event', async () => { + handleMcpHandlerError(new Error(`synthetic serving failure ${ORG_SLUG}`)) + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toEqual({ + 'auth.outcome': 'unknown', + 'error.source': 'mcp_handler', + 'mcp.client': 'unknown', + 'mcp.tool': 'unknown', + transport: 'http', + }) + expect(events[0]!.fingerprint).toEqual([ + 'socket-mcp', + 'server', + 'mcp_handler', + 'Error', + ]) + expect(envelopes.join('\n')).not.toContain(ORG_SLUG) + }) + + test('a request the MCP handler rejects for the client is not reported', async () => { + const res = await fetch(endpoint, { + method: 'POST', + headers: { + accept: 'application/json, text/event-stream', + 'content-type': 'text/plain', + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), + }) + expect(res.status).toBe(415) + expect(await recordedEvents()).toEqual([]) + }) + + test('an adapter failure sends one event, a client abort none', async () => { + const abort = new Error('This operation was aborted') + abort.name = 'AbortError' + handleMcpAdapterError(abort) + expect(await recordedEvents()).toEqual([]) + + handleMcpAdapterError(new Error('synthetic adapter failure')) + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ 'error.source': 'mcp_adapter' }) + }) + + test('an unexpected routing exception sends one event with request context', async () => { + const { res } = makeRes() + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double: the handler reads only the headers and auth members. + const req = { + headers: { 'user-agent': 'Synthetic-Router-Client/1.0.0' }, + auth: { token: CALLER_TOKEN, clientId: 'socket-api-key', scopes: [] }, + } as unknown as AuthenticatedRequest & IncomingMessage + createRouteFailureHandler(res, req)(new TypeError('synthetic routing bug')) + + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'auth.outcome': 'bearer_ok', + 'error.source': 'http_route', + 'mcp.client': 'synthetic-router-client', + 'mcp.client_version': '1.0.0', + }) + expect(envelopes.join('\n')).not.toContain(CALLER_TOKEN) + }) + + test('a reset while verifying a token is an upstream failure, not a client abort', async () => { + reportServerError( + Object.assign(new Error('introspection reset'), { code: 'ECONNRESET' }), + { source: 'oauth_verify' }, + ) + const events = await recordedEvents() + expect(events).toHaveLength(1) + expect(events[0]!.tags).toMatchObject({ + 'error.code': 'ECONNRESET', + 'error.source': 'oauth_verify', + }) + }) +}) + +describe('an unreachable Sentry', () => { + test('does not break the tool call or the flush', async () => { + await closeErrorReporting() + // A port that was just released, so the connection is refused. + const closed = createServer() + await new Promise(resolve => closed.listen(0, '127.0.0.1', resolve)) + const address = closed.address() + const closedPort = + typeof address === 'object' && address !== null ? address.port : 0 + await new Promise(resolve => closed.close(() => resolve())) + await expect( + initErrorReporting({ + dsn: `http://public@127.0.0.1:${closedPort}/1`, + mode: 'http', + }), + ).resolves.toBe(true) + + nock(SOCKET_API) + .get(`/v0/orgs/${ORG_SLUG}/alerts`) + .query(true) + .reply(500, BODY_CANARY) + const res = await postToolCall('alerts', { org_slug: ORG_SLUG }, bearer) + expect(res.status).toBe(200) + expect(await res.text()).toContain('"isError":true') + + const started = Date.now() + await expect(flushErrorReporting(2000)).resolves.toBeTypeOf('boolean') + expect(Date.now() - started).toBeLessThan(2500) + }) +}) diff --git a/test/repo/unit/cli.test.mts b/test/repo/unit/cli.test.mts index 4cd192aa0..7715a74a8 100644 --- a/test/repo/unit/cli.test.mts +++ b/test/repo/unit/cli.test.mts @@ -15,10 +15,12 @@ import { runSocketMcpCli, } from '../../../lib/cli.mts' import type { SocketMcpCliDeps } from '../../../lib/cli.mts' +import type { ErrorReportingConfig } from '../../../lib/error-reporting.mts' import { logger } from '../../../lib/logger.mts' // What startup did with the deps it was handed. interface Recorded { + errorReporting: ErrorReportingConfig[] httpPorts: number[] prompted: number staticKeys: Array<{ key: string; shared: boolean | undefined }> @@ -32,6 +34,7 @@ function recordingDeps(overrides?: Partial | undefined): { recorded: Recorded } { const recorded: Recorded = { + errorReporting: [], httpPorts: [], prompted: 0, staticKeys: [], @@ -52,10 +55,16 @@ function recordingDeps(overrides?: Partial | undefined): { recorded.stdioStarts += 1 return { close: () => Promise.resolve() } }, + sentryDsn: undefined, + sentryEnvironment: undefined, setOauthEnabled: () => undefined, setStaticApiKey: (value, options) => { recorded.staticKeys.push({ key: value, shared: options?.shared }) }, + startErrorReporting: config => { + recorded.errorReporting.push(config) + return Promise.resolve() + }, startHttpServer: port => { recorded.httpPorts.push(port) }, @@ -86,6 +95,7 @@ describe('createSocketMcpCliDeps', () => { 'serveStdio', 'setOauthEnabled', 'setStaticApiKey', + 'startErrorReporting', 'startHttpServer', ] as const) { expect(typeof deps[name]).toBe('function') @@ -93,6 +103,42 @@ describe('createSocketMcpCliDeps', () => { }) }) +describe('error reporting', () => { + test('stays off in HTTP mode when no DSN is set', async () => { + const { deps, recorded } = recordingDeps({ envHttpMode: true }) + await expect(runSocketMcpCli(deps)).resolves.toBe(0) + expect(recorded.httpPorts).toEqual([3000]) + expect(recorded.errorReporting).toEqual([]) + }) + + test('starts before the HTTP server listens when a DSN is set', async () => { + const order: string[] = [] + const { deps } = recordingDeps({ + envHttpMode: true, + sentryDsn: 'https://public@sentry.invalid/1', + sentryEnvironment: 'staging', + startErrorReporting: config => { + order.push(`reporting:${config.mode}:${config.environment}`) + return Promise.resolve() + }, + startHttpServer: () => { + order.push('http') + }, + }) + await expect(runSocketMcpCli(deps)).resolves.toBe(0) + expect(order).toEqual(['reporting:http:staging', 'http']) + }) + + test('never starts in stdio mode, even with a DSN', async () => { + const { deps, recorded } = recordingDeps({ + sentryDsn: 'https://public@sentry.invalid/1', + }) + await expect(runSocketMcpCli(deps)).resolves.toBe(0) + expect(recorded.stdioStarts).toBe(1) + expect(recorded.errorReporting).toEqual([]) + }) +}) + describe('transport selection', () => { test('serves stdio by default', async () => { const { deps, recorded } = recordingDeps() diff --git a/test/repo/unit/error-reporting.test.mts b/test/repo/unit/error-reporting.test.mts new file mode 100644 index 000000000..ee1ac4aa1 --- /dev/null +++ b/test/repo/unit/error-reporting.test.mts @@ -0,0 +1,340 @@ +/** + * @file Error reporting's decisions in isolation: it stays off (and never + * loads the Sentry module) without a DSN or in stdio mode, which tool calls + * earn an event, how the bounded tags are derived, and what the event + * sanitizer lets through. The HTTP-driven cases live in + * test/repo/integration/error-reporting.test.mts. + */ + +import type { ErrorEvent } from '@sentry/core' +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { + closeErrorReporting, + errorCodeTag, + errorTypeName, + flushErrorReporting, + initErrorReporting, + isErrorReportingEnabled, + isReportableToolCall, + reportServerError, + reportToolCall, + resolveAuthOutcome, + resolveMcpClient, +} from '../../../lib/error-reporting.mts' +import { logger } from '../../../lib/logger.mts' + +// Count how often the lazily loaded Sentry module is evaluated. +const sentryModule = vi.hoisted(() => ({ loads: 0 })) +vi.mock('../../../lib/error-reporting-sentry.mts', async importOriginal => { + sentryModule.loads += 1 + return await importOriginal() +}) + +// Record every request the shared HTTP helper sends. +const httpRequests = vi.hoisted(() => ({ count: 0 })) +vi.mock('@socketsecurity/lib/http-request/request', async importOriginal => { + const actual = + await importOriginal< + typeof import('@socketsecurity/lib/http-request/request') + >() + return { + ...actual, + httpRequest: (...args: Parameters) => { + httpRequests.count += 1 + return actual.httpRequest(...args) + }, + } +}) + +afterEach(async () => { + await closeErrorReporting() + vi.restoreAllMocks() +}) + +// These run first: once a later case loads the Sentry module, the count can +// no longer show that the off path skipped it. +describe('when no DSN is set or the transport is stdio', () => { + test('does not load Sentry, send anything or report', async () => { + await expect( + initErrorReporting({ dsn: undefined, mode: 'http' }), + ).resolves.toBe(false) + await expect(initErrorReporting({ dsn: '', mode: 'http' })).resolves.toBe( + false, + ) + await expect( + initErrorReporting({ dsn: 'http://public@127.0.0.1:9/1', mode: 'stdio' }), + ).resolves.toBe(false) + expect(isErrorReportingEnabled()).toBe(false) + + reportToolCall({ + clientInfo: undefined, + error: new Error('boom'), + identity: { kind: 'anonymous' }, + outcome: 'failure', + threw: true, + tool: 'depscore', + transport: 'http', + userAgent: undefined, + }) + reportServerError(new Error('boom'), { source: 'mcp_adapter' }) + await expect(flushErrorReporting(10)).resolves.toBe(true) + + expect(sentryModule.loads).toBe(0) + expect(httpRequests.count).toBe(0) + }) +}) + +describe('initErrorReporting', () => { + test('logs and stays off when the DSN does not parse', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + for (const dsn of [ + 'not a dsn', + 'ftp://public@127.0.0.1/1', + 'http://127.0.0.1/1', + 'http://public@127.0.0.1/project', + // Cleartext HTTP is refused off loopback. + 'http://public@sentry.example.com/1', + ]) { + await expect(initErrorReporting({ dsn, mode: 'http' })).resolves.toBe( + false, + ) + } + expect(consoleError).not.toHaveBeenCalled() + expect(isErrorReportingEnabled()).toBe(false) + // A DSN is what loads the Sentry module at all. + expect(sentryModule.loads).toBe(1) + expect(warn).toHaveBeenCalledWith( + 'SOCKET_MCP_SENTRY_DSN is not a valid HTTPS Sentry DSN; error reporting is off', + ) + // The log line never echoes the DSN. + expect(JSON.stringify(warn.mock.calls)).not.toContain('not a dsn') + }) +}) + +describe('resolveMcpClient', () => { + test('prefers clientInfo and normalizes it', () => { + expect( + resolveMcpClient({ name: 'Claude Code', version: '2.1.4' }, 'curl/8'), + ).toEqual({ name: 'claude-code', version: '2.1.4' }) + }) + + test('falls back to the User-Agent product token', () => { + expect( + resolveMcpClient(undefined, 'Cursor/1.7.2 (darwin arm64) node/24'), + ).toEqual({ name: 'cursor', version: '1.7.2' }) + expect(resolveMcpClient({ name: ' ' }, 'python-httpx/0.28.1')).toEqual({ + name: 'python-httpx', + version: '0.28.1', + }) + expect(resolveMcpClient(undefined, 'node')).toEqual({ + name: 'node', + version: undefined, + }) + }) + + test('answers unknown without either', () => { + expect(resolveMcpClient(undefined, undefined)).toEqual({ name: 'unknown' }) + expect(resolveMcpClient('not an object', ' ')).toEqual({ + name: 'unknown', + }) + }) + + test('bounds the name and drops versions that do not look like one', () => { + const client = resolveMcpClient( + { name: `${'x'.repeat(200)}`, version: 'v'.repeat(80) }, + undefined, + ) + expect(client.name).toHaveLength(64) + expect(client.version).toBeUndefined() + expect( + resolveMcpClient({ name: 'ok', version: '1.0.0