From 7bfbe64f79fc2cfdb92f2fa86bdfa5148437b37a Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 15:12:31 -0300 Subject: [PATCH 1/7] feat(events): add MCP Events push stream for new Socket alerts Advertise the io.modelcontextprotocol/events extension (SEP-3415, Beta) and implement events/list and events/stream on the local stdio and HTTP servers. One event, socket.alert.created, polls the org alerts API with the caller's own token and emits each alert once per stream. The TypeScript SDK has no events API yet (typescript-sdk#3209), so both methods are custom request handlers. SOCKET_MCP_EVENTS_FAKE_ALERT=1 emits synthetic alerts without network calls for demos. --- README.md | 46 ++++ lib/events.mts | 345 ++++++++++++++++++++++++++ lib/server.mts | 3 + test/repo/integration/events.test.mts | 174 +++++++++++++ 4 files changed, 568 insertions(+) create mode 100644 lib/events.mts create mode 100644 test/repo/integration/events.test.mts diff --git a/README.md b/README.md index e9c98214..20571665 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,52 @@ See the [authentication reference](docs/service.md#authentication-for-organizati See the [organization and alerts example](docs/service.md#worked-example-organization-details-and-alerts). +### MCP Events: new-alert notifications (Beta) + +The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer one event, `socket.alert.created`, which takes `org_slug` and an optional comma-separated `severity` filter. With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. + +| Variable | Default | Purpose | +| -------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `SOCKET_MCP_EVENTS_POLL_MS` | `60000` | Poll interval, also the granted heartbeat interval | +| `SOCKET_MCP_EVENTS_FAKE_ALERT=1` | off | Demo mode: no Socket API calls and no token needed. Each poll after the baseline emits one synthetic `demo-evil-package` malware alert | + +Recipe for OpenCode 2.4.0 (demo mode): + +1. Build this checkout with `pnpm install && pnpm run build`, then add the server to `opencode.json`: + + ```json + { + "mcp": { + "socket": { + "type": "local", + "command": ["node", "/path/to/socket-mcp/dist/index.cjs"], + "environment": { + "SOCKET_MCP_EVENTS_FAKE_ALERT": "1", + "SOCKET_MCP_EVENTS_POLL_MS": "15000" + } + } + } + } + ``` + + Drop `SOCKET_MCP_EVENTS_FAKE_ALERT` to watch real alerts. The server then uses your `socket-mcp login` session or `SOCKET_API_TOKEN`. + +2. In OpenCode, run `list_mcp_events`. It shows `socket.alert.created` from the `socket` server. +3. Create the automation: + + ```js + automation_create({ + trigger: { + type: 'event', + server: 'socket', + event: 'socket.alert.created', + args: { org_slug: 'my-org', severity: 'high,critical' }, + }, + }) + ``` + +4. About one poll interval later, the automation fires with the alert in `data.alert`. In demo mode, one more fake alert arrives on each later poll. + ### Adjusting tool usage via client rules See [client rule examples](docs/service.md#adjusting-tool-usage-via-client-rules). diff --git a/lib/events.mts b/lib/events.mts new file mode 100644 index 00000000..22ffa1bb --- /dev/null +++ b/lib/events.mts @@ -0,0 +1,345 @@ +/** + * @file MCP Events (SEP-3415, `io.modelcontextprotocol/events`, Beta) for the + * local stdio and `--http` server. One event type, `socket.alert.created`, + * delivered by push only: `events/stream` polls the org alerts API with the + * caller's own token and emits each alert it has not seen before. + * The TypeScript SDK has no events support yet + * (modelcontextprotocol/typescript-sdk#3209), so the two methods are plain + * custom request handlers. Swap them for the SDK's API once it lands. + */ +import { setTimeout as sleep } from 'node:timers/promises' + +import { + ProtocolError, + SUBSCRIPTION_ID_META_KEY, +} from '@modelcontextprotocol/server' +import type { + Server, + ServerContext, + StandardSchemaV1, +} from '@modelcontextprotocol/server' +import { isPlainObject } from '@socketsecurity/lib-stable/objects/predicates' + +import { fetchAlerts } from './alerts.mts' +import { envBool, envInt } from './env.mts' +import { logger } from './logger.mts' +import { + AUTH_REQUIRED_MSG, + resolveScopedAuthToken, + SOCKET_API_BASE_URL, +} from './server.mts' +import { UpstreamHttpError } from './tool-outcome.mts' + +export const EVENTS_EXTENSION = 'io.modelcontextprotocol/events' +export const ALERT_CREATED_EVENT = 'socket.alert.created' + +// Spec error codes (SEP-3415). +const NOT_FOUND = -32_023 +const FORBIDDEN = -32_024 + +const ALERT_CREATED_DEFINITION = { + name: ALERT_CREATED_EVENT, + description: + 'A new Socket alert appeared for an organization you can access. Polls the org alerts API with your own token and fires once per new alert.', + delivery: ['push'], + inputSchema: { + type: 'object', + properties: { + org_slug: { + type: 'string', + description: 'Organization slug, e.g. "my-org"', + }, + severity: { + type: 'string', + description: + 'Comma-separated severities to include: subset of low,medium,high,critical', + }, + }, + required: ['org_slug'], + additionalProperties: false, + }, + payloadSchema: { + type: 'object', + properties: { + org_slug: { type: 'string' }, + alert: { + type: 'object', + description: 'The alert as returned by GET /v0/orgs/{org}/alerts', + }, + }, + required: ['org_slug', 'alert'], + }, +} + +export interface AlertCreatedArgs { + org_slug: string + severity?: string | undefined +} + +interface StreamParams { + name: string + arguments: AlertCreatedArgs + cursor: string | null +} + +export type Alert = Record & { id: string } + +export type AlertSource = ( + args: AlertCreatedArgs, + token: string, + userAgent: string, +) => Promise + +export interface EventsOptions { + // Poll interval for `events/stream`; also the granted heartbeat interval. + pollMs?: number | undefined + source?: AlertSource | undefined + userAgent?: string | undefined +} + +// Pass-through Standard Schema: the SDK only needs a validator object for a +// custom method, and these params are checked by hand below. +function passthrough( + parse: (value: unknown) => T, +): StandardSchemaV1 { + return { + '~standard': { + version: 1, + vendor: 'socket-mcp', + validate(value) { + try { + return { value: parse(value) } + } catch (error) { + return { issues: [{ message: (error as Error).message }] } + } + }, + }, + } +} + +export function parseStreamParams(value: unknown): StreamParams { + const params = isPlainObject(value) ? value : {} + const name = params['name'] + if (typeof name !== 'string') { + throw new Error('name must be a string') + } + const args = isPlainObject(params['arguments']) ? params['arguments'] : {} + const orgSlug = args['org_slug'] + const severity = args['severity'] + if (typeof orgSlug !== 'string' || orgSlug === '') { + throw new Error('arguments.org_slug must be a non-empty string') + } + if (severity !== undefined && typeof severity !== 'string') { + throw new Error('arguments.severity must be a string') + } + const extra = Object.keys(args).filter( + key => key !== 'org_slug' && key !== 'severity', + ) + if (extra.length > 0) { + throw new Error(`unknown arguments: ${extra.join(', ')}`) + } + const cursor = params['cursor'] + if (cursor !== undefined && cursor !== null && typeof cursor !== 'string') { + throw new Error('cursor must be a string or null') + } + return { + name, + arguments: { org_slug: orgSlug, ...(severity ? { severity } : {}) }, + cursor: cursor ?? null, + } +} + +function alertTime(alert: Alert): string | undefined { + const value = alert['createdAt'] ?? alert['created_at'] + return typeof value === 'string' ? value : undefined +} + +// Live source: open alerts for the org, newest page only. +// shortcut: reads one page of 100, so a burst of >100 alerts between polls +// drops the overflow; page through `endCursor` if that matters. +export const socketAlertSource: AlertSource = async ( + args, + token, + userAgent, +) => { + const body = await fetchAlerts({ + baseUrl: SOCKET_API_BASE_URL, + orgSlug: args.org_slug, + authToken: token, + userAgent, + filters: { + status: 'open', + perPage: 100, + ...(args.severity ? { severity: args.severity } : {}), + }, + }) + const record = isPlainObject(body) ? body : {} + const items = record['items'] ?? record['results'] ?? [] + return (Array.isArray(items) ? items : []).flatMap(item => { + if (!isPlainObject(item)) { + return [] + } + const id = item['id'] ?? item['key'] + return typeof id === 'string' || typeof id === 'number' + ? [{ ...item, id: String(id) }] + : [] + }) +} + +// Demo source (SOCKET_MCP_EVENTS_FAKE_ALERT=1): no network. The first poll is +// empty (the baseline); every later poll returns one more synthetic alert, so +// a new event fires once per poll interval. +export function fakeAlertSource(): AlertSource { + const alerts: Alert[] = [] + let polls = 0 + return async args => { + if (polls++ > 0) { + const severity = args.severity?.split(',')[0]?.trim() || 'critical' + alerts.unshift({ + id: `fake-alert-${polls - 1}`, + type: 'malware', + severity, + category: 'supplyChainRisk', + status: 'open', + createdAt: new Date().toISOString(), + artifact: { type: 'npm', name: 'demo-evil-package', version: '6.6.6' }, + description: 'Synthetic alert from SOCKET_MCP_EVENTS_FAKE_ALERT', + }) + } + return alerts + } +} + +/** + * Advertise the extension and register `events/list` and `events/stream` on + * a configured server. The capability rides on both `initialize` and + * `server/discover`, since the SDK reads both from `getCapabilities()`. + */ +export function registerEventHandlers( + server: Server, + options: EventsOptions = {}, +): void { + const pollMs = options.pollMs ?? envInt('SOCKET_MCP_EVENTS_POLL_MS') ?? 60_000 + const fake = envBool('SOCKET_MCP_EVENTS_FAKE_ALERT') + const source = + options.source ?? (fake ? fakeAlertSource() : socketAlertSource) + const userAgent = options.userAgent ?? '' + + server.registerCapabilities({ extensions: { [EVENTS_EXTENSION]: {} } }) + + server.setRequestHandler( + 'events/list', + { params: passthrough(value => value) }, + () => ({ events: [ALERT_CREATED_DEFINITION] }), + ) + + server.setRequestHandler( + 'events/stream', + { params: passthrough(parseStreamParams) }, + async (params, ctx) => { + if (params.name !== ALERT_CREATED_EVENT) { + throw new ProtocolError(NOT_FOUND, `Unknown event: ${params.name}`, { + kind: 'event', + }) + } + const token = resolveScopedAuthToken(ctx.http?.authInfo?.token) + if (!token && !fake) { + throw new ProtocolError(FORBIDDEN, AUTH_REQUIRED_MSG) + } + return streamAlerts(params, ctx, { + pollMs, + poll: () => source(params.arguments, token ?? '', userAgent), + }) + }, + ) +} + +/** + * Run one push subscription until the client cancels it. Dedup is by alert + * id within the stream; the cursor is the newest `createdAt` emitted, so a + * reconnect with it skips everything at or before that time. + */ +export async function streamAlerts( + params: StreamParams, + ctx: ServerContext, + opts: { pollMs: number; poll: () => Promise }, +): Promise<{ _meta: Record }> { + const { signal } = ctx.mcpReq + const meta = { [SUBSCRIPTION_ID_META_KEY]: ctx.mcpReq.id } + const notify = (method: string, body: Record) => + ctx.mcpReq.notify({ + method: `notifications/events/${method}`, + params: { ...body, _meta: meta }, + }) + const seen = new Set() + // With no client cursor, whatever the first poll returns is the baseline. + const resumed = params.cursor !== null + let cursor = params.cursor ?? new Date().toISOString() + let baseline = true + + const tick = async (): Promise => { + let alerts: Alert[] + try { + alerts = await opts.poll() + } catch (error) { + const status = error instanceof UpstreamHttpError ? error.status : 0 + const payload = { + error: { + code: status === 401 || status === 403 ? FORBIDDEN : -32_603, + message: 'UpstreamError', + data: { reason: (error as Error).message }, + }, + } + if (status === 401 || status === 403) { + await notify('terminated', payload) + return false + } + await notify('error', payload) + return true + } + // Oldest first, so the cursor only moves forward. + const fresh = alerts.filter(alert => !seen.has(alert.id)).reverse() + for (const alert of fresh) { + seen.add(alert.id) + const time = alertTime(alert) + // On the first poll emit only what is newer than the client's cursor. + if (baseline && (!resumed || !time || time <= cursor)) { + continue + } + if (time && time > cursor) { + cursor = time + } + await notify('event', { + eventId: `${params.arguments.org_slug}:${alert.id}`, + name: ALERT_CREATED_EVENT, + timestamp: time ?? new Date().toISOString(), + data: { org_slug: params.arguments.org_slug, alert }, + cursor, + }) + } + if (baseline) { + baseline = false + } else if (fresh.length === 0) { + await notify('heartbeat', { cursor }) + } + return true + } + + logger.info({ event: ALERT_CREATED_EVENT }, 'events stream opened') + await notify('active', { + cursor, + truncated: false, + heartbeatMs: opts.pollMs, + }) + let open = await tick() + while (open && !signal.aborted) { + try { + await sleep(opts.pollMs, undefined, { signal }) + } catch { + break + } + open = await tick() + } + logger.info({ event: ALERT_CREATED_EVENT }, 'events stream closed') + return { _meta: meta } +} diff --git a/lib/server.mts b/lib/server.mts index 07d41fbf..989d30d2 100644 --- a/lib/server.mts +++ b/lib/server.mts @@ -14,6 +14,7 @@ import { resolveMcpClient, traceToolCall, } from './error-reporting.mts' +import { registerEventHandlers } from './events.mts' import { buildToolAuditEvent } from './tool-audit-event.mts' import type { ToolAuditEventV1, @@ -184,6 +185,8 @@ export function createConfiguredServer( }, ) + registerEventHandlers(server, { userAgent }) + server.setRequestHandler('tools/list', () => ({ __proto__: null, tools: specs.map(toToolListEntry), diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts new file mode 100644 index 00000000..4d21f9fa --- /dev/null +++ b/test/repo/integration/events.test.mts @@ -0,0 +1,174 @@ +import { Client, InMemoryTransport } from '@modelcontextprotocol/client' +import type { StandardSchemaV1 } from '@modelcontextprotocol/client' +import nock from 'nock' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' + +import { ALERT_CREATED_EVENT, EVENTS_EXTENSION } from '../../../lib/events.mts' +import { + createConfiguredServer, + setStaticApiKey, +} from '../../../lib/server.mts' + +const API = 'https://api.socket.dev' + +const anything: StandardSchemaV1> = { + '~standard': { + version: 1, + vendor: 'test', + validate: value => ({ value: value as Record }), + }, +} + +interface Note { + method: string + params: Record +} + +async function connect(): Promise<{ client: Client; notes: Note[] }> { + const server = createConfiguredServer(undefined, 'stdio') + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair() + await server.connect(serverTransport) + const client = new Client( + { name: 'test', version: '0.0.0' }, + { capabilities: {} }, + ) + await client.connect(clientTransport) + const notes: Note[] = [] + for (const kind of ['active', 'event', 'heartbeat', 'error', 'terminated']) { + const method = `notifications/events/${kind}` + client.setNotificationHandler(method, { params: anything }, params => { + notes.push({ method, params }) + }) + } + return { client, notes } +} + +function openStream( + client: Client, + args: Record, + name = ALERT_CREATED_EVENT, +) { + const controller = new AbortController() + const done = client + .request( + { + method: 'events/stream', + params: { name, arguments: args, cursor: null }, + }, + anything, + { signal: controller.signal, timeout: 60_000 }, + ) + .catch((error: unknown) => error) + return { controller, done } +} + +const alert = (id: string, createdAt: string) => ({ + id, + type: 'malware', + severity: 'critical', + createdAt, +}) + +beforeEach(() => { + nock.disableNetConnect() + process.env['SOCKET_MCP_EVENTS_POLL_MS'] = '20' + setStaticApiKey('tok') +}) + +afterEach(() => { + nock.cleanAll() + nock.enableNetConnect() + delete process.env['SOCKET_MCP_EVENTS_POLL_MS'] + delete process.env['SOCKET_MCP_EVENTS_FAKE_ALERT'] + setStaticApiKey('') +}) + +test('advertises the events extension and lists socket.alert.created', async () => { + const { client } = await connect() + expect(client.getServerCapabilities()?.extensions).toEqual({ + [EVENTS_EXTENSION]: {}, + }) + const result = await client.request( + { method: 'events/list', params: {} }, + anything, + ) + const events = result['events'] as Array> + expect(events).toHaveLength(1) + expect(events[0]).toMatchObject({ + name: ALERT_CREATED_EVENT, + delivery: ['push'], + inputSchema: { required: ['org_slug'] }, + }) + await client.close() +}) + +test('events/stream emits a new alert exactly once', async () => { + const old = alert('a1', '2026-11-01T00:00:00.000Z') + const fresh = alert('a2', '2026-11-02T00:00:00.000Z') + const scope = nock(API) + .matchHeader('authorization', 'Bearer tok') + .get('/v0/orgs/my-org/alerts') + .query({ + 'filters.alertStatus': 'open', + 'filters.alertSeverity': 'critical', + per_page: '100', + }) + .reply(200, { items: [old] }) + .get('/v0/orgs/my-org/alerts') + .query(true) + .times(3) + .reply(200, { items: [fresh, old] }) + + const { client, notes } = await connect() + const { controller, done } = openStream(client, { + org_slug: 'my-org', + severity: 'critical', + }) + await vi.waitFor(() => expect(scope.isDone()).toBe(true), { timeout: 5000 }) + controller.abort() + await done + + const events = notes.filter(n => n.method === 'notifications/events/event') + expect(notes[0]?.method).toBe('notifications/events/active') + expect(events).toHaveLength(1) + expect(events[0]?.params).toMatchObject({ + eventId: 'my-org:a2', + name: ALERT_CREATED_EVENT, + cursor: expect.any(String), + data: { org_slug: 'my-org', alert: { id: 'a2' } }, + }) + expect(notes.some(n => n.method === 'notifications/events/heartbeat')).toBe( + true, + ) + await client.close() +}) + +test('events/stream rejects an unknown event name', async () => { + const { client } = await connect() + const { done } = openStream(client, { org_slug: 'my-org' }, 'nope') + expect(await done).toMatchObject({ code: -32_023 }) + await client.close() +}) + +test('fake-alert mode emits a synthetic alert without calling the API', async () => { + process.env['SOCKET_MCP_EVENTS_FAKE_ALERT'] = '1' + setStaticApiKey('') + const { client, notes } = await connect() + const { controller, done } = openStream(client, { org_slug: 'demo' }) + await vi.waitFor( + () => + expect( + notes.filter(n => n.method === 'notifications/events/event').length, + ).toBeGreaterThanOrEqual(2), + { timeout: 5000 }, + ) + controller.abort() + await done + const ids = notes + .filter(n => n.method === 'notifications/events/event') + .map(n => n.params['eventId']) + expect(new Set(ids).size).toBe(ids.length) + expect(ids[0]).toBe('demo:fake-alert-1') + await client.close() +}) From 3d8ad6ecd8ba244e09de0b684d7489010d930f8c Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 15:27:09 -0300 Subject: [PATCH 2/7] fix(events): heartbeat on its own clock and fix the OpenCode recipe OpenCode 2.4 drops an event stream after 30 seconds of silence, whatever heartbeat interval the server grants. Heartbeats followed the 60 second default poll interval, so real-mode streams were cut. They now run every SOCKET_MCP_EVENTS_HEARTBEAT_MS (default 10 seconds), capped at the poll interval. The README recipe now uses OpenCode 2.4's mcp.servers config, set with `opencode mcp add`, and the full automation_create shape with its action. Both were checked against OpenCode 2.4.2. --- README.md | 43 +++++++++++++-------------- lib/events.mts | 26 ++++++++++++---- test/repo/integration/events.test.mts | 19 ++++++++++++ 3 files changed, 61 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 20571665..be7c51f2 100644 --- a/README.md +++ b/README.md @@ -238,45 +238,44 @@ The local stdio and `--http` servers implement the [MCP Events extension](https: | Variable | Default | Purpose | | -------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- | -| `SOCKET_MCP_EVENTS_POLL_MS` | `60000` | Poll interval, also the granted heartbeat interval | +| `SOCKET_MCP_EVENTS_POLL_MS` | `60000` | Poll interval | +| `SOCKET_MCP_EVENTS_HEARTBEAT_MS` | `10000` | Heartbeat interval, capped at the poll interval. Clients drop a quiet stream (OpenCode 2.4 after 30 seconds) | | `SOCKET_MCP_EVENTS_FAKE_ALERT=1` | off | Demo mode: no Socket API calls and no token needed. Each poll after the baseline emits one synthetic `demo-evil-package` malware alert | -Recipe for OpenCode 2.4.0 (demo mode): - -1. Build this checkout with `pnpm install && pnpm run build`, then add the server to `opencode.json`: - - ```json - { - "mcp": { - "socket": { - "type": "local", - "command": ["node", "/path/to/socket-mcp/dist/index.cjs"], - "environment": { - "SOCKET_MCP_EVENTS_FAKE_ALERT": "1", - "SOCKET_MCP_EVENTS_POLL_MS": "15000" - } - } - } - } +Recipe for OpenCode 2.4 (demo mode, checked against 2.4.2): + +1. Build this checkout with `pnpm install && pnpm run build`, then register it globally. Use absolute paths, because the desktop app doesn't inherit your shell's `PATH`: + + ```sh + opencode mcp add --global \ + --env SOCKET_MCP_EVENTS_FAKE_ALERT=1 --env SOCKET_MCP_EVENTS_POLL_MS=15000 \ + socket -- "$(command -v node)" /path/to/socket-mcp/dist/index.cjs + opencode service restart ``` - Drop `SOCKET_MCP_EVENTS_FAKE_ALERT` to watch real alerts. The server then uses your `socket-mcp login` session or `SOCKET_API_TOKEN`. + This writes `mcp.servers.socket` to `~/.config/opencode/opencode.json`. Drop `SOCKET_MCP_EVENTS_FAKE_ALERT` to watch real alerts. The server then uses your `socket-mcp login` session or `SOCKET_API_TOKEN`. -2. In OpenCode, run `list_mcp_events`. It shows `socket.alert.created` from the `socket` server. -3. Create the automation: +2. In an OpenCode session, ask it to run `list_mcp_events` for server `socket`. It shows `socket.alert.created`, with its `args` and `data` schemas. +3. Ask it to create the automation. An event watch can only be created from a session, not over the HTTP API: ```js automation_create({ + name: 'socket-alerts', trigger: { type: 'event', server: 'socket', event: 'socket.alert.created', args: { org_slug: 'my-org', severity: 'high,critical' }, }, + action: { + type: 'prompt', + prompt: 'A new Socket alert arrived. Summarize it and suggest a fix.', + to: { session: '' }, + }, }) ``` -4. About one poll interval later, the automation fires with the alert in `data.alert`. In demo mode, one more fake alert arrives on each later poll. +4. About one poll interval later, the automation fires. In demo mode, one more fake alert arrives on each later poll, so delete the automation when the demo is over. ### Adjusting tool usage via client rules diff --git a/lib/events.mts b/lib/events.mts index 22ffa1bb..1b930f97 100644 --- a/lib/events.mts +++ b/lib/events.mts @@ -91,8 +91,10 @@ export type AlertSource = ( ) => Promise export interface EventsOptions { - // Poll interval for `events/stream`; also the granted heartbeat interval. + // Poll interval for `events/stream`. pollMs?: number | undefined + // Heartbeat interval, capped at the poll interval. + heartbeatMs?: number | undefined source?: AlertSource | undefined userAgent?: string | undefined } @@ -220,6 +222,12 @@ export function registerEventHandlers( options: EventsOptions = {}, ): void { const pollMs = options.pollMs ?? envInt('SOCKET_MCP_EVENTS_POLL_MS') ?? 60_000 + // Clients drop a quiet stream fast (OpenCode 2.4 after 30s, whatever we + // grant), so heartbeats run on their own short clock, not the poll's. + const heartbeatMs = Math.min( + pollMs, + options.heartbeatMs ?? envInt('SOCKET_MCP_EVENTS_HEARTBEAT_MS') ?? 10_000, + ) const fake = envBool('SOCKET_MCP_EVENTS_FAKE_ALERT') const source = options.source ?? (fake ? fakeAlertSource() : socketAlertSource) @@ -248,6 +256,7 @@ export function registerEventHandlers( } return streamAlerts(params, ctx, { pollMs, + heartbeatMs, poll: () => source(params.arguments, token ?? '', userAgent), }) }, @@ -262,7 +271,7 @@ export function registerEventHandlers( export async function streamAlerts( params: StreamParams, ctx: ServerContext, - opts: { pollMs: number; poll: () => Promise }, + opts: { pollMs: number; heartbeatMs: number; poll: () => Promise }, ): Promise<{ _meta: Record }> { const { signal } = ctx.mcpReq const meta = { [SUBSCRIPTION_ID_META_KEY]: ctx.mcpReq.id } @@ -329,16 +338,23 @@ export async function streamAlerts( await notify('active', { cursor, truncated: false, - heartbeatMs: opts.pollMs, + heartbeatMs: opts.heartbeatMs, }) let open = await tick() + let lastPoll = Date.now() while (open && !signal.aborted) { + const untilPoll = Math.max(0, lastPoll + opts.pollMs - Date.now()) try { - await sleep(opts.pollMs, undefined, { signal }) + await sleep(Math.min(opts.heartbeatMs, untilPoll), undefined, { signal }) } catch { break } - open = await tick() + if (Date.now() >= lastPoll + opts.pollMs) { + lastPoll = Date.now() + open = await tick() + } else { + await notify('heartbeat', { cursor }) + } } logger.info({ event: ALERT_CREATED_EVENT }, 'events stream closed') return { _meta: meta } diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts index 4d21f9fa..fbf4a5ee 100644 --- a/test/repo/integration/events.test.mts +++ b/test/repo/integration/events.test.mts @@ -81,6 +81,7 @@ afterEach(() => { nock.enableNetConnect() delete process.env['SOCKET_MCP_EVENTS_POLL_MS'] delete process.env['SOCKET_MCP_EVENTS_FAKE_ALERT'] + delete process.env['SOCKET_MCP_EVENTS_HEARTBEAT_MS'] setStaticApiKey('') }) @@ -172,3 +173,21 @@ test('fake-alert mode emits a synthetic alert without calling the API', async () expect(ids[0]).toBe('demo:fake-alert-1') await client.close() }) + +test('events/stream heartbeats between slow polls', async () => { + process.env['SOCKET_MCP_EVENTS_POLL_MS'] = '60000' + process.env['SOCKET_MCP_EVENTS_HEARTBEAT_MS'] = '20' + nock(API).get('/v0/orgs/my-org/alerts').query(true).reply(200, { items: [] }) + const { client, notes } = await connect() + const { controller, done } = openStream(client, { org_slug: 'my-org' }) + const heartbeats = () => + notes.filter(n => n.method === 'notifications/events/heartbeat') + await vi.waitFor(() => expect(heartbeats().length).toBeGreaterThan(2), { + timeout: 5000, + }) + controller.abort() + await done + expect(notes[0]?.params).toMatchObject({ heartbeatMs: 20 }) + expect(nock.isDone()).toBe(true) + await client.close() +}) From 96d915050b342bf005dd6b0cc98cdbdcee7a6625 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 15:34:25 -0300 Subject: [PATCH 3/7] feat(events): drive demo alerts from a local file Replace the timer-based SOCKET_MCP_EVENTS_FAKE_ALERT mode, which emitted a synthetic alert on every poll, with SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE. Each poll reads alerts from a local NDJSON file instead of the Socket API. Lines present when a stream opens are its baseline, and each appended line fires once, so a demo fires a realistic alert on cue. The severity filter applies to file alerts too. --- README.md | 27 +++++++----- lib/events.mts | 59 ++++++++++++++++----------- test/repo/integration/events.test.mts | 42 +++++++++++-------- 3 files changed, 79 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index be7c51f2..3fce681b 100644 --- a/README.md +++ b/README.md @@ -236,24 +236,25 @@ See the [organization and alerts example](docs/service.md#worked-example-organiz The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer one event, `socket.alert.created`, which takes `org_slug` and an optional comma-separated `severity` filter. With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. -| Variable | Default | Purpose | -| -------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- | -| `SOCKET_MCP_EVENTS_POLL_MS` | `60000` | Poll interval | -| `SOCKET_MCP_EVENTS_HEARTBEAT_MS` | `10000` | Heartbeat interval, capped at the poll interval. Clients drop a quiet stream (OpenCode 2.4 after 30 seconds) | -| `SOCKET_MCP_EVENTS_FAKE_ALERT=1` | off | Demo mode: no Socket API calls and no token needed. Each poll after the baseline emits one synthetic `demo-evil-package` malware alert | +| Variable | Default | Purpose | +| ------------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SOCKET_MCP_EVENTS_POLL_MS` | `60000` | Poll interval | +| `SOCKET_MCP_EVENTS_HEARTBEAT_MS` | `10000` | Heartbeat interval, capped at the poll interval. Clients drop a quiet stream (OpenCode 2.4 after 30 seconds) | +| `SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE` | unset | Demo mode: read alerts from this local NDJSON file (one alert object with an `id` per line) instead of the Socket API, with no token or network. Lines present when a stream opens are the baseline, and each appended line fires once | Recipe for OpenCode 2.4 (demo mode, checked against 2.4.2): -1. Build this checkout with `pnpm install && pnpm run build`, then register it globally. Use absolute paths, because the desktop app doesn't inherit your shell's `PATH`: +1. Build this checkout with `pnpm install && pnpm run build`, then register it in your project. Use absolute paths, because the desktop app doesn't inherit your shell's `PATH`: ```sh - opencode mcp add --global \ - --env SOCKET_MCP_EVENTS_FAKE_ALERT=1 --env SOCKET_MCP_EVENTS_POLL_MS=15000 \ + cd your-project + opencode mcp add \ + --env SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE="$PWD/.socket/fake-alerts.ndjson" --env SOCKET_MCP_EVENTS_POLL_MS=3000 \ socket -- "$(command -v node)" /path/to/socket-mcp/dist/index.cjs opencode service restart ``` - This writes `mcp.servers.socket` to `~/.config/opencode/opencode.json`. Drop `SOCKET_MCP_EVENTS_FAKE_ALERT` to watch real alerts. The server then uses your `socket-mcp login` session or `SOCKET_API_TOKEN`. + This writes `mcp.servers.socket` to the project's `opencode.json`. Drop `SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE` to watch real alerts. The server then uses your `socket-mcp login` session or `SOCKET_API_TOKEN`. 2. In an OpenCode session, ask it to run `list_mcp_events` for server `socket`. It shows `socket.alert.created`, with its `args` and `data` schemas. 3. Ask it to create the automation. An event watch can only be created from a session, not over the HTTP API: @@ -275,7 +276,13 @@ Recipe for OpenCode 2.4 (demo mode, checked against 2.4.2): }) ``` -4. About one poll interval later, the automation fires. In demo mode, one more fake alert arrives on each later poll, so delete the automation when the demo is over. +4. In demo mode, append an alert to fire it on cue: + + ```sh + echo '{"id":"demo-1","type":"cve","severity":"high","artifact":{"type":"npm","name":"lodash","version":"4.17.20"},"createdAt":"2026-11-27T00:00:00Z"}' >> .socket/fake-alerts.ndjson + ``` + + The automation fires within one poll interval. ### Adjusting tool usage via client rules diff --git a/lib/events.mts b/lib/events.mts index 1b930f97..9837ee8d 100644 --- a/lib/events.mts +++ b/lib/events.mts @@ -7,6 +7,7 @@ * (modelcontextprotocol/typescript-sdk#3209), so the two methods are plain * custom request handlers. Swap them for the SDK's API once it lands. */ +import { readFile } from 'node:fs/promises' import { setTimeout as sleep } from 'node:timers/promises' import { @@ -21,7 +22,7 @@ import type { import { isPlainObject } from '@socketsecurity/lib-stable/objects/predicates' import { fetchAlerts } from './alerts.mts' -import { envBool, envInt } from './env.mts' +import { envInt, envString } from './env.mts' import { logger } from './logger.mts' import { AUTH_REQUIRED_MSG, @@ -177,7 +178,12 @@ export const socketAlertSource: AlertSource = async ( }) const record = isPlainObject(body) ? body : {} const items = record['items'] ?? record['results'] ?? [] - return (Array.isArray(items) ? items : []).flatMap(item => { + return toAlerts(Array.isArray(items) ? items : []) +} + +// Keep objects that carry an `id` (or `key`), with the id as a string. +function toAlerts(items: unknown[]): Alert[] { + return items.flatMap(item => { if (!isPlainObject(item)) { return [] } @@ -188,27 +194,33 @@ export const socketAlertSource: AlertSource = async ( }) } -// Demo source (SOCKET_MCP_EVENTS_FAKE_ALERT=1): no network. The first poll is -// empty (the baseline); every later poll returns one more synthetic alert, so -// a new event fires once per poll interval. -export function fakeAlertSource(): AlertSource { - const alerts: Alert[] = [] - let polls = 0 +/** + * Demo source (SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE): no network and no token. + * Each poll reads alerts from a local NDJSON file, one alert object per line. + * Lines already in the file when a stream opens are its baseline, so + * appending a line fires exactly one event on cue. + */ +export function fileAlertSource(file: string): AlertSource { return async args => { - if (polls++ > 0) { - const severity = args.severity?.split(',')[0]?.trim() || 'critical' - alerts.unshift({ - id: `fake-alert-${polls - 1}`, - type: 'malware', - severity, - category: 'supplyChainRisk', - status: 'open', - createdAt: new Date().toISOString(), - artifact: { type: 'npm', name: 'demo-evil-package', version: '6.6.6' }, - description: 'Synthetic alert from SOCKET_MCP_EVENTS_FAKE_ALERT', - }) + let text = '' + try { + text = await readFile(file, 'utf8') + } catch { + // No file yet means no alerts yet. } - return alerts + const parsed = text.split('\n').flatMap(line => { + try { + return line.trim() ? [JSON.parse(line) as unknown] : [] + } catch { + return [] + } + }) + const wanted = args.severity?.split(',').map(s => s.trim()) + return toAlerts(parsed) + .filter( + alert => !wanted || wanted.includes(String(alert['severity'] ?? '')), + ) + .reverse() } } @@ -228,9 +240,10 @@ export function registerEventHandlers( pollMs, options.heartbeatMs ?? envInt('SOCKET_MCP_EVENTS_HEARTBEAT_MS') ?? 10_000, ) - const fake = envBool('SOCKET_MCP_EVENTS_FAKE_ALERT') + const fakeFile = envString('SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE') + const fake = fakeFile !== undefined const source = - options.source ?? (fake ? fakeAlertSource() : socketAlertSource) + options.source ?? (fake ? fileAlertSource(fakeFile) : socketAlertSource) const userAgent = options.userAgent ?? '' server.registerCapabilities({ extensions: { [EVENTS_EXTENSION]: {} } }) diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts index fbf4a5ee..07848665 100644 --- a/test/repo/integration/events.test.mts +++ b/test/repo/integration/events.test.mts @@ -1,3 +1,7 @@ +import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + import { Client, InMemoryTransport } from '@modelcontextprotocol/client' import type { StandardSchemaV1 } from '@modelcontextprotocol/client' import nock from 'nock' @@ -80,7 +84,7 @@ afterEach(() => { nock.cleanAll() nock.enableNetConnect() delete process.env['SOCKET_MCP_EVENTS_POLL_MS'] - delete process.env['SOCKET_MCP_EVENTS_FAKE_ALERT'] + delete process.env['SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE'] delete process.env['SOCKET_MCP_EVENTS_HEARTBEAT_MS'] setStaticApiKey('') }) @@ -152,26 +156,32 @@ test('events/stream rejects an unknown event name', async () => { await client.close() }) -test('fake-alert mode emits a synthetic alert without calling the API', async () => { - process.env['SOCKET_MCP_EVENTS_FAKE_ALERT'] = '1' +test('fake-alerts file fires each appended alert once, with no API call', async () => { + const dir = mkdtempSync(path.join(tmpdir(), 'mcp-events-')) + const file = path.join(dir, 'alerts.ndjson') + const line = (id: string, severity = 'critical') => + `${JSON.stringify({ id, severity, createdAt: new Date().toISOString() })}\n` + writeFileSync(file, line('old')) + process.env['SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE'] = file setStaticApiKey('') const { client, notes } = await connect() - const { controller, done } = openStream(client, { org_slug: 'demo' }) - await vi.waitFor( - () => - expect( - notes.filter(n => n.method === 'notifications/events/event').length, - ).toBeGreaterThanOrEqual(2), - { timeout: 5000 }, - ) + const events = () => + notes.filter(n => n.method === 'notifications/events/event') + const { controller, done } = openStream(client, { + org_slug: 'demo', + severity: 'critical,high', + }) + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(1)) + appendFileSync(file, line('low-one', 'low') + 'not json\n' + line('new')) + await vi.waitFor(() => expect(events()).toHaveLength(1), { timeout: 5000 }) + appendFileSync(file, line('new')) + const heartbeats = notes.length + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(heartbeats + 2)) controller.abort() await done - const ids = notes - .filter(n => n.method === 'notifications/events/event') - .map(n => n.params['eventId']) - expect(new Set(ids).size).toBe(ids.length) - expect(ids[0]).toBe('demo:fake-alert-1') + expect(events().map(n => n.params['eventId'])).toEqual(['demo:new']) await client.close() + rmSync(dir, { recursive: true, force: true }) }) test('events/stream heartbeats between slow polls', async () => { From 2fe17d4d97a5ab69484b48c9dbb2cd0169700e93 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 17:11:11 -0300 Subject: [PATCH 4/7] feat(events): add socket.patch.available event and watch-socket-alerts skill Add a second event, socket.patch.available. It fires for new CVE alerts that a Socket Certified Patch fixes: the API query adds filters.cvePatchStatus=patch_available, and the payload lists each patch's uuid and purl for `socket-patch get `. The fake-alerts file applies the same patch filter. Implement the MCP Skills extension (io.modelcontextprotocol/skills) with one skill, watch-socket-alerts. It teaches an agent to set up an automation on these events and to preview and apply a certified patch. skills/list and skills/get are custom handlers with a sha256 manifest, and SKILL.md is served through resources/list and resources/read. --- README.md | 13 +- lib/alerts.mts | 5 + lib/events.mts | 148 +++++++++++++++---- lib/server.mts | 2 + lib/skills.mts | 195 ++++++++++++++++++++++++++ test/repo/integration/events.test.mts | 94 ++++++++++++- test/repo/integration/skills.test.mts | 90 ++++++++++++ 7 files changed, 512 insertions(+), 35 deletions(-) create mode 100644 lib/skills.mts create mode 100644 test/repo/integration/skills.test.mts diff --git a/README.md b/README.md index 3fce681b..62efddf4 100644 --- a/README.md +++ b/README.md @@ -232,9 +232,18 @@ See the [authentication reference](docs/service.md#authentication-for-organizati See the [organization and alerts example](docs/service.md#worked-example-organization-details-and-alerts). -### MCP Events: new-alert notifications (Beta) +### MCP Events and Skills: new-alert notifications (Beta) -The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer one event, `socket.alert.created`, which takes `org_slug` and an optional comma-separated `severity` filter. With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. +The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer two events. Both take `org_slug` and an optional comma-separated `severity` filter. + +| Event | Fires when | `data` | +| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `socket.alert.created` | A new alert appears in the org | `org_slug`, `alert` | +| `socket.patch.available` | A new CVE alert has a [Socket Certified Patch](https://docs.socket.dev/docs/sca-patches) (`filters.cvePatchStatus=patch_available`) | `org_slug`, `alert`, `patches[]` with each patch's `uuid` and `purl` | + +With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. + +The servers also implement the [MCP Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) (`io.modelcontextprotocol/skills`) with one skill, `watch-socket-alerts`, at `skill://socket/watch-socket-alerts/SKILL.md`. It teaches an agent how to turn these events into an automation, and how to preview and apply a certified patch with `socket-patch`. A user can then say "watch my Socket alerts for patches" instead of spelling out the automation. | Variable | Default | Purpose | | ------------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/lib/alerts.mts b/lib/alerts.mts index 8ac6b85c..a5031f1b 100644 --- a/lib/alerts.mts +++ b/lib/alerts.mts @@ -18,6 +18,8 @@ export interface AlertsFilters { alertType?: string | undefined // Comma-separated repo slugs repoSlug?: string | undefined + // Comma-separated subset of: patch_unavailable,patch_available,patch_applied + patchStatus?: string | undefined // 1..5000. The API caps at 5000 and defaults to 1000. perPage?: number | undefined // Pagination cursor from a previous response's endCursor @@ -65,6 +67,9 @@ export function buildAlertsQuery( if (f.repoSlug) { params.set('filters.repoSlug', f.repoSlug) } + if (f.patchStatus) { + params.set('filters.cvePatchStatus', f.patchStatus) + } const perPage = f.perPage ?? perPageFallback if (typeof perPage === 'number') { params.set('per_page', String(perPage)) diff --git a/lib/events.mts b/lib/events.mts index 9837ee8d..5a3a739d 100644 --- a/lib/events.mts +++ b/lib/events.mts @@ -1,8 +1,9 @@ /** * @file MCP Events (SEP-3415, `io.modelcontextprotocol/events`, Beta) for the - * local stdio and `--http` server. One event type, `socket.alert.created`, - * delivered by push only: `events/stream` polls the org alerts API with the - * caller's own token and emits each alert it has not seen before. + * local stdio and `--http` server. Two event types, `socket.alert.created` + * and `socket.patch.available`, delivered by push only: `events/stream` + * polls the org alerts API with the caller's own token and emits each alert + * it has not seen before. * The TypeScript SDK has no events support yet * (modelcontextprotocol/typescript-sdk#3209), so the two methods are plain * custom request handlers. Swap them for the SDK's API once it lands. @@ -33,50 +34,91 @@ import { UpstreamHttpError } from './tool-outcome.mts' export const EVENTS_EXTENSION = 'io.modelcontextprotocol/events' export const ALERT_CREATED_EVENT = 'socket.alert.created' +export const PATCH_AVAILABLE_EVENT = 'socket.patch.available' // Spec error codes (SEP-3415). const NOT_FOUND = -32_023 const FORBIDDEN = -32_024 +const ALERT_INPUT_SCHEMA = { + type: 'object', + properties: { + org_slug: { + type: 'string', + description: 'Organization slug, e.g. "my-org"', + }, + severity: { + type: 'string', + description: + 'Comma-separated severities to include: subset of low,medium,high,critical', + }, + }, + required: ['org_slug'], + additionalProperties: false, +} + +const ALERT_PAYLOAD_PROPERTIES = { + org_slug: { type: 'string' }, + alert: { + type: 'object', + description: 'The alert as returned by GET /v0/orgs/{org}/alerts', + }, +} + const ALERT_CREATED_DEFINITION = { name: ALERT_CREATED_EVENT, description: 'A new Socket alert appeared for an organization you can access. Polls the org alerts API with your own token and fires once per new alert.', delivery: ['push'], - inputSchema: { + inputSchema: ALERT_INPUT_SCHEMA, + payloadSchema: { type: 'object', - properties: { - org_slug: { - type: 'string', - description: 'Organization slug, e.g. "my-org"', - }, - severity: { - type: 'string', - description: - 'Comma-separated severities to include: subset of low,medium,high,critical', - }, - }, - required: ['org_slug'], - additionalProperties: false, + properties: ALERT_PAYLOAD_PROPERTIES, + required: ['org_slug', 'alert'], }, +} + +const PATCH_AVAILABLE_DEFINITION = { + name: PATCH_AVAILABLE_EVENT, + description: + 'A CVE alert that a Socket Certified Patch fixes appeared for an organization you can access. A certified patch backports the fix into the exact version in use, so nothing is upgraded. Apply one with `socket-patch get ` from the project root. Fires once per alert.', + delivery: ['push'], + inputSchema: ALERT_INPUT_SCHEMA, payloadSchema: { type: 'object', properties: { - org_slug: { type: 'string' }, - alert: { - type: 'object', - description: 'The alert as returned by GET /v0/orgs/{org}/alerts', + ...ALERT_PAYLOAD_PROPERTIES, + patches: { + type: 'array', + description: 'The certified patches available for this alert', + items: { + type: 'object', + properties: { + uuid: { + type: 'string', + description: 'Patch id, for `socket-patch get `', + }, + purl: { type: 'string', description: 'The patched package' }, + }, + required: ['uuid'], + }, }, }, - required: ['org_slug', 'alert'], + required: ['org_slug', 'alert', 'patches'], }, } +const EVENT_DEFINITIONS = [ALERT_CREATED_DEFINITION, PATCH_AVAILABLE_DEFINITION] + export interface AlertCreatedArgs { org_slug: string severity?: string | undefined } +// What a source fetches: the event's arguments, plus whether only alerts +// with an available certified patch count. +export type AlertQuery = AlertCreatedArgs & { patchOnly?: boolean | undefined } + interface StreamParams { name: string arguments: AlertCreatedArgs @@ -86,7 +128,7 @@ interface StreamParams { export type Alert = Record & { id: string } export type AlertSource = ( - args: AlertCreatedArgs, + query: AlertQuery, token: string, userAgent: string, ) => Promise @@ -174,6 +216,7 @@ export const socketAlertSource: AlertSource = async ( status: 'open', perPage: 100, ...(args.severity ? { severity: args.severity } : {}), + ...(args.patchOnly ? { patchStatus: 'patch_available' } : {}), }, }) const record = isPlainObject(body) ? body : {} @@ -194,6 +237,36 @@ function toAlerts(items: unknown[]): Alert[] { }) } +/** + * The certified patches an alert can use: its locations whose patch status is + * `patch_available`, one entry per patch uuid. + */ +export function availablePatches( + alert: Alert, +): Array<{ uuid: string; purl?: string }> { + const locations = Array.isArray(alert['locations']) ? alert['locations'] : [] + const patches = new Map() + for (const location of locations) { + if (!isPlainObject(location) || !isPlainObject(location['patch'])) { + continue + } + const { uuid, status } = location['patch'] + if (typeof uuid !== 'string' || status !== 'patch_available') { + continue + } + const artifact = isPlainObject(location['artifact']) + ? location['artifact'] + : {} + const { type, namespace, name, version } = artifact + const purl = + typeof type === 'string' && typeof name === 'string' + ? `pkg:${type}/${typeof namespace === 'string' && namespace ? `${namespace}/` : ''}${name}${typeof version === 'string' ? `@${version}` : ''}` + : undefined + patches.set(uuid, { uuid, ...(purl ? { purl } : {}) }) + } + return [...patches.values()] +} + /** * Demo source (SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE): no network and no token. * Each poll reads alerts from a local NDJSON file, one alert object per line. @@ -220,6 +293,7 @@ export function fileAlertSource(file: string): AlertSource { .filter( alert => !wanted || wanted.includes(String(alert['severity'] ?? '')), ) + .filter(alert => !args.patchOnly || availablePatches(alert).length > 0) .reverse() } } @@ -251,14 +325,14 @@ export function registerEventHandlers( server.setRequestHandler( 'events/list', { params: passthrough(value => value) }, - () => ({ events: [ALERT_CREATED_DEFINITION] }), + () => ({ events: EVENT_DEFINITIONS }), ) server.setRequestHandler( 'events/stream', { params: passthrough(parseStreamParams) }, async (params, ctx) => { - if (params.name !== ALERT_CREATED_EVENT) { + if (!EVENT_DEFINITIONS.some(event => event.name === params.name)) { throw new ProtocolError(NOT_FOUND, `Unknown event: ${params.name}`, { kind: 'event', }) @@ -270,7 +344,15 @@ export function registerEventHandlers( return streamAlerts(params, ctx, { pollMs, heartbeatMs, - poll: () => source(params.arguments, token ?? '', userAgent), + poll: () => + source( + { + ...params.arguments, + patchOnly: params.name === PATCH_AVAILABLE_EVENT, + }, + token ?? '', + userAgent, + ), }) }, ) @@ -333,9 +415,15 @@ export async function streamAlerts( } await notify('event', { eventId: `${params.arguments.org_slug}:${alert.id}`, - name: ALERT_CREATED_EVENT, + name: params.name, timestamp: time ?? new Date().toISOString(), - data: { org_slug: params.arguments.org_slug, alert }, + data: { + org_slug: params.arguments.org_slug, + alert, + ...(params.name === PATCH_AVAILABLE_EVENT + ? { patches: availablePatches(alert) } + : {}), + }, cursor, }) } @@ -347,7 +435,7 @@ export async function streamAlerts( return true } - logger.info({ event: ALERT_CREATED_EVENT }, 'events stream opened') + logger.info({ event: params.name }, 'events stream opened') await notify('active', { cursor, truncated: false, @@ -369,6 +457,6 @@ export async function streamAlerts( await notify('heartbeat', { cursor }) } } - logger.info({ event: ALERT_CREATED_EVENT }, 'events stream closed') + logger.info({ event: params.name }, 'events stream closed') return { _meta: meta } } diff --git a/lib/server.mts b/lib/server.mts index 989d30d2..930e35f8 100644 --- a/lib/server.mts +++ b/lib/server.mts @@ -15,6 +15,7 @@ import { traceToolCall, } from './error-reporting.mts' import { registerEventHandlers } from './events.mts' +import { registerSkillHandlers } from './skills.mts' import { buildToolAuditEvent } from './tool-audit-event.mts' import type { ToolAuditEventV1, @@ -186,6 +187,7 @@ export function createConfiguredServer( ) registerEventHandlers(server, { userAgent }) + registerSkillHandlers(server) server.setRequestHandler('tools/list', () => ({ __proto__: null, diff --git a/lib/skills.mts b/lib/skills.mts new file mode 100644 index 00000000..e9830293 --- /dev/null +++ b/lib/skills.mts @@ -0,0 +1,195 @@ +/** + * @file MCP Skills (`io.modelcontextprotocol/skills`, Beta) for the local + * stdio and `--http` server. One skill, `watch-socket-alerts`, teaches an + * agent to turn this server's events into an automation. The SDK has no + * skills support yet, so `skills/list` and `skills/get` are custom handlers, + * and the skill's single file is served through `resources/read`. + */ +import { createHash } from 'node:crypto' + +import { ProtocolError } from '@modelcontextprotocol/server' +import type { Server, StandardSchemaV1 } from '@modelcontextprotocol/server' +import { isPlainObject } from '@socketsecurity/lib-stable/objects/predicates' + +export const SKILLS_EXTENSION = 'io.modelcontextprotocol/skills' +export const WATCH_SKILL_URI = 'skill://socket/watch-socket-alerts/SKILL.md' + +const INVALID_PARAMS = -32_602 +// The skill only changes when socket-mcp ships, so clients may cache it. +const CACHE = { ttlMs: 60 * 60 * 1000, cacheScope: 'public' } + +const FRONTMATTER = { + name: 'watch-socket-alerts', + description: + 'Set up an automation that reacts when Socket finds a new alert, or a new CVE with a Socket Certified Patch, in an organization. Use when the user wants to watch, monitor, or get notified about Socket alerts, vulnerabilities, malware, or patches.', +} + +export const WATCH_SKILL_MD = `--- +name: ${FRONTMATTER.name} +description: ${FRONTMATTER.description} +--- + +# Watch Socket alerts + +This server publishes MCP events. An automation subscribes to one, and the +client runs the automation's action each time the event fires, even while +nobody is looking at the session. + +## Events + +| Event | Fires when | \`data\` | +| --- | --- | --- | +| \`socket.alert.created\` | A new alert appears in the org | \`org_slug\`, \`alert\` | +| \`socket.patch.available\` | A new CVE alert has a Socket Certified Patch | \`org_slug\`, \`alert\`, \`patches[]\` (\`uuid\`, \`purl\`) | + +Both take \`org_slug\` (required) and \`severity\` (optional, comma-separated +subset of \`low,medium,high,critical\`). Existing alerts never fire: only alerts +that appear after the automation starts do. + +## Steps + +1. Get the organization slug. Call this server's \`organizations\` tool, or ask + the user if they belong to several. +2. Pick the event. Use \`socket.patch.available\` when the user wants fixes + they can apply now, and \`socket.alert.created\` for everything else. +3. Create the automation with the client's automation tool. In OpenCode: + + \`\`\`js + automation_create({ + name: 'socket-alerts', + trigger: { + type: 'event', + server: '', + event: 'socket.patch.available', + args: { org_slug: '', severity: 'high,critical' }, + }, + action: { + type: 'prompt', + prompt: '', + to: { session: '' }, + }, + }) + \`\`\` + + OpenCode exposes the current session id as \`$OPENCODE_SESSION_ID\`. +4. Tell the user what you set up, and that deleting this session pauses the + automation. + +## Prompt for the action + +For \`socket.alert.created\`: + +> A new Socket alert arrived. Read the alert in the event data, check whether +> this project uses the affected package (manifests, lockfile, source), and +> propose a fix. Don't change files until I confirm. + +For \`socket.patch.available\`: + +> A Socket Certified Patch is available for a new CVE alert. Check that this +> project uses the affected package version, then preview the patch with +> \`socket-patch get --dry-run\` using each uuid in the event's +> \`patches\`. Show me the preview and wait for my confirmation before applying +> it. + +## Applying a certified patch + +A certified patch backports the CVE fix into the exact version the project +already uses, so nothing is upgraded. Run these from the project root: + +- \`socket-patch get --dry-run\` previews the change. +- \`socket-patch get \` applies it. Add \`--mode vendored\` to commit the + patched package into the repo (\`.socket/vendor/\`) instead of pointing the + lockfile at \`patch.socket.dev\`. +- Reinstall dependencies afterwards, then run \`socket-patch list\` to confirm. + +If \`socket-patch\` isn't installed, use \`npx @socketsecurity/socket-patch\`. +Free patches cover critical CVEs and need no token. Other patches need a +Socket API token for an organization with the Patches add-on. +` + +const WATCH_SKILL = { + uri: WATCH_SKILL_URI, + frontmatter: FRONTMATTER, + resources: [ + { + uri: WATCH_SKILL_URI, + digest: `sha256:${createHash('sha256').update(WATCH_SKILL_MD).digest('hex')}`, + size: Buffer.byteLength(WATCH_SKILL_MD), + }, + ], +} + +function uriParams(): StandardSchemaV1 { + return { + '~standard': { + version: 1, + vendor: 'socket-mcp', + validate(value) { + const uri = isPlainObject(value) ? value['uri'] : undefined + return typeof uri === 'string' + ? { value: { uri } } + : { issues: [{ message: 'uri must be a string' }] } + }, + }, + } +} + +function assertSkillUri(uri: string): void { + if (uri !== WATCH_SKILL_URI) { + throw new ProtocolError(INVALID_PARAMS, `Unknown skill resource: ${uri}`) + } +} + +/** + * Advertise the skills extension (plus `resources`, which the spec requires + * because skill files are resources) and register its handlers. + */ +export function registerSkillHandlers(server: Server): void { + server.registerCapabilities({ + resources: {}, + extensions: { [SKILLS_EXTENSION]: {} }, + }) + + server.setRequestHandler( + 'skills/list', + { + params: { + '~standard': { + version: 1, + vendor: 'socket-mcp', + validate: value => ({ value }), + }, + }, + }, + () => ({ skills: [WATCH_SKILL], ...CACHE }), + ) + + server.setRequestHandler('skills/get', { params: uriParams() }, ({ uri }) => { + assertSkillUri(uri) + return { skill: WATCH_SKILL, ...CACHE } + }) + + server.setRequestHandler('resources/list', () => ({ + resources: [ + { + uri: WATCH_SKILL_URI, + name: FRONTMATTER.name, + description: FRONTMATTER.description, + mimeType: 'text/markdown', + }, + ], + })) + + server.setRequestHandler('resources/read', request => { + assertSkillUri(request.params.uri) + return { + contents: [ + { + uri: WATCH_SKILL_URI, + mimeType: 'text/markdown', + text: WATCH_SKILL_MD, + }, + ], + } + }) +} diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts index 07848665..678482ed 100644 --- a/test/repo/integration/events.test.mts +++ b/test/repo/integration/events.test.mts @@ -7,7 +7,11 @@ import type { StandardSchemaV1 } from '@modelcontextprotocol/client' import nock from 'nock' import { afterEach, beforeEach, expect, test, vi } from 'vitest' -import { ALERT_CREATED_EVENT, EVENTS_EXTENSION } from '../../../lib/events.mts' +import { + ALERT_CREATED_EVENT, + EVENTS_EXTENSION, + PATCH_AVAILABLE_EVENT, +} from '../../../lib/events.mts' import { createConfiguredServer, setStaticApiKey, @@ -91,7 +95,7 @@ afterEach(() => { test('advertises the events extension and lists socket.alert.created', async () => { const { client } = await connect() - expect(client.getServerCapabilities()?.extensions).toEqual({ + expect(client.getServerCapabilities()?.extensions).toMatchObject({ [EVENTS_EXTENSION]: {}, }) const result = await client.request( @@ -99,7 +103,10 @@ test('advertises the events extension and lists socket.alert.created', async () anything, ) const events = result['events'] as Array> - expect(events).toHaveLength(1) + expect(events.map(e => e['name'])).toEqual([ + ALERT_CREATED_EVENT, + PATCH_AVAILABLE_EVENT, + ]) expect(events[0]).toMatchObject({ name: ALERT_CREATED_EVENT, delivery: ['push'], @@ -201,3 +208,84 @@ test('events/stream heartbeats between slow polls', async () => { expect(nock.isDone()).toBe(true) await client.close() }) + +const patchable = (id: string, uuid: string) => ({ + id, + severity: 'critical', + createdAt: new Date().toISOString(), + vulnerability: { cveId: 'CVE-2021-44906' }, + locations: [ + { + patch: { uuid, status: 'patch_available', deprecated: false }, + artifact: { type: 'npm', name: 'minimist', version: '1.2.2' }, + }, + { + patch: { uuid: null, status: 'patch_unavailable', deprecated: false }, + artifact: { type: 'npm', name: 'minimist', version: '0.0.8' }, + }, + ], +}) + +test('socket.patch.available fires only for alerts with a certified patch', async () => { + const dir = mkdtempSync(path.join(tmpdir(), 'mcp-events-')) + const file = path.join(dir, 'alerts.ndjson') + writeFileSync(file, '') + process.env['SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE'] = file + setStaticApiKey('') + const { client, notes } = await connect() + const events = () => + notes.filter(n => n.method === 'notifications/events/event') + const { controller, done } = openStream( + client, + { org_slug: 'demo' }, + PATCH_AVAILABLE_EVENT, + ) + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(1)) + const plain = { + id: 'no-patch', + severity: 'critical', + createdAt: new Date().toISOString(), + } + appendFileSync( + file, + `${JSON.stringify(plain)}\n${JSON.stringify(patchable('fixable', 'patch-1'))}\n`, + ) + await vi.waitFor(() => expect(events()).toHaveLength(1), { timeout: 5000 }) + const heartbeats = notes.length + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(heartbeats + 2)) + controller.abort() + await done + expect(events()).toHaveLength(1) + expect(events()[0]?.params).toMatchObject({ + eventId: 'demo:fixable', + name: PATCH_AVAILABLE_EVENT, + data: { + org_slug: 'demo', + patches: [{ uuid: 'patch-1', purl: 'pkg:npm/minimist@1.2.2' }], + }, + }) + await client.close() + rmSync(dir, { recursive: true, force: true }) +}) + +test('socket.patch.available asks the API for patchable alerts only', async () => { + const scope = nock(API) + .matchHeader('authorization', 'Bearer tok') + .get('/v0/orgs/my-org/alerts') + .query({ + 'filters.alertStatus': 'open', + 'filters.cvePatchStatus': 'patch_available', + per_page: '100', + }) + .reply(200, { items: [] }) + const { client } = await connect() + const { controller, done } = openStream( + client, + { org_slug: 'my-org' }, + PATCH_AVAILABLE_EVENT, + ) + await vi.waitFor(() => expect(scope.isDone()).toBe(true), { timeout: 5000 }) + controller.abort() + await done + await client.close() +}) diff --git a/test/repo/integration/skills.test.mts b/test/repo/integration/skills.test.mts new file mode 100644 index 00000000..5c7d112c --- /dev/null +++ b/test/repo/integration/skills.test.mts @@ -0,0 +1,90 @@ +import { createHash } from 'node:crypto' + +import { Client, InMemoryTransport } from '@modelcontextprotocol/client' +import type { StandardSchemaV1 } from '@modelcontextprotocol/client' +import { expect, test } from 'vitest' + +import { EVENTS_EXTENSION } from '../../../lib/events.mts' +import { createConfiguredServer } from '../../../lib/server.mts' +import { SKILLS_EXTENSION, WATCH_SKILL_URI } from '../../../lib/skills.mts' + +const anything: StandardSchemaV1> = { + '~standard': { + version: 1, + vendor: 'test', + validate: value => ({ value: value as Record }), + }, +} + +async function connect(): Promise { + const server = createConfiguredServer(undefined, 'stdio') + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair() + await server.connect(serverTransport) + const client = new Client( + { name: 'test', version: '0.0.0' }, + { capabilities: {} }, + ) + await client.connect(clientTransport) + return client +} + +test('advertises skills, events and resources together', async () => { + const client = await connect() + const capabilities = client.getServerCapabilities() + expect(capabilities?.extensions).toEqual({ + [EVENTS_EXTENSION]: {}, + [SKILLS_EXTENSION]: {}, + }) + expect(capabilities?.resources).toEqual({}) + expect(capabilities?.tools).toBeDefined() + await client.close() +}) + +test('skills/list manifest matches the bytes resources/read serves', async () => { + const client = await connect() + const list = await client.request( + { method: 'skills/list', params: {} }, + anything, + ) + const skills = list['skills'] as Array> + expect(skills).toHaveLength(1) + const [skill] = skills + expect(skill?.['uri']).toBe(WATCH_SKILL_URI) + expect(skill?.['frontmatter']['name']).toBe('watch-socket-alerts') + expect(list['ttlMs']).toBeGreaterThan(0) + + const read = await client.readResource({ uri: WATCH_SKILL_URI }) + const text = (read.contents[0] as { text: string }).text + expect(text.startsWith('---\nname: watch-socket-alerts\n')).toBe(true) + expect(skill?.['resources']).toEqual([ + { + uri: WATCH_SKILL_URI, + digest: `sha256:${createHash('sha256').update(text).digest('hex')}`, + size: Buffer.byteLength(text), + }, + ]) + + const { resources } = await client.listResources() + expect(resources.map(r => r.uri)).toEqual([WATCH_SKILL_URI]) + await client.close() +}) + +test('skills/get returns the skill and rejects unknown uris', async () => { + const client = await connect() + const got = await client.request( + { method: 'skills/get', params: { uri: WATCH_SKILL_URI } }, + anything, + ) + expect((got['skill'] as Record)['uri']).toBe(WATCH_SKILL_URI) + await expect( + client.request( + { method: 'skills/get', params: { uri: 'skill://socket/nope/SKILL.md' } }, + anything, + ), + ).rejects.toMatchObject({ code: -32_602 }) + await expect( + client.readResource({ uri: 'skill://socket/nope/SKILL.md' }), + ).rejects.toMatchObject({ code: -32_602 }) + await client.close() +}) From b2a19150ac2a85dc54d9ef86ae38d1bd9ec72cc8 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 18:15:44 -0300 Subject: [PATCH 5/7] feat(skills): add apply-socket-patch skill Add a second MCP skill, apply-socket-patch. It covers the whole socket-patch workflow on its own, with or without an event: finding a patch, previewing it, choosing vendored or hosted mode under pnpm 11 or later, reinstalling from a clean node_modules, verifying with list and vex plus an exploit check that must first succeed on the unpatched version, and rolling back. watch-socket-alerts now points to it instead of carrying its own patch steps. Skills are defined in one table, so the list, get and resource handlers serve both. --- README.md | 5 +- lib/skills.mts | 192 +++++++++++++++++--------- test/repo/integration/skills.test.mts | 42 +++--- 3 files changed, 155 insertions(+), 84 deletions(-) diff --git a/README.md b/README.md index 62efddf4..1d0223b3 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,10 @@ The local stdio and `--http` servers implement the [MCP Events extension](https: With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. -The servers also implement the [MCP Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) (`io.modelcontextprotocol/skills`) with one skill, `watch-socket-alerts`, at `skill://socket/watch-socket-alerts/SKILL.md`. It teaches an agent how to turn these events into an automation, and how to preview and apply a certified patch with `socket-patch`. A user can then say "watch my Socket alerts for patches" instead of spelling out the automation. +The servers also implement the [MCP Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) (`io.modelcontextprotocol/skills`) with two skills, served at `skill://socket//SKILL.md`: + +- `watch-socket-alerts` teaches an agent to turn these events into an automation. A user can say "watch my Socket alerts for patches" instead of spelling out the automation. +- `apply-socket-patch` teaches an agent to find, preview, apply, verify, and roll back a Socket Certified Patch with `socket-patch`, with or without an event. | Variable | Default | Purpose | | ------------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/lib/skills.mts b/lib/skills.mts index e9830293..0e99bfdc 100644 --- a/lib/skills.mts +++ b/lib/skills.mts @@ -1,9 +1,10 @@ /** * @file MCP Skills (`io.modelcontextprotocol/skills`, Beta) for the local - * stdio and `--http` server. One skill, `watch-socket-alerts`, teaches an - * agent to turn this server's events into an automation. The SDK has no + * stdio and `--http` server. Two skills, each a single `SKILL.md`: + * `watch-socket-alerts` turns this server's events into an automation, and + * `apply-socket-patch` applies a Socket Certified Patch. The SDK has no * skills support yet, so `skills/list` and `skills/get` are custom handlers, - * and the skill's single file is served through `resources/read`. + * and each skill's file is served through `resources/read`. */ import { createHash } from 'node:crypto' @@ -13,23 +14,16 @@ import { isPlainObject } from '@socketsecurity/lib-stable/objects/predicates' export const SKILLS_EXTENSION = 'io.modelcontextprotocol/skills' export const WATCH_SKILL_URI = 'skill://socket/watch-socket-alerts/SKILL.md' +export const PATCH_SKILL_URI = 'skill://socket/apply-socket-patch/SKILL.md' const INVALID_PARAMS = -32_602 -// The skill only changes when socket-mcp ships, so clients may cache it. +// Skills only change when socket-mcp ships, so clients may cache them. const CACHE = { ttlMs: 60 * 60 * 1000, cacheScope: 'public' } -const FRONTMATTER = { - name: 'watch-socket-alerts', - description: - 'Set up an automation that reacts when Socket finds a new alert, or a new CVE with a Socket Certified Patch, in an organization. Use when the user wants to watch, monitor, or get notified about Socket alerts, vulnerabilities, malware, or patches.', -} - -export const WATCH_SKILL_MD = `--- -name: ${FRONTMATTER.name} -description: ${FRONTMATTER.description} ---- +const WATCH_DESCRIPTION = + 'Set up an automation that reacts when Socket finds a new alert, or a new CVE with a Socket Certified Patch, in an organization. Use when the user wants to watch, monitor, or get notified about Socket alerts, vulnerabilities, malware, or patches.' -# Watch Socket alerts +const WATCH_BODY = `# Watch Socket alerts This server publishes MCP events. An automation subscribes to one, and the client runs the automation's action each time the event fires, even while @@ -51,7 +45,8 @@ that appear after the automation starts do. 1. Get the organization slug. Call this server's \`organizations\` tool, or ask the user if they belong to several. 2. Pick the event. Use \`socket.patch.available\` when the user wants fixes - they can apply now, and \`socket.alert.created\` for everything else. + they can apply now, and \`socket.alert.created\` for everything else. Pass + \`severity\` when the user names one. 3. Create the automation with the client's automation tool. In OpenCode: \`\`\`js @@ -85,40 +80,109 @@ For \`socket.alert.created\`: For \`socket.patch.available\`: -> A Socket Certified Patch is available for a new CVE alert. Check that this -> project uses the affected package version, then preview the patch with -> \`socket-patch get --dry-run\` using each uuid in the event's -> \`patches\`. Show me the preview and wait for my confirmation before applying -> it. +> A Socket Certified Patch is available for a new CVE alert. Load the +> apply-socket-patch skill, check that this project uses the affected package +> version, and preview each patch in the event's \`patches\`. Show me the +> preview and wait for my confirmation before applying it. + +To apply a patch, follow the \`apply-socket-patch\` skill from this server. +` + +const PATCH_DESCRIPTION = + 'Find, preview, apply, verify, and roll back Socket Certified Patches with the socket-patch CLI. A certified patch backports a CVE fix into the exact dependency version in use, so nothing is upgraded. Use when the user wants to patch a CVE, GHSA, or package without upgrading it, or acts on a socket.patch.available event.' + +const PATCH_BODY = `# Apply a Socket Certified Patch + +A Socket Certified Patch removes a CVE from a dependency without changing its +version. Run every command from the project root. If \`socket-patch\` isn't +installed, use \`npx @socketsecurity/socket-patch\`. + +## Access + +- Free patches cover critical CVEs. They need no token: the CLI reads them + from Socket's public patch API. +- Other patches need \`SOCKET_API_TOKEN\` for an organization with the Patches + add-on. + +## 1. Find the patch + +- From a \`socket.patch.available\` event: use each \`uuid\` in \`patches\`. +- \`socket-patch get --dry-run\` targets + one advisory or package. +- \`socket-patch scan --dry-run\` lists every available patch for the project. + +\`--dry-run\` changes nothing. \`scan --json\` without \`--dry-run\` applies +patches, so never use it to preview. + +Before applying, confirm the project really uses the affected version: check +the manifest, the lockfile, and \`node_modules\` (or the ecosystem's +equivalent). + +## 2. Pick a mode + +- **Vendored** (\`--mode vendored\`): commits the patched package under + \`.socket/vendor/\`. Installs need nothing from Socket. Prefer it with pnpm 11 + or later. +- **Hosted** (the default for a project with no patches): points the lockfile + at \`patch.socket.dev\`. With pnpm 11 or later it also writes + \`trustLockfile: true\` to \`pnpm-workspace.yaml\`, which turns off pnpm's + lockfile re-verification for every entry. Mention that before using it. + +A project keeps the mode it already uses unless you pass \`--mode\`. + +## 3. Apply and reinstall -## Applying a certified patch +\`\`\`sh +socket-patch get --mode vendored +rm -rf node_modules && pnpm install # or the project's install command +\`\`\` -A certified patch backports the CVE fix into the exact version the project -already uses, so nothing is upgraded. Run these from the project root: +Reinstall from a clean \`node_modules\`: an existing install can keep the +unpatched files. Never rebuild the lockfile (for example \`pnpm clean +--lockfile\`), because that drops the patch and reinstalls the vulnerable +version. -- \`socket-patch get --dry-run\` previews the change. -- \`socket-patch get \` applies it. Add \`--mode vendored\` to commit the - patched package into the repo (\`.socket/vendor/\`) instead of pointing the - lockfile at \`patch.socket.dev\`. -- Reinstall dependencies afterwards, then run \`socket-patch list\` to confirm. +Commit what the CLI reports, together: \`.socket/vendor/\`, the lockfile, +\`package.json\`, and \`pnpm-workspace.yaml\` when it was written. -If \`socket-patch\` isn't installed, use \`npx @socketsecurity/socket-patch\`. -Free patches cover critical CVEs and need no token. Other patches need a -Socket API token for an organization with the Patches add-on. +## 4. Verify + +- \`socket-patch list\` shows the patch, its mode, and the files it changed. +- \`socket-patch vex\` should report the CVE as \`not_affected\`. +- If you test the exploit, use the advisory's real payload, and show that it + succeeds on the unpatched version first. A check that passes on both + versions proves nothing. + +## 5. Roll back + +\`socket-patch rollback\` restores the upstream packages. In vendored mode, +\`socket-patch vendor --revert\` also works. Reinstall afterwards. ` -const WATCH_SKILL = { - uri: WATCH_SKILL_URI, - frontmatter: FRONTMATTER, - resources: [ - { - uri: WATCH_SKILL_URI, - digest: `sha256:${createHash('sha256').update(WATCH_SKILL_MD).digest('hex')}`, - size: Buffer.byteLength(WATCH_SKILL_MD), +function defineSkill(name: string, description: string, body: string) { + const uri = `skill://socket/${name}/SKILL.md` + const text = `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}` + return { + text, + entry: { + uri, + frontmatter: { name, description }, + resources: [ + { + uri, + digest: `sha256:${createHash('sha256').update(text).digest('hex')}`, + size: Buffer.byteLength(text), + }, + ], }, - ], + } } +const SKILLS = [ + defineSkill('watch-socket-alerts', WATCH_DESCRIPTION, WATCH_BODY), + defineSkill('apply-socket-patch', PATCH_DESCRIPTION, PATCH_BODY), +] + function uriParams(): StandardSchemaV1 { return { '~standard': { @@ -134,10 +198,12 @@ function uriParams(): StandardSchemaV1 { } } -function assertSkillUri(uri: string): void { - if (uri !== WATCH_SKILL_URI) { +function findSkill(uri: string) { + const skill = SKILLS.find(s => s.entry.uri === uri) + if (!skill) { throw new ProtocolError(INVALID_PARAMS, `Unknown skill resource: ${uri}`) } + return skill } /** @@ -161,35 +227,29 @@ export function registerSkillHandlers(server: Server): void { }, }, }, - () => ({ skills: [WATCH_SKILL], ...CACHE }), + () => ({ skills: SKILLS.map(s => s.entry), ...CACHE }), ) - server.setRequestHandler('skills/get', { params: uriParams() }, ({ uri }) => { - assertSkillUri(uri) - return { skill: WATCH_SKILL, ...CACHE } - }) + server.setRequestHandler( + 'skills/get', + { params: uriParams() }, + ({ uri }) => ({ + skill: findSkill(uri).entry, + ...CACHE, + }), + ) server.setRequestHandler('resources/list', () => ({ - resources: [ - { - uri: WATCH_SKILL_URI, - name: FRONTMATTER.name, - description: FRONTMATTER.description, - mimeType: 'text/markdown', - }, - ], + resources: SKILLS.map(({ entry }) => ({ + uri: entry.uri, + name: entry.frontmatter.name, + description: entry.frontmatter.description, + mimeType: 'text/markdown', + })), })) server.setRequestHandler('resources/read', request => { - assertSkillUri(request.params.uri) - return { - contents: [ - { - uri: WATCH_SKILL_URI, - mimeType: 'text/markdown', - text: WATCH_SKILL_MD, - }, - ], - } + const { entry, text } = findSkill(request.params.uri) + return { contents: [{ uri: entry.uri, mimeType: 'text/markdown', text }] } }) } diff --git a/test/repo/integration/skills.test.mts b/test/repo/integration/skills.test.mts index 5c7d112c..92418ab5 100644 --- a/test/repo/integration/skills.test.mts +++ b/test/repo/integration/skills.test.mts @@ -6,7 +6,11 @@ import { expect, test } from 'vitest' import { EVENTS_EXTENSION } from '../../../lib/events.mts' import { createConfiguredServer } from '../../../lib/server.mts' -import { SKILLS_EXTENSION, WATCH_SKILL_URI } from '../../../lib/skills.mts' +import { + PATCH_SKILL_URI, + SKILLS_EXTENSION, + WATCH_SKILL_URI, +} from '../../../lib/skills.mts' const anything: StandardSchemaV1> = { '~standard': { @@ -41,32 +45,36 @@ test('advertises skills, events and resources together', async () => { await client.close() }) -test('skills/list manifest matches the bytes resources/read serves', async () => { +test('skills/list manifests match the bytes resources/read serves', async () => { const client = await connect() const list = await client.request( { method: 'skills/list', params: {} }, anything, ) const skills = list['skills'] as Array> - expect(skills).toHaveLength(1) - const [skill] = skills - expect(skill?.['uri']).toBe(WATCH_SKILL_URI) - expect(skill?.['frontmatter']['name']).toBe('watch-socket-alerts') + expect(skills.map(skill => skill['uri'])).toEqual([ + WATCH_SKILL_URI, + PATCH_SKILL_URI, + ]) expect(list['ttlMs']).toBeGreaterThan(0) - const read = await client.readResource({ uri: WATCH_SKILL_URI }) - const text = (read.contents[0] as { text: string }).text - expect(text.startsWith('---\nname: watch-socket-alerts\n')).toBe(true) - expect(skill?.['resources']).toEqual([ - { - uri: WATCH_SKILL_URI, - digest: `sha256:${createHash('sha256').update(text).digest('hex')}`, - size: Buffer.byteLength(text), - }, - ]) + for (const skill of skills) { + const name = skill['frontmatter']['name'] as string + expect(skill['uri']).toBe(`skill://socket/${name}/SKILL.md`) + const read = await client.readResource({ uri: skill['uri'] }) + const text = (read.contents[0] as { text: string }).text + expect(text.startsWith(`---\nname: ${name}\n`)).toBe(true) + expect(skill['resources']).toEqual([ + { + uri: skill['uri'], + digest: `sha256:${createHash('sha256').update(text).digest('hex')}`, + size: Buffer.byteLength(text), + }, + ]) + } const { resources } = await client.listResources() - expect(resources.map(r => r.uri)).toEqual([WATCH_SKILL_URI]) + expect(resources.map(r => r.uri)).toEqual([WATCH_SKILL_URI, PATCH_SKILL_URI]) await client.close() }) From 0575902a96f4de28f264a27651cefc6cd74be420 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Fri, 27 Nov 2026 20:44:14 -0300 Subject: [PATCH 6/7] fix(events): scope watches to a repo and poll only new alerts Event watches covered every repo in an org, and each poll read one unsorted page of 100 alerts, so in an org with more open alerts a new one could be missed entirely. - Both events take optional repo_slug and package arguments, mapped to the API's repoSlug and artifactName filters. - socket.alert.created asks only for alerts created since the previous poll (filters.alertCreatedAt.gte, with a 5 minute overlap) and follows every page through endCursor. - socket.patch.available fetches every patchable alert once as its baseline, then asks for patchable alerts updated since the previous poll, so an existing alert that gains a patch fires too. - The seen check runs per alert, so an id repeated within one poll is emitted once, and an alert created in the stream's first millisecond counts as existing. - watch-socket-alerts scopes watches to the current repo by default and passes only the severities the user names. --- README.md | 4 +- lib/alerts.mts | 10 + lib/events.mts | 312 ++++++++++++++++++-------- lib/skills.mts | 32 ++- test/repo/integration/events.test.mts | 159 +++++++++++-- 5 files changed, 398 insertions(+), 119 deletions(-) diff --git a/README.md b/README.md index 1d0223b3..1c9ee1f3 100644 --- a/README.md +++ b/README.md @@ -234,14 +234,14 @@ See the [organization and alerts example](docs/service.md#worked-example-organiz ### MCP Events and Skills: new-alert notifications (Beta) -The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer two events. Both take `org_slug` and an optional comma-separated `severity` filter. +The local stdio and `--http` servers implement the [MCP Events extension](https://modelcontextprotocol.io/extensions/events/overview) (`io.modelcontextprotocol/events`, SEP-3415). They offer two events. Both take `org_slug`, plus optional `repo_slug` (comma-separated Socket repo slugs; without it the watch covers every repo in the org), `package`, and comma-separated `severity` filters. | Event | Fires when | `data` | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `socket.alert.created` | A new alert appears in the org | `org_slug`, `alert` | | `socket.patch.available` | A new CVE alert has a [Socket Certified Patch](https://docs.socket.dev/docs/sca-patches) (`filters.cvePatchStatus=patch_available`) | `org_slug`, `alert`, `patches[]` with each patch's `uuid` and `purl` | -With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token and emits each alert it hasn't seen before. The first poll is the baseline, so alerts that already exist don't fire. +With push delivery (`events/stream`), the server polls `GET /v0/orgs/{org_slug}/alerts` with your own token. Each poll asks only for alerts created since the previous one (for `socket.patch.available`, patchable alerts updated since then), follows every page, and emits each alert once. Alerts that existed before the watch started don't fire; for the patch event, an existing alert that gains a patch does. The servers also implement the [MCP Skills extension](https://modelcontextprotocol.io/extensions/skills/overview) (`io.modelcontextprotocol/skills`) with two skills, served at `skill://socket//SKILL.md`: diff --git a/lib/alerts.mts b/lib/alerts.mts index a5031f1b..a67e783d 100644 --- a/lib/alerts.mts +++ b/lib/alerts.mts @@ -20,6 +20,10 @@ export interface AlertsFilters { repoSlug?: string | undefined // Comma-separated subset of: patch_unavailable,patch_available,patch_applied patchStatus?: string | undefined + // Only alerts created or updated at or after this time, as + // "YYYY-MM-DD HH:MM:SS" in UTC. + createdAtGte?: string | undefined + updatedAtGte?: string | undefined // 1..5000. The API caps at 5000 and defaults to 1000. perPage?: number | undefined // Pagination cursor from a previous response's endCursor @@ -70,6 +74,12 @@ export function buildAlertsQuery( if (f.patchStatus) { params.set('filters.cvePatchStatus', f.patchStatus) } + if (f.createdAtGte) { + params.set('filters.alertCreatedAt.gte', f.createdAtGte) + } + if (f.updatedAtGte) { + params.set('filters.alertUpdatedAt.gte', f.updatedAtGte) + } const perPage = f.perPage ?? perPageFallback if (typeof perPage === 'number') { params.set('per_page', String(perPage)) diff --git a/lib/events.mts b/lib/events.mts index 5a3a739d..e7ffe6ba 100644 --- a/lib/events.mts +++ b/lib/events.mts @@ -2,8 +2,9 @@ * @file MCP Events (SEP-3415, `io.modelcontextprotocol/events`, Beta) for the * local stdio and `--http` server. Two event types, `socket.alert.created` * and `socket.patch.available`, delivered by push only: `events/stream` - * polls the org alerts API with the caller's own token and emits each alert - * it has not seen before. + * polls the org alerts API with the caller's own token, asking only for + * alerts created (or, for patches, updated) since the previous poll, and + * emits each alert it has not emitted before. * The TypeScript SDK has no events support yet * (modelcontextprotocol/typescript-sdk#3209), so the two methods are plain * custom request handlers. Swap them for the SDK's API once it lands. @@ -40,6 +41,19 @@ export const PATCH_AVAILABLE_EVENT = 'socket.patch.available' const NOT_FOUND = -32_023 const FORBIDDEN = -32_024 +// Each poll looks back this far past the previous one, so an alert that is +// indexed a little after its timestamp is still found. Re-found alerts are +// deduped by id within a stream, and by eventId in the client after a resume. +export const POLL_OVERLAP_MS = 5 * 60 * 1000 +// The API allows up to 5000 per page; a time-filtered poll rarely needs more +// than one page. +const PAGE_SIZE = 1000 +// shortcut: stops after 20 pages (20,000 alerts) per poll and logs it; raise +// it if a single org can create more than that between two polls. +const MAX_PAGES = 20 + +const ARG_NAMES = ['org_slug', 'severity', 'repo_slug', 'package'] as const + const ALERT_INPUT_SCHEMA = { type: 'object', properties: { @@ -52,6 +66,15 @@ const ALERT_INPUT_SCHEMA = { description: 'Comma-separated severities to include: subset of low,medium,high,critical', }, + repo_slug: { + type: 'string', + description: + 'Comma-separated Socket repo slugs to watch, usually the repository name. Omit to watch every repo in the org', + }, + package: { + type: 'string', + description: 'Only alerts for this package name, e.g. "minimist"', + }, }, required: ['org_slug'], additionalProperties: false, @@ -68,7 +91,7 @@ const ALERT_PAYLOAD_PROPERTIES = { const ALERT_CREATED_DEFINITION = { name: ALERT_CREATED_EVENT, description: - 'A new Socket alert appeared for an organization you can access. Polls the org alerts API with your own token and fires once per new alert.', + 'A new Socket alert appeared in an organization you can access, optionally limited to some repos, a package, or severities. Polls the org alerts API with your own token and fires once per new alert.', delivery: ['push'], inputSchema: ALERT_INPUT_SCHEMA, payloadSchema: { @@ -81,7 +104,7 @@ const ALERT_CREATED_DEFINITION = { const PATCH_AVAILABLE_DEFINITION = { name: PATCH_AVAILABLE_EVENT, description: - 'A CVE alert that a Socket Certified Patch fixes appeared for an organization you can access. A certified patch backports the fix into the exact version in use, so nothing is upgraded. Apply one with `socket-patch get ` from the project root. Fires once per alert.', + 'A Socket Certified Patch became available for a CVE alert in an organization you can access: a new alert that has one, or an existing alert that just gained one. A certified patch backports the fix into the exact version in use, so nothing is upgraded. Apply one with `socket-patch get ` from the project root. Fires once per alert.', delivery: ['push'], inputSchema: ALERT_INPUT_SCHEMA, payloadSchema: { @@ -113,11 +136,17 @@ const EVENT_DEFINITIONS = [ALERT_CREATED_DEFINITION, PATCH_AVAILABLE_DEFINITION] export interface AlertCreatedArgs { org_slug: string severity?: string | undefined + repo_slug?: string | undefined + package?: string | undefined } -// What a source fetches: the event's arguments, plus whether only alerts -// with an available certified patch count. -export type AlertQuery = AlertCreatedArgs & { patchOnly?: boolean | undefined } +// What a source fetches: the event's arguments, whether only alerts with an +// available certified patch count, and an optional time window (ISO 8601). +export type AlertQuery = AlertCreatedArgs & { + patchOnly?: boolean | undefined + createdSince?: string | undefined + updatedSince?: string | undefined +} interface StreamParams { name: string @@ -168,60 +197,98 @@ export function parseStreamParams(value: unknown): StreamParams { if (typeof name !== 'string') { throw new Error('name must be a string') } - const args = isPlainObject(params['arguments']) ? params['arguments'] : {} - const orgSlug = args['org_slug'] - const severity = args['severity'] - if (typeof orgSlug !== 'string' || orgSlug === '') { - throw new Error('arguments.org_slug must be a non-empty string') - } - if (severity !== undefined && typeof severity !== 'string') { - throw new Error('arguments.severity must be a string') - } - const extra = Object.keys(args).filter( - key => key !== 'org_slug' && key !== 'severity', + const raw = isPlainObject(params['arguments']) ? params['arguments'] : {} + const extra = Object.keys(raw).filter( + key => !(ARG_NAMES as readonly string[]).includes(key), ) if (extra.length > 0) { throw new Error(`unknown arguments: ${extra.join(', ')}`) } + const args: Partial> = {} + for (const key of ARG_NAMES) { + const arg = raw[key] + if (arg !== undefined && typeof arg !== 'string') { + throw new Error(`arguments.${key} must be a string`) + } + if (arg) { + args[key] = arg + } + } + const orgSlug = args.org_slug + if (!orgSlug) { + throw new Error('arguments.org_slug must be a non-empty string') + } const cursor = params['cursor'] - if (cursor !== undefined && cursor !== null && typeof cursor !== 'string') { - throw new Error('cursor must be a string or null') + if (cursor !== undefined && cursor !== null) { + if (typeof cursor !== 'string' || Number.isNaN(Date.parse(cursor))) { + throw new Error('cursor must be a timestamp from this server, or null') + } } return { name, - arguments: { org_slug: orgSlug, ...(severity ? { severity } : {}) }, + arguments: { ...args, org_slug: orgSlug }, cursor: cursor ?? null, } } -function alertTime(alert: Alert): string | undefined { - const value = alert['createdAt'] ?? alert['created_at'] - return typeof value === 'string' ? value : undefined +function timeOf(alert: Alert, field: 'createdAt' | 'updatedAt'): string { + const value = alert[field] ?? alert['createdAt'] + return typeof value === 'string' ? value : '' } -// Live source: open alerts for the org, newest page only. -// shortcut: reads one page of 100, so a burst of >100 alerts between polls -// drops the overflow; page through `endCursor` if that matters. +// The API filters on "YYYY-MM-DD HH:MM:SS" in UTC. +function apiTime(iso: string): string { + return new Date(iso).toISOString().replace('T', ' ').slice(0, 19) +} + +/** + * Live source: open alerts for the org, matching the query, every page. A + * time window keeps each poll small, because the endpoint's order is not by + * time, so a single page could miss new alerts. + */ export const socketAlertSource: AlertSource = async ( - args, + query, token, userAgent, ) => { - const body = await fetchAlerts({ - baseUrl: SOCKET_API_BASE_URL, - orgSlug: args.org_slug, - authToken: token, - userAgent, - filters: { - status: 'open', - perPage: 100, - ...(args.severity ? { severity: args.severity } : {}), - ...(args.patchOnly ? { patchStatus: 'patch_available' } : {}), - }, - }) - const record = isPlainObject(body) ? body : {} - const items = record['items'] ?? record['results'] ?? [] - return toAlerts(Array.isArray(items) ? items : []) + const alerts: Alert[] = [] + let cursor: string | undefined + for (let page = 0; page < MAX_PAGES; page += 1) { + const body = await fetchAlerts({ + baseUrl: SOCKET_API_BASE_URL, + orgSlug: query.org_slug, + authToken: token, + userAgent, + filters: { + status: 'open', + perPage: PAGE_SIZE, + ...(query.severity ? { severity: query.severity } : {}), + ...(query.repo_slug ? { repoSlug: query.repo_slug } : {}), + ...(query.package ? { artifactName: query.package } : {}), + ...(query.patchOnly ? { patchStatus: 'patch_available' } : {}), + ...(query.createdSince + ? { createdAtGte: apiTime(query.createdSince) } + : {}), + ...(query.updatedSince + ? { updatedAtGte: apiTime(query.updatedSince) } + : {}), + ...(cursor ? { cursor } : {}), + }, + }) + const record = isPlainObject(body) ? body : {} + const items = record['items'] ?? record['results'] ?? [] + alerts.push(...toAlerts(Array.isArray(items) ? items : [])) + const next = record['endCursor'] + if (typeof next !== 'string' || !next) { + return alerts + } + cursor = next + } + logger.warn( + { org: query.org_slug, pages: MAX_PAGES }, + 'alerts poll stopped at the page limit', + ) + return alerts } // Keep objects that carry an `id` (or `key`), with the id as a string. @@ -237,6 +304,11 @@ function toAlerts(items: unknown[]): Alert[] { }) } +function alertLocations(alert: Alert): Array> { + const locations = Array.isArray(alert['locations']) ? alert['locations'] : [] + return locations.filter(isPlainObject) +} + /** * The certified patches an alert can use: its locations whose patch status is * `patch_available`, one entry per patch uuid. @@ -244,10 +316,9 @@ function toAlerts(items: unknown[]): Alert[] { export function availablePatches( alert: Alert, ): Array<{ uuid: string; purl?: string }> { - const locations = Array.isArray(alert['locations']) ? alert['locations'] : [] const patches = new Map() - for (const location of locations) { - if (!isPlainObject(location) || !isPlainObject(location['patch'])) { + for (const location of alertLocations(alert)) { + if (!isPlainObject(location['patch'])) { continue } const { uuid, status } = location['patch'] @@ -267,14 +338,57 @@ export function availablePatches( return [...patches.values()] } +// The same filters the API applies, for alerts from the demo file. +function matchesQuery(alert: Alert, query: AlertQuery): boolean { + const list = (value: string | undefined) => + value?.split(',').map(item => item.trim()) + const severities = list(query.severity) + if (severities && !severities.includes(String(alert['severity'] ?? ''))) { + return false + } + const locations = alertLocations(alert) + const repos = list(query.repo_slug) + if ( + repos && + !locations.some(location => { + const repo = isPlainObject(location['repository']) + ? location['repository']['slug'] + : undefined + return typeof repo === 'string' && repos.includes(repo) + }) + ) { + return false + } + if ( + query.package && + !locations.some( + location => + isPlainObject(location['artifact']) && + location['artifact']['name'] === query.package, + ) + ) { + return false + } + if (query.patchOnly && availablePatches(alert).length === 0) { + return false + } + if (query.createdSince && timeOf(alert, 'createdAt') < query.createdSince) { + return false + } + if (query.updatedSince && timeOf(alert, 'updatedAt') < query.updatedSince) { + return false + } + return true +} + /** * Demo source (SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE): no network and no token. - * Each poll reads alerts from a local NDJSON file, one alert object per line. - * Lines already in the file when a stream opens are its baseline, so - * appending a line fires exactly one event on cue. + * Each poll reads alerts from a local NDJSON file, one alert object per line, + * and applies the same filters as the API. Give each line a current + * `createdAt` so it counts as new. */ export function fileAlertSource(file: string): AlertSource { - return async args => { + return async query => { let text = '' try { text = await readFile(file, 'utf8') @@ -288,13 +402,7 @@ export function fileAlertSource(file: string): AlertSource { return [] } }) - const wanted = args.severity?.split(',').map(s => s.trim()) - return toAlerts(parsed) - .filter( - alert => !wanted || wanted.includes(String(alert['severity'] ?? '')), - ) - .filter(alert => !args.patchOnly || availablePatches(alert).length > 0) - .reverse() + return toAlerts(parsed).filter(alert => matchesQuery(alert, query)) } } @@ -344,29 +452,34 @@ export function registerEventHandlers( return streamAlerts(params, ctx, { pollMs, heartbeatMs, - poll: () => - source( - { - ...params.arguments, - patchOnly: params.name === PATCH_AVAILABLE_EVENT, - }, - token ?? '', - userAgent, - ), + poll: query => source(query, token ?? '', userAgent), }) }, ) } /** - * Run one push subscription until the client cancels it. Dedup is by alert - * id within the stream; the cursor is the newest `createdAt` emitted, so a - * reconnect with it skips everything at or before that time. + * Run one push subscription until the client cancels it. + * + * - `socket.alert.created` asks for alerts created since the previous poll (minus + * the overlap) and never emits one created before the stream started, unless + * the client resumed from a cursor. + * - `socket.patch.available` first fetches every currently patchable alert as the + * baseline, then asks for patchable alerts updated since the previous poll, + * which also catches an existing alert that just gained a patch. + * + * The cursor is the start time of the last completed poll. A resume replays + * from the cursor minus the overlap, so delivery is at least once, and the + * client dedupes on `eventId`. */ export async function streamAlerts( params: StreamParams, ctx: ServerContext, - opts: { pollMs: number; heartbeatMs: number; poll: () => Promise }, + opts: { + pollMs: number + heartbeatMs: number + poll: (query: AlertQuery) => Promise + }, ): Promise<{ _meta: Record }> { const { signal } = ctx.mcpReq const meta = { [SUBSCRIPTION_ID_META_KEY]: ctx.mcpReq.id } @@ -375,16 +488,29 @@ export async function streamAlerts( method: `notifications/events/${method}`, params: { ...body, _meta: meta }, }) - const seen = new Set() - // With no client cursor, whatever the first poll returns is the baseline. + const patchEvent = params.name === PATCH_AVAILABLE_EVENT + const timeField = patchEvent ? 'updatedAt' : 'createdAt' + const startedAt = new Date().toISOString() const resumed = params.cursor !== null - let cursor = params.cursor ?? new Date().toISOString() - let baseline = true + let cursor = params.cursor ?? startedAt + let needsBaseline = patchEvent && !resumed + const seen = new Set() const tick = async (): Promise => { + const pollStart = new Date().toISOString() + const since = new Date(Date.parse(cursor) - POLL_OVERLAP_MS).toISOString() + const window = needsBaseline + ? {} + : patchEvent + ? { updatedSince: since } + : { createdSince: since } let alerts: Alert[] try { - alerts = await opts.poll() + alerts = await opts.poll({ + ...params.arguments, + patchOnly: patchEvent, + ...window, + }) } catch (error) { const status = error instanceof UpstreamHttpError ? error.status : 0 const payload = { @@ -401,37 +527,39 @@ export async function streamAlerts( await notify('error', payload) return true } - // Oldest first, so the cursor only moves forward. - const fresh = alerts.filter(alert => !seen.has(alert.id)).reverse() - for (const alert of fresh) { + const ordered = alerts.toSorted((a, b) => + timeOf(a, timeField).localeCompare(timeOf(b, timeField)), + ) + for (const alert of ordered) { + // Checked per alert: one poll can return the same id twice, for + // example when results shift between pages. + if (seen.has(alert.id)) { + continue + } seen.add(alert.id) - const time = alertTime(alert) - // On the first poll emit only what is newer than the client's cursor. - if (baseline && (!resumed || !time || time <= cursor)) { + if (needsBaseline) { continue } - if (time && time > cursor) { - cursor = time + // The overlap window reaches back before the stream started; those + // alerts already existed when the user subscribed. + if (!resumed && !patchEvent && timeOf(alert, 'createdAt') <= startedAt) { + continue } await notify('event', { eventId: `${params.arguments.org_slug}:${alert.id}`, name: params.name, - timestamp: time ?? new Date().toISOString(), + timestamp: timeOf(alert, timeField) || pollStart, data: { org_slug: params.arguments.org_slug, alert, - ...(params.name === PATCH_AVAILABLE_EVENT - ? { patches: availablePatches(alert) } - : {}), + ...(patchEvent ? { patches: availablePatches(alert) } : {}), }, cursor, }) } - if (baseline) { - baseline = false - } else if (fresh.length === 0) { - await notify('heartbeat', { cursor }) - } + needsBaseline = false + cursor = pollStart + await notify('heartbeat', { cursor }) return true } diff --git a/lib/skills.mts b/lib/skills.mts index 0e99bfdc..adb1a7be 100644 --- a/lib/skills.mts +++ b/lib/skills.mts @@ -36,18 +36,32 @@ nobody is looking at the session. | \`socket.alert.created\` | A new alert appears in the org | \`org_slug\`, \`alert\` | | \`socket.patch.available\` | A new CVE alert has a Socket Certified Patch | \`org_slug\`, \`alert\`, \`patches[]\` (\`uuid\`, \`purl\`) | -Both take \`org_slug\` (required) and \`severity\` (optional, comma-separated -subset of \`low,medium,high,critical\`). Existing alerts never fire: only alerts -that appear after the automation starts do. +Arguments for both: + +| Argument | Required | Meaning | +| --- | --- | --- | +| \`org_slug\` | yes | The Socket organization | +| \`repo_slug\` | no | Comma-separated Socket repo slugs. Without it, the watch covers every repo in the org | +| \`package\` | no | Only alerts for this package name | +| \`severity\` | no | Comma-separated subset of \`low,medium,high,critical\` | + +Existing alerts never fire: only alerts that appear after the automation +starts do. \`socket.patch.available\` also fires when an existing alert gains a +patch. ## Steps 1. Get the organization slug. Call this server's \`organizations\` tool, or ask the user if they belong to several. -2. Pick the event. Use \`socket.patch.available\` when the user wants fixes +2. Scope the watch to the current project. Pass \`repo_slug\`: the Socket repo + slug is usually the repository name, from the git remote or, without one, + the project directory's name. Watch the whole org only if the user asks + for it, and say so when you confirm. +3. Pick the event. Use \`socket.patch.available\` when the user wants fixes they can apply now, and \`socket.alert.created\` for everything else. Pass - \`severity\` when the user names one. -3. Create the automation with the client's automation tool. In OpenCode: + \`severity\` or \`package\` only when the user names one, with exactly the + values they named: "high" is \`high\`, not \`high,critical\`. +4. Create the automation with the client's automation tool. In OpenCode: \`\`\`js automation_create({ @@ -56,7 +70,7 @@ that appear after the automation starts do. type: 'event', server: '', event: 'socket.patch.available', - args: { org_slug: '', severity: 'high,critical' }, + args: { org_slug: '', repo_slug: '' }, }, action: { type: 'prompt', @@ -67,8 +81,8 @@ that appear after the automation starts do. \`\`\` OpenCode exposes the current session id as \`$OPENCODE_SESSION_ID\`. -4. Tell the user what you set up, and that deleting this session pauses the - automation. +5. Tell the user what you set up, including the repo it watches, and that + deleting this session pauses the automation. ## Prompt for the action diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts index 678482ed..48e16e4b 100644 --- a/test/repo/integration/events.test.mts +++ b/test/repo/integration/events.test.mts @@ -116,21 +116,24 @@ test('advertises the events extension and lists socket.alert.created', async () }) test('events/stream emits a new alert exactly once', async () => { - const old = alert('a1', '2026-11-01T00:00:00.000Z') - const fresh = alert('a2', '2026-11-02T00:00:00.000Z') + const before = alert('a1', new Date(Date.now() - 60_000).toISOString()) + const fresh = alert('a2', new Date(Date.now() + 60_000).toISOString()) + const queries: Array> = [] const scope = nock(API) .matchHeader('authorization', 'Bearer tok') .get('/v0/orgs/my-org/alerts') - .query({ - 'filters.alertStatus': 'open', - 'filters.alertSeverity': 'critical', - per_page: '100', + .query(q => { + queries.push(q as Record) + return true }) - .reply(200, { items: [old] }) + .reply(200, { items: [before] }) .get('/v0/orgs/my-org/alerts') - .query(true) + .query(q => { + queries.push(q as Record) + return true + }) .times(3) - .reply(200, { items: [fresh, old] }) + .reply(200, { items: [fresh, before] }) const { client, notes } = await connect() const { controller, done } = openStream(client, { @@ -141,8 +144,20 @@ test('events/stream emits a new alert exactly once', async () => { controller.abort() await done + // Every poll is time-filtered, so it never pages through old alerts. + for (const q of queries) { + expect(q).toMatchObject({ + 'filters.alertStatus': 'open', + 'filters.alertSeverity': 'critical', + per_page: '1000', + }) + expect(q['filters.alertCreatedAt.gte']).toMatch( + /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/u, + ) + } const events = notes.filter(n => n.method === 'notifications/events/event') expect(notes[0]?.method).toBe('notifications/events/active') + // a1 was created before the stream started, so only a2 fires, once. expect(events).toHaveLength(1) expect(events[0]?.params).toMatchObject({ eventId: 'my-org:a2', @@ -156,6 +171,49 @@ test('events/stream emits a new alert exactly once', async () => { await client.close() }) +test('events/stream scopes polls to a repo and package, and follows pages', async () => { + const fresh = (id: string) => + alert(id, new Date(Date.now() + 60_000).toISOString()) + const scoped = { + 'filters.alertStatus': 'open', + 'filters.repoSlug': 'socket-events-demo', + 'filters.artifactName': 'minimist', + per_page: '1000', + } + const scope = nock(API) + .get('/v0/orgs/my-org/alerts') + .query( + q => + q['startAfterCursor'] === undefined && + Object.entries(scoped).every(([k, v]) => q[k] === v), + ) + .reply(200, { items: [fresh('p1')], endCursor: 'page-2' }) + .get('/v0/orgs/my-org/alerts') + .query( + q => + q['startAfterCursor'] === 'page-2' && + Object.entries(scoped).every(([k, v]) => q[k] === v), + ) + .reply(200, { items: [fresh('p2')], endCursor: null }) + const { client, notes } = await connect() + const { controller, done } = openStream(client, { + org_slug: 'my-org', + repo_slug: 'socket-events-demo', + package: 'minimist', + }) + await vi.waitFor( + () => + expect( + notes.filter(n => n.method === 'notifications/events/event'), + ).toHaveLength(2), + { timeout: 5000 }, + ) + controller.abort() + await done + expect(scope.isDone()).toBe(true) + await client.close() +}) + test('events/stream rejects an unknown event name', async () => { const { client } = await connect() const { done } = openStream(client, { org_slug: 'my-org' }, 'nope') @@ -268,17 +326,27 @@ test('socket.patch.available fires only for alerts with a certified patch', asyn rmSync(dir, { recursive: true, force: true }) }) -test('socket.patch.available asks the API for patchable alerts only', async () => { +test('socket.patch.available baselines, then fires when an alert gains a patch', async () => { + const queries: Array> = [] + const record = (q: object) => { + queries.push(q as Record) + return true + } const scope = nock(API) .matchHeader('authorization', 'Bearer tok') .get('/v0/orgs/my-org/alerts') - .query({ - 'filters.alertStatus': 'open', - 'filters.cvePatchStatus': 'patch_available', - per_page: '100', + .query(record) + .reply(200, { items: [patchable('already-patchable', 'patch-0')] }) + .get('/v0/orgs/my-org/alerts') + .query(record) + .times(2) + .reply(200, { + items: [ + patchable('already-patchable', 'patch-0'), + patchable('gained-patch', 'patch-1'), + ], }) - .reply(200, { items: [] }) - const { client } = await connect() + const { client, notes } = await connect() const { controller, done } = openStream( client, { org_slug: 'my-org' }, @@ -287,5 +355,64 @@ test('socket.patch.available asks the API for patchable alerts only', async () = await vi.waitFor(() => expect(scope.isDone()).toBe(true), { timeout: 5000 }) controller.abort() await done + + // The baseline fetches every patchable alert; later polls only recent ones. + expect(queries[0]).toMatchObject({ + 'filters.alertStatus': 'open', + 'filters.cvePatchStatus': 'patch_available', + per_page: '1000', + }) + expect(queries[0]?.['filters.alertUpdatedAt.gte']).toBeUndefined() + for (const q of queries.slice(1)) { + expect(q['filters.cvePatchStatus']).toBe('patch_available') + expect(q['filters.alertUpdatedAt.gte']).toMatch(/^\d{4}-\d{2}-\d{2} /u) + } + const events = notes.filter(n => n.method === 'notifications/events/event') + expect(events.map(n => n.params['eventId'])).toEqual(['my-org:gained-patch']) + expect(events[0]?.params).toMatchObject({ + data: { patches: [{ uuid: 'patch-1', purl: 'pkg:npm/minimist@1.2.2' }] }, + }) await client.close() }) + +test('fake-alerts file applies the repo filter', async () => { + const dir = mkdtempSync(path.join(tmpdir(), 'mcp-events-')) + const file = path.join(dir, 'alerts.ndjson') + writeFileSync(file, '') + process.env['SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE'] = file + setStaticApiKey('') + const { client, notes } = await connect() + const { controller, done } = openStream(client, { + org_slug: 'demo', + repo_slug: 'this-repo', + }) + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(1)) + const inRepo = (id: string, slug: string) => + JSON.stringify({ + id, + createdAt: new Date().toISOString(), + locations: [{ repository: { slug } }], + }) + appendFileSync( + file, + `${inRepo('other', 'other-repo')}\n${inRepo('mine', 'this-repo')}\n`, + ) + await vi.waitFor( + () => + expect( + notes.filter(n => n.method === 'notifications/events/event'), + ).toHaveLength(1), + { timeout: 5000 }, + ) + const heartbeats = notes.length + await vi.waitFor(() => expect(notes.length).toBeGreaterThan(heartbeats + 2)) + controller.abort() + await done + expect( + notes + .filter(n => n.method === 'notifications/events/event') + .map(n => n.params['eventId']), + ).toEqual(['demo:mine']) + await client.close() + rmSync(dir, { recursive: true, force: true }) +}) From d00e0fda0ddb5a73dfbbd31aa56e0220e4107754 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Mon, 30 Nov 2026 13:27:38 -0300 Subject: [PATCH 7/7] fix(events): finish every page before moving the poll cursor A poll that hit the 20-page cap advanced the stream cursor and ended the patch baseline, so alerts on later pages could age out of the overlap unseen. Each tick now fetches up to 20 pages; when more remain, the next tick continues from the page cursor with the same time window, and the cursor moves only after the last page. Heartbeats keep running while a poll is in flight, and each alerts request carries the stream's abort signal and a 30s timeout. The fake-alerts file treats only ENOENT as "no alerts yet"; other read errors are reported and the same window is retried. The apply-socket-patch skill no longer tells the agent to run an advisory's exploit payload from the project root. --- lib/alerts.mts | 10 +- lib/events.mts | 144 +++++++++++++++++++------- lib/skills.mts | 6 +- test/repo/integration/events.test.mts | 144 ++++++++++++++++++++++++++ 4 files changed, 260 insertions(+), 44 deletions(-) diff --git a/lib/alerts.mts b/lib/alerts.mts index a67e783d..ce23bbf1 100644 --- a/lib/alerts.mts +++ b/lib/alerts.mts @@ -38,6 +38,10 @@ export interface FetchAlertsConfig { // Socket access token, sent as `Authorization: Bearer ` when set. authToken?: string | undefined extraHeaders?: Record | undefined + // Cancels the request, for example when an events stream closes. + signal?: AbortSignal | undefined + // Per-request timeout in milliseconds. + timeout?: number | undefined } /** @@ -100,7 +104,11 @@ export async function fetchAlerts(config: FetchAlertsConfig): Promise { const qs = buildAlertsQuery(config.filters).toString() const url = `${baseUrl}/v0/orgs/${encodeURIComponent(config.orgSlug)}/alerts${qs ? `?${qs}` : ''}` - const res = await httpRequest(url, { headers: buildJsonApiHeaders(config) }) + const res = await httpRequest(url, { + headers: buildJsonApiHeaders(config), + ...(config.signal ? { signal: config.signal } : {}), + ...(config.timeout ? { timeout: config.timeout } : {}), + }) if (!res.ok) { throw new UpstreamHttpError( res.status, diff --git a/lib/events.mts b/lib/events.mts index e7ffe6ba..3ec76c3b 100644 --- a/lib/events.mts +++ b/lib/events.mts @@ -48,9 +48,13 @@ export const POLL_OVERLAP_MS = 5 * 60 * 1000 // The API allows up to 5000 per page; a time-filtered poll rarely needs more // than one page. const PAGE_SIZE = 1000 -// shortcut: stops after 20 pages (20,000 alerts) per poll and logs it; raise -// it if a single org can create more than that between two polls. -const MAX_PAGES = 20 +// Pages fetched per tick. A poll with more pages continues on the next tick +// from the page cursor, with the same time window, before the stream cursor +// moves, so heartbeats keep flowing and no page is skipped. +export const MAX_PAGES = 20 +// Per-request timeout for the alerts API. A timeout is a recoverable error, +// and the next tick retries the same page and window. +const REQUEST_TIMEOUT_MS = 30_000 const ARG_NAMES = ['org_slug', 'severity', 'repo_slug', 'package'] as const @@ -156,11 +160,18 @@ interface StreamParams { export type Alert = Record & { id: string } +export interface AlertBatch { + alerts: Alert[] + // Page cursor to continue the same query from; absent on the last page. + next?: string | undefined +} + export type AlertSource = ( query: AlertQuery, token: string, userAgent: string, -) => Promise + page?: { cursor?: string | undefined; signal?: AbortSignal | undefined }, +) => Promise export interface EventsOptions { // Poll interval for `events/stream`. @@ -242,23 +253,27 @@ function apiTime(iso: string): string { } /** - * Live source: open alerts for the org, matching the query, every page. A - * time window keeps each poll small, because the endpoint's order is not by - * time, so a single page could miss new alerts. + * Live source: open alerts for the org, matching the query, up to MAX_PAGES + * pages from `page.cursor`. A time window keeps each poll small, because the + * endpoint's order is not by time, so a single page could miss new alerts. + * When more pages remain, the batch carries the cursor to continue from. */ export const socketAlertSource: AlertSource = async ( query, token, userAgent, + page = {}, ) => { const alerts: Alert[] = [] - let cursor: string | undefined - for (let page = 0; page < MAX_PAGES; page += 1) { + let cursor = page.cursor + for (let count = 0; count < MAX_PAGES; count += 1) { const body = await fetchAlerts({ baseUrl: SOCKET_API_BASE_URL, orgSlug: query.org_slug, authToken: token, userAgent, + timeout: REQUEST_TIMEOUT_MS, + ...(page.signal ? { signal: page.signal } : {}), filters: { status: 'open', perPage: PAGE_SIZE, @@ -280,15 +295,15 @@ export const socketAlertSource: AlertSource = async ( alerts.push(...toAlerts(Array.isArray(items) ? items : [])) const next = record['endCursor'] if (typeof next !== 'string' || !next) { - return alerts + return { alerts } } cursor = next } - logger.warn( + logger.info( { org: query.org_slug, pages: MAX_PAGES }, - 'alerts poll stopped at the page limit', + 'alerts poll continues on the next tick', ) - return alerts + return { alerts, next: cursor } } // Keep objects that carry an `id` (or `key`), with the id as a string. @@ -392,8 +407,14 @@ export function fileAlertSource(file: string): AlertSource { let text = '' try { text = await readFile(file, 'utf8') - } catch { - // No file yet means no alerts yet. + } catch (error) { + // Only a missing file means no alerts yet. Other errors go to tick(), + // which reports them and retries the same window. + if ( + !(error instanceof Error && 'code' in error && error.code === 'ENOENT') + ) { + throw error + } } const parsed = text.split('\n').flatMap(line => { try { @@ -402,7 +423,9 @@ export function fileAlertSource(file: string): AlertSource { return [] } }) - return toAlerts(parsed).filter(alert => matchesQuery(alert, query)) + return { + alerts: toAlerts(parsed).filter(alert => matchesQuery(alert, query)), + } } } @@ -452,7 +475,7 @@ export function registerEventHandlers( return streamAlerts(params, ctx, { pollMs, heartbeatMs, - poll: query => source(query, token ?? '', userAgent), + poll: (query, page) => source(query, token ?? '', userAgent, page), }) }, ) @@ -468,6 +491,10 @@ export function registerEventHandlers( * baseline, then asks for patchable alerts updated since the previous poll, * which also catches an existing alert that just gained a patch. * + * A poll with more than MAX_PAGES pages finishes over several ticks: each one + * continues from the page cursor with the same time window, and the stream + * cursor moves only after the last page. + * * The cursor is the start time of the last completed poll. A resume replays * from the cursor minus the overlap, so delivery is at least once, and the * client dedupes on `eventId`. @@ -478,7 +505,10 @@ export async function streamAlerts( opts: { pollMs: number heartbeatMs: number - poll: (query: AlertQuery) => Promise + poll: ( + query: AlertQuery, + page: { cursor?: string | undefined; signal: AbortSignal }, + ) => Promise }, ): Promise<{ _meta: Record }> { const { signal } = ctx.mcpReq @@ -495,23 +525,46 @@ export async function streamAlerts( let cursor = params.cursor ?? startedAt let needsBaseline = patchEvent && !resumed const seen = new Set() - - const tick = async (): Promise => { - const pollStart = new Date().toISOString() - const since = new Date(Date.parse(cursor) - POLL_OVERLAP_MS).toISOString() - const window = needsBaseline - ? {} - : patchEvent - ? { updatedSince: since } - : { createdSince: since } - let alerts: Alert[] - try { - alerts = await opts.poll({ + // A poll that has more pages: its window, start time and page cursor. + let pending: { + query: AlertQuery + pollStart: string + page: string + } | null = null + + // 'more' means the current poll has pages left. + const tick = async (): Promise<'closed' | 'done' | 'more'> => { + let query: AlertQuery + let pollStart: string + if (pending) { + ;({ query, pollStart } = pending) + } else { + pollStart = new Date().toISOString() + const since = new Date(Date.parse(cursor) - POLL_OVERLAP_MS).toISOString() + query = { ...params.arguments, patchOnly: patchEvent, - ...window, + ...(needsBaseline + ? {} + : patchEvent + ? { updatedSince: since } + : { createdSince: since }), + } + } + // A long poll must not starve heartbeats: clients drop a quiet stream. + const beat = setInterval(() => { + void notify('heartbeat', { cursor }).catch(() => {}) + }, opts.heartbeatMs) + let batch: AlertBatch + try { + batch = await opts.poll(query, { + ...(pending ? { cursor: pending.page } : {}), + signal, }) } catch (error) { + if (signal.aborted) { + return 'closed' + } const status = error instanceof UpstreamHttpError ? error.status : 0 const payload = { error: { @@ -522,12 +575,15 @@ export async function streamAlerts( } if (status === 401 || status === 403) { await notify('terminated', payload) - return false + return 'closed' } + // Keep `pending` and `cursor`: the next tick retries the same window. await notify('error', payload) - return true + return 'done' + } finally { + clearInterval(beat) } - const ordered = alerts.toSorted((a, b) => + const ordered = batch.alerts.toSorted((a, b) => timeOf(a, timeField).localeCompare(timeOf(b, timeField)), ) for (const alert of ordered) { @@ -557,10 +613,16 @@ export async function streamAlerts( cursor, }) } + if (batch.next) { + pending = { query, pollStart, page: batch.next } + await notify('heartbeat', { cursor }) + return 'more' + } + pending = null needsBaseline = false cursor = pollStart await notify('heartbeat', { cursor }) - return true + return 'done' } logger.info({ event: params.name }, 'events stream opened') @@ -569,18 +631,20 @@ export async function streamAlerts( truncated: false, heartbeatMs: opts.heartbeatMs, }) - let open = await tick() + let state = await tick() let lastPoll = Date.now() - while (open && !signal.aborted) { - const untilPoll = Math.max(0, lastPoll + opts.pollMs - Date.now()) + while (state !== 'closed' && !signal.aborted) { + // Pages left: continue right away instead of waiting a full interval. + const untilPoll = + state === 'more' ? 0 : Math.max(0, lastPoll + opts.pollMs - Date.now()) try { await sleep(Math.min(opts.heartbeatMs, untilPoll), undefined, { signal }) } catch { break } - if (Date.now() >= lastPoll + opts.pollMs) { + if (state === 'more' || Date.now() >= lastPoll + opts.pollMs) { lastPoll = Date.now() - open = await tick() + state = await tick() } else { await notify('heartbeat', { cursor }) } diff --git a/lib/skills.mts b/lib/skills.mts index adb1a7be..ba339f75 100644 --- a/lib/skills.mts +++ b/lib/skills.mts @@ -163,9 +163,9 @@ Commit what the CLI reports, together: \`.socket/vendor/\`, the lockfile, - \`socket-patch list\` shows the patch, its mode, and the files it changed. - \`socket-patch vex\` should report the CVE as \`not_affected\`. -- If you test the exploit, use the advisory's real payload, and show that it - succeeds on the unpatched version first. A check that passes on both - versions proves nothing. +- Run the upstream regression test for the fix in an isolated fixture, then + run the project's tests against the patched dependency. Never run an + advisory's exploit payload from the project root. ## 5. Roll back diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts index 48e16e4b..7b70327c 100644 --- a/test/repo/integration/events.test.mts +++ b/test/repo/integration/events.test.mts @@ -10,6 +10,7 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest' import { ALERT_CREATED_EVENT, EVENTS_EXTENSION, + MAX_PAGES, PATCH_AVAILABLE_EVENT, } from '../../../lib/events.mts' import { @@ -416,3 +417,146 @@ test('fake-alerts file applies the repo filter', async () => { await client.close() rmSync(dir, { recursive: true, force: true }) }) + +// Replies MAX_PAGES full pages, then a last page with `last`, then `after` +// for every later poll. Records every query. +function overCap( + queries: Array>, + page: (n: number) => Record, + last: Record, + after: Record, +) { + const record = (q: object) => { + queries.push(q as Record) + return true + } + let scope = nock(API) + for (let n = 1; n <= MAX_PAGES; n += 1) { + scope = scope + .get('/v0/orgs/my-org/alerts') + .query(record) + .reply(200, { items: [page(n)], endCursor: `c${n}` }) + } + return scope + .get('/v0/orgs/my-org/alerts') + .query(record) + .reply(200, { items: [last] }) + .get('/v0/orgs/my-org/alerts') + .query(record) + .times(2) + .reply(200, { items: [after] }) +} + +test('a poll over the page cap finishes before the cursor moves', async () => { + const future = () => new Date(Date.now() + 60_000).toISOString() + const queries: Array> = [] + const scope = overCap( + queries, + n => alert(`p${n}`, future()), + alert('last-page', future()), + alert('later', future()), + ) + const { client, notes } = await connect() + const { controller, done } = openStream(client, { org_slug: 'my-org' }) + await vi.waitFor(() => expect(scope.isDone()).toBe(true), { timeout: 5000 }) + controller.abort() + await done + + const first = queries.slice(0, MAX_PAGES + 1) + const gte = first[0]?.['filters.alertCreatedAt.gte'] + // Every page of the first poll keeps the same window and follows the cursor. + first.forEach((q, i) => { + expect(q['filters.alertCreatedAt.gte']).toBe(gte) + expect(q['startAfterCursor']).toBe(i === 0 ? undefined : `c${i}`) + }) + expect(queries[MAX_PAGES + 1]?.['startAfterCursor']).toBeUndefined() + const ids = notes + .filter(n => n.method === 'notifications/events/event') + .map(n => n.params['eventId']) + expect(ids).toContain('my-org:last-page') + expect(ids).toContain('my-org:later') + expect(ids).toHaveLength(MAX_PAGES + 2) + await client.close() +}) + +test('a patch baseline over the page cap covers every page', async () => { + const queries: Array> = [] + const scope = overCap( + queries, + n => patchable(`old${n}`, `patch-${n}`), + patchable('old-last-page', 'patch-last'), + patchable('gained', 'patch-new'), + ) + const { client, notes } = await connect() + const { controller, done } = openStream( + client, + { org_slug: 'my-org' }, + PATCH_AVAILABLE_EVENT, + ) + await vi.waitFor(() => expect(scope.isDone()).toBe(true), { timeout: 5000 }) + controller.abort() + await done + + for (const q of queries.slice(0, MAX_PAGES + 1)) { + expect(q['filters.alertUpdatedAt.gte']).toBeUndefined() + } + expect(queries[MAX_PAGES]?.['startAfterCursor']).toBe(`c${MAX_PAGES}`) + expect(queries[MAX_PAGES + 1]?.['filters.alertUpdatedAt.gte']).toMatch( + /^\d{4}-/u, + ) + // The alert on the last baseline page is part of the baseline, not new. + const ids = notes + .filter(n => n.method === 'notifications/events/event') + .map(n => n.params['eventId']) + expect(ids).toEqual(['my-org:gained']) + await client.close() +}) + +test('a fake-alerts file that cannot be read reports an error', async () => { + const dir = mkdtempSync(path.join(tmpdir(), 'mcp-events-')) + // A directory where the file should be: reading it fails with EISDIR. + process.env['SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE'] = dir + setStaticApiKey('') + const { client, notes } = await connect() + const { controller, done } = openStream(client, { org_slug: 'demo' }) + await vi.waitFor( + () => + expect(notes.some(n => n.method === 'notifications/events/error')).toBe( + true, + ), + { timeout: 5000 }, + ) + controller.abort() + await done + // The stream cursor never moved past the failed window. + const active = notes[0]?.params['cursor'] + for (const n of notes.filter( + m => m.method === 'notifications/events/heartbeat', + )) { + expect(n.params['cursor']).toBe(active) + } + await client.close() + rmSync(dir, { recursive: true, force: true }) +}) + +test('events/stream heartbeats while a poll is in flight', async () => { + process.env['SOCKET_MCP_EVENTS_POLL_MS'] = '60000' + process.env['SOCKET_MCP_EVENTS_HEARTBEAT_MS'] = '20' + nock(API) + .get('/v0/orgs/my-org/alerts') + .query(true) + .delay(2000) + .reply(200, { items: [] }) + const { client, notes } = await connect() + const { controller, done } = openStream(client, { org_slug: 'my-org' }) + await vi.waitFor( + () => + expect( + notes.filter(n => n.method === 'notifications/events/heartbeat').length, + ).toBeGreaterThan(3), + { timeout: 1000 }, + ) + controller.abort() + await done + await client.close() +})