Repository navigation
feat(events): add MCP Events and Skills for new Socket alerts and certified patches - #245
Gerardo Sabetta (gerardosabetta) wants to merge 7 commits into
Conversation
PR SummaryMedium Risk Overview Adds MCP Skills with
Reviewed by Cursor Bugbot for commit 0837fb9. Configure here. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 0837fb9. Configure here.
John-David Dalton (jdalton)
left a comment
There was a problem hiding this comment.
[agent] Please keep the polling window open until every page has been processed. The current checkpoint can permanently skip alerts on busy organizations.
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.
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.
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.
…s 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 <uuid>`. 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.
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.
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.
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.
0837fb9 to
d00e0fd
Compare
John-David Dalton (jdalton)
left a comment
There was a problem hiding this comment.
See suggestions
John-David Dalton (jdalton)
left a comment
There was a problem hiding this comment.
Inline review comments for the event delivery and protocol issues.
| return streamAlerts(params, ctx, { | ||
| pollMs, | ||
| heartbeatMs, | ||
| poll: (query, page) => source(query, token ?? '', userAgent, page), |
There was a problem hiding this comment.
The token is resolved once when the stream opens, then captured by this callback for the life of the subscription. In stdio mode, if the CLI refreshes its login token while this stream stays open, every later poll still sends the expired token and the watch terminates with 401. Resolve the token when each poll runs so long-lived watches follow token rotation.
| poll: (query, page) => source(query, token ?? '', userAgent, page), | |
| poll: (query, page) => | |
| source( | |
| query, | |
| resolveScopedAuthToken(ctx.http?.authInfo?.token) ?? '', | |
| userAgent, | |
| page, | |
| ), |
| continue | ||
| } | ||
| seen.add(alert.id) | ||
| if (needsBaseline) { |
There was a problem hiding this comment.
This unconditionally discards every alert returned by the patch baseline. If an existing alert gains a patch while the baseline request is in flight, that alert can be included in this baseline and then omitted from the next updated-since poll, so the subscriber never hears about it. Keep baseline alerts older than the subscription suppressed, but emit alerts updated after the subscription began.
| if (needsBaseline) { | |
| if (needsBaseline && timeOf(alert, 'updatedAt') <= startedAt) { | |
| 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) { |
There was a problem hiding this comment.
The API timestamp filter is truncated to whole seconds, but this comparison uses the stream start time with milliseconds. An alert created later in the same second as the subscription can therefore be returned by the API and then dropped here. Use a strict comparison so same-second alerts are delivered; the API cannot distinguish which came first within that second.
| if (!resumed && !patchEvent && timeOf(alert, 'createdAt') <= startedAt) { | |
| if (!resumed && !patchEvent && timeOf(alert, 'createdAt') < startedAt) { |
| const timeField = patchEvent ? 'updatedAt' : 'createdAt' | ||
| const startedAt = new Date().toISOString() | ||
| const resumed = params.cursor !== null | ||
| let cursor = params.cursor ?? startedAt |
There was a problem hiding this comment.
A resumed stream uses the client cursor directly and never applies SEP-3415 maxAgeMs. I reproduced a one-minute-old alert being replayed with maxAgeMs: 1000; the five-minute overlap also allows it through, and active reports truncated: false. Parse maxAgeMs, clamp the replay start to the requested window, and set truncated when older history is skipped.
| let cursor = params.cursor ?? startedAt | |
| let cursor = params.cursor === null | |
| ? startedAt | |
| : clampReplayCursor(params.cursor, params.maxAgeMs, startedAt) |
| data: { | ||
| org_slug: params.arguments.org_slug, | ||
| alert, | ||
| ...(patchEvent ? { patches: availablePatches(alert) } : {}), |
There was a problem hiding this comment.
For a repo-scoped watch, the API filters which alerts match but still returns all locations for each alert. availablePatches(alert) then includes patch UUIDs from locations in other repos the caller can access. Filter the patch locations by the requested repo slugs before building this payload.
| ...(patchEvent ? { patches: availablePatches(alert) } : {}), | |
| ...(patchEvent | |
| ? { patches: availablePatches(alert, params.arguments.repo_slug) } | |
| : {}), |
| () => ({ events: EVENT_DEFINITIONS }), | ||
| ) | ||
|
|
||
| server.setRequestHandler( |
There was a problem hiding this comment.
SEP-3415 requires Mcp-Name on events/stream over Streamable HTTP. This custom handler is registered without that check, and the pinned SDK's built-in validation does not cover custom Events methods, so HTTP clients can open a stream that the spec says must be rejected. Validate the header before dispatching this handler.
| server.setRequestHandler( | |
| 'events/stream', | |
| { | |
| params: passthrough(parseStreamParams), | |
| validateRequest: requireMcpNameHeader, | |
| }, |
|
[agent] Posted by Matt's AI review agent (Claude in Cursor), at his request. Live polling will likely miss most real alerts. Each poll asks for alerts whose Trace (socket-mcp at d00e0fd, depscan master)
|
John-David Dalton (jdalton)
left a comment
There was a problem hiding this comment.
The pagination and heartbeat fixes are present. The current review still has open event-delivery and protocol items. I found one additional issue in the demo instructions.
| 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 |
There was a problem hiding this comment.
The watch skips alerts created before its stream started, so the fixed timestamp prevents this sample from firing when readers run it today. Generate the timestamp at append time.
| 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 | |
| printf '{"id":"demo-1","type":"cve","severity":"high","artifact":{"type":"npm","name":"lodash","version":"4.17.20"},"createdAt":"%s"}\n' "$(node -p 'new Date().toISOString()')" >> .socket/fake-alerts.ndjson |
John-David Dalton (jdalton)
left a comment
There was a problem hiding this comment.
[agent] Please cover cancellation during delivery with a test that cancels after the first event in a multi-alert batch and asserts that no second event is sent.
| const ordered = batch.alerts.toSorted((a, b) => | ||
| timeOf(a, timeField).localeCompare(timeOf(b, timeField)), | ||
| ) | ||
| for (const alert of ordered) { |
There was a problem hiding this comment.
[agent] Cancellation can arrive while the first notification is being sent. Check before processing the next alert so the rest of the batch is skipped.
| for (const alert of ordered) { | |
| for (const alert of ordered) { | |
| if (signal.aborted) { | |
| return 'closed' | |
| } |

Implements a demoable MVP of MCP Events (SEP-3415,
io.modelcontextprotocol/events, Beta, protocol 2026-07-28) and MCP Skills (io.modelcontextprotocol/skills) for the local stdio and--httpserver. Hosted is out of scope. Tracks SURF-2271 and SURF-2272.What changed
Events (
lib/events.mts, new). The server advertises the extension undercapabilities.extensions, so it appears on bothinitializeandserver/discover.events/listreturns two events. Both takeorg_slug, plus optionalrepo_slug,packageand comma-separatedseverity, mapped to the API'srepoSlug,artifactNameandalertSeverityfilters:socket.alert.createdfires for new alerts.socket.patch.availablefires for CVE alerts with an available Socket Certified Patch (filters.cvePatchStatus=patch_available), including an existing alert that gains one. Its payload addspatches[]with each patch'suuidandpurl(fromlocations[].patch), ready forsocket-patch get <uuid>.Push delivery (
events/stream). The stream sendsnotifications/events/active, then pollsGET /v0/orgs/{org}/alertswith the caller's own token everySOCKET_MCP_EVENTS_POLL_MS(default 60s). The endpoint doesn't sort by time, so each poll is time-filtered and follows every page throughendCursor:socket.alert.createdasks for alerts created since the previous poll (filters.alertCreatedAt.gte, with a 5-minute overlap for indexing delay). Alerts created before the stream started never fire.socket.patch.availablefetches every patchable alert once as its baseline, then asks for patchable alerts updated since the previous poll (filters.alertUpdatedAt.gte).eventId(OpenCode does).SOCKET_MCP_EVENTS_HEARTBEAT_MS(default 10s). A 401 or 403 sendsterminated, and other upstream errors send a recoverableerror. Cancelling stops the loop.Skills (
lib/skills.mts, new). The server advertises the skills extension andresources, and ships two skills atskill://socket/<name>/SKILL.md:watch-socket-alertsteaches an agent to find the org, pick the right event, and create the automation, with a reaction prompt for each event.apply-socket-patchteaches thesocket-patchworkflow with or without an event: find, preview, pick vendored or hosted mode (pnpm 11+ caveats), reinstall cleanly, verify withlist,vexand the upstream regression test in an isolated fixture (never an exploit payload from the project root), and roll back.skills/listandskills/getreturn manifests with sha256 digests and sizes. EachSKILL.mdis served throughresources/listandresources/read.Demo mode.
SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE=<path>reads alerts from a local NDJSON file instead of the API, with no token and no network. Lines already in the file when a stream opens are the baseline, and each appended line fires once.Other files.
lib/alerts.mtsgains apatchStatusfilter.lib/server.mtsgains two imports and two calls,registerEventHandlersandregisterSkillHandlers. The README gains an events and skills section, with an OpenCode recipe.The stream is notify-only. Creating PRs from events is SURF-2273.
Heads-up for reviewers
@modelcontextprotocol/server2.0.0 has no events or skills API (events: draft feat: Events extension (SEP-3415) modelcontextprotocol/typescript-sdk#3209). All four methods are custom handlers registered with the 3-argumentsetRequestHandler, and params are validated by hand. Swap them for the SDK API once it lands../error-reporting.mtsimport inlib/server.mts; both sides are kept.resources, which the skills spec requires. It serves only the skill file.updatedAt. I haven't confirmed that in depscan; if it doesn't, such an alert only fires after its next update.events/poll, webhooks andlist_changedare not implemented.workspaces/api-v0/src/endpoints/orgs/alerts/list.tsandlist-schema.ts(items,endCursor,locations[].patch,sort: undefined), and the stateful alert field definitions inanalytics-shared(cvePatchStatus,alertCreatedAtandalertUpdatedAtwithgte).pnpm run mcp:schema:checkstill passes. Real stdio clients list resources fine on both 2025-11-25 and 2026-07-28 (checked by hand).Demo (verified with OpenCode 2.4.2)
The demo project is a small pnpm Express app that pins
minimist@1.2.2(CVE-2021-44906, which has a real free certified patch). Its projectopencode.jsonpoints at this build in file mode and turns on OpenCode's experimentalmcp_skillsflag, which is required for OpenCode to load MCP skills.skill socket:watch-socket-alerts. It then created an automation onsocket.patch.availablewhose prompt previews the patch and waits.pnpm socket:alertappends a critical minimist alert carrying the real patch uuid. About 3 seconds later the session woke up, confirmedminimist@1.2.2is a direct dependency used insrc/server.js, ransocket-patch get <uuid> --dry-run, and stopped to wait.socket-patch listshows the patch;socket-patch vexreportsnot_affected;Testing
pnpm test, rebased on main: 76 files and 709 tests pass. They cover:test/repo/integration/events.test.mts):events/listreturns both events;-32023for an unknown event;socket.patch.availablefires only for patchable alerts, withpatches[];repoSlugandartifactName, and followsendCursorpages;test/repo/integration/skills.test.mts):resources/readserves;skills/getandresources/readreturn-32602for unknown URIs.pnpm run checkis clean, andpnpm run mcp:schema:checkmatches the golden.socket.alert.createdwithrepo_slugandseverity: high, andsocket.patch.availablewithrepo_slug. Each received only its own alert.SOCKET_API_BASE_URLat an unreachable local port and passes a placeholder token, so an agent calling the org tools during a demo can't reach the real Socket API. A patch question with no events involved ("can we fix CVE-2021-44906 with a certified patch? preview only") loadedsocket:apply-socket-patch, previewed the patch, chose vendored mode for pnpm 12, and changed nothing.Slides