diff --git a/README.md b/README.md index e9c98214..1c9ee1f3 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,70 @@ 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 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`, 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. 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`: + +- `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 | +| ------------------------------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 in your project. Use absolute paths, because the desktop app doesn't inherit your shell's `PATH`: + + ```sh + 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 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: + + ```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. 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 See [client rule examples](docs/service.md#adjusting-tool-usage-via-client-rules). diff --git a/lib/alerts.mts b/lib/alerts.mts index 8ac6b85c..ce23bbf1 100644 --- a/lib/alerts.mts +++ b/lib/alerts.mts @@ -18,6 +18,12 @@ 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 + // 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 @@ -32,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 } /** @@ -65,6 +75,15 @@ export function buildAlertsQuery( if (f.repoSlug) { params.set('filters.repoSlug', f.repoSlug) } + 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)) @@ -85,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 new file mode 100644 index 00000000..3ec76c3b --- /dev/null +++ b/lib/events.mts @@ -0,0 +1,654 @@ +/** + * @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, 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. + */ +import { readFile } from 'node:fs/promises' +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 { envInt, envString } 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' +export const PATCH_AVAILABLE_EVENT = 'socket.patch.available' + +// Spec error codes (SEP-3415). +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 +// 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 + +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', + }, + 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, +} + +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 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: { + type: 'object', + properties: ALERT_PAYLOAD_PROPERTIES, + required: ['org_slug', 'alert'], + }, +} + +const PATCH_AVAILABLE_DEFINITION = { + name: PATCH_AVAILABLE_EVENT, + description: + '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: { + type: 'object', + properties: { + ...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', 'patches'], + }, +} + +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, 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 + arguments: AlertCreatedArgs + cursor: string | null +} + +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, + page?: { cursor?: string | undefined; signal?: AbortSignal | undefined }, +) => Promise + +export interface EventsOptions { + // Poll interval for `events/stream`. + pollMs?: number | undefined + // Heartbeat interval, capped at the poll interval. + heartbeatMs?: 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 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) { + 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: { ...args, org_slug: orgSlug }, + cursor: cursor ?? null, + } +} + +function timeOf(alert: Alert, field: 'createdAt' | 'updatedAt'): string { + const value = alert[field] ?? alert['createdAt'] + return typeof value === 'string' ? value : '' +} + +// 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, 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 = 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, + ...(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.info( + { org: query.org_slug, pages: MAX_PAGES }, + 'alerts poll continues on the next tick', + ) + return { alerts, next: cursor } +} + +// 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 [] + } + const id = item['id'] ?? item['key'] + return typeof id === 'string' || typeof id === 'number' + ? [{ ...item, id: String(id) }] + : [] + }) +} + +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. + */ +export function availablePatches( + alert: Alert, +): Array<{ uuid: string; purl?: string }> { + const patches = new Map() + for (const location of alertLocations(alert)) { + if (!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()] +} + +// 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, + * 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 query => { + let text = '' + try { + text = await readFile(file, 'utf8') + } 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 { + return line.trim() ? [JSON.parse(line) as unknown] : [] + } catch { + return [] + } + }) + return { + alerts: toAlerts(parsed).filter(alert => matchesQuery(alert, query)), + } + } +} + +/** + * 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 + // 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 fakeFile = envString('SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE') + const fake = fakeFile !== undefined + const source = + options.source ?? (fake ? fileAlertSource(fakeFile) : socketAlertSource) + const userAgent = options.userAgent ?? '' + + server.registerCapabilities({ extensions: { [EVENTS_EXTENSION]: {} } }) + + server.setRequestHandler( + 'events/list', + { params: passthrough(value => value) }, + () => ({ events: EVENT_DEFINITIONS }), + ) + + server.setRequestHandler( + 'events/stream', + { params: passthrough(parseStreamParams) }, + async (params, ctx) => { + if (!EVENT_DEFINITIONS.some(event => event.name === params.name)) { + 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, + heartbeatMs, + poll: (query, page) => source(query, token ?? '', userAgent, page), + }) + }, + ) +} + +/** + * 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. + * + * 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`. + */ +export async function streamAlerts( + params: StreamParams, + ctx: ServerContext, + opts: { + pollMs: number + heartbeatMs: number + poll: ( + query: AlertQuery, + page: { cursor?: string | undefined; signal: AbortSignal }, + ) => 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 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 ?? startedAt + let needsBaseline = patchEvent && !resumed + const seen = new Set() + // 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, + ...(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: { + 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 'closed' + } + // Keep `pending` and `cursor`: the next tick retries the same window. + await notify('error', payload) + return 'done' + } finally { + clearInterval(beat) + } + const ordered = batch.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) + if (needsBaseline) { + continue + } + // 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: timeOf(alert, timeField) || pollStart, + data: { + org_slug: params.arguments.org_slug, + alert, + ...(patchEvent ? { patches: availablePatches(alert) } : {}), + }, + 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 'done' + } + + logger.info({ event: params.name }, 'events stream opened') + await notify('active', { + cursor, + truncated: false, + heartbeatMs: opts.heartbeatMs, + }) + let state = await tick() + let lastPoll = 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 (state === 'more' || Date.now() >= lastPoll + opts.pollMs) { + lastPoll = Date.now() + state = await tick() + } else { + await notify('heartbeat', { cursor }) + } + } + logger.info({ event: params.name }, 'events stream closed') + return { _meta: meta } +} diff --git a/lib/server.mts b/lib/server.mts index 07d41fbf..930e35f8 100644 --- a/lib/server.mts +++ b/lib/server.mts @@ -14,6 +14,8 @@ import { resolveMcpClient, 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, @@ -184,6 +186,9 @@ export function createConfiguredServer( }, ) + registerEventHandlers(server, { userAgent }) + registerSkillHandlers(server) + server.setRequestHandler('tools/list', () => ({ __proto__: null, tools: specs.map(toToolListEntry), diff --git a/lib/skills.mts b/lib/skills.mts new file mode 100644 index 00000000..ba339f75 --- /dev/null +++ b/lib/skills.mts @@ -0,0 +1,269 @@ +/** + * @file MCP Skills (`io.modelcontextprotocol/skills`, Beta) for the local + * 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 each skill's 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' +export const PATCH_SKILL_URI = 'skill://socket/apply-socket-patch/SKILL.md' + +const INVALID_PARAMS = -32_602 +// Skills only change when socket-mcp ships, so clients may cache them. +const CACHE = { ttlMs: 60 * 60 * 1000, cacheScope: 'public' } + +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.' + +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 +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\`) | + +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. 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\` 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({ + name: 'socket-alerts', + trigger: { + type: 'event', + server: '', + event: 'socket.patch.available', + args: { org_slug: '', repo_slug: '' }, + }, + action: { + type: 'prompt', + prompt: '', + to: { session: '' }, + }, + }) + \`\`\` + + OpenCode exposes the current session id as \`$OPENCODE_SESSION_ID\`. +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 + +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. 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 + +\`\`\`sh +socket-patch get --mode vendored +rm -rf node_modules && pnpm install # or the project's install command +\`\`\` + +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. + +Commit what the CLI reports, together: \`.socket/vendor/\`, the lockfile, +\`package.json\`, and \`pnpm-workspace.yaml\` when it was written. + +## 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\`. +- 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 + +\`socket-patch rollback\` restores the upstream packages. In vendored mode, +\`socket-patch vendor --revert\` also works. Reinstall afterwards. +` + +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': { + 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 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 +} + +/** + * 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: SKILLS.map(s => s.entry), ...CACHE }), + ) + + server.setRequestHandler( + 'skills/get', + { params: uriParams() }, + ({ uri }) => ({ + skill: findSkill(uri).entry, + ...CACHE, + }), + ) + + server.setRequestHandler('resources/list', () => ({ + resources: SKILLS.map(({ entry }) => ({ + uri: entry.uri, + name: entry.frontmatter.name, + description: entry.frontmatter.description, + mimeType: 'text/markdown', + })), + })) + + server.setRequestHandler('resources/read', request => { + const { entry, text } = findSkill(request.params.uri) + return { contents: [{ uri: entry.uri, mimeType: 'text/markdown', text }] } + }) +} diff --git a/test/repo/integration/events.test.mts b/test/repo/integration/events.test.mts new file mode 100644 index 00000000..7b70327c --- /dev/null +++ b/test/repo/integration/events.test.mts @@ -0,0 +1,562 @@ +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' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' + +import { + ALERT_CREATED_EVENT, + EVENTS_EXTENSION, + MAX_PAGES, + PATCH_AVAILABLE_EVENT, +} 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_ALERTS_FILE'] + delete process.env['SOCKET_MCP_EVENTS_HEARTBEAT_MS'] + setStaticApiKey('') +}) + +test('advertises the events extension and lists socket.alert.created', async () => { + const { client } = await connect() + expect(client.getServerCapabilities()?.extensions).toMatchObject({ + [EVENTS_EXTENSION]: {}, + }) + const result = await client.request( + { method: 'events/list', params: {} }, + anything, + ) + const events = result['events'] as Array> + expect(events.map(e => e['name'])).toEqual([ + ALERT_CREATED_EVENT, + PATCH_AVAILABLE_EVENT, + ]) + 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 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(q => { + queries.push(q as Record) + return true + }) + .reply(200, { items: [before] }) + .get('/v0/orgs/my-org/alerts') + .query(q => { + queries.push(q as Record) + return true + }) + .times(3) + .reply(200, { items: [fresh, before] }) + + 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 + + // 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', + 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 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') + expect(await done).toMatchObject({ code: -32_023 }) + await client.close() +}) + +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 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 + 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 () => { + 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() +}) + +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 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(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'), + ], + }) + 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 + + // 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 }) +}) + +// 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() +}) diff --git a/test/repo/integration/skills.test.mts b/test/repo/integration/skills.test.mts new file mode 100644 index 00000000..92418ab5 --- /dev/null +++ b/test/repo/integration/skills.test.mts @@ -0,0 +1,98 @@ +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 { + PATCH_SKILL_URI, + 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 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.map(skill => skill['uri'])).toEqual([ + WATCH_SKILL_URI, + PATCH_SKILL_URI, + ]) + expect(list['ttlMs']).toBeGreaterThan(0) + + 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, PATCH_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() +})