Skip to content

feat(events): add MCP Events and Skills for new Socket alerts and certified patches - #245

Open
Gerardo Sabetta (gerardosabetta) wants to merge 7 commits into
mainfrom
surf-2271-mcp-events-mvp
Open

Gerardo Sabetta (gerardosabetta) wants to merge 7 commits into
mainfrom
surf-2271-mcp-events-mvp

Conversation

@gerardosabetta

@gerardosabetta Gerardo Sabetta (gerardosabetta) commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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 --http server. Hosted is out of scope. Tracks SURF-2271 and SURF-2272.

What changed

  • Events (lib/events.mts, new). The server advertises the extension under capabilities.extensions, so it appears on both initialize and server/discover. events/list returns two events. Both take org_slug, plus optional repo_slug, package and comma-separated severity, mapped to the API's repoSlug, artifactName and alertSeverity filters:

    • socket.alert.created fires for new alerts.
    • socket.patch.available fires for CVE alerts with an available Socket Certified Patch (filters.cvePatchStatus=patch_available), including an existing alert that gains one. Its payload adds patches[] with each patch's uuid and purl (from locations[].patch), ready for socket-patch get <uuid>.
  • Push delivery (events/stream). The stream sends notifications/events/active, then polls GET /v0/orgs/{org}/alerts with the caller's own token every SOCKET_MCP_EVENTS_POLL_MS (default 60s). The endpoint doesn't sort by time, so each poll is time-filtered and follows every page through endCursor:

    • socket.alert.created asks 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.available fetches every patchable alert once as its baseline, then asks for patchable alerts updated since the previous poll (filters.alertUpdatedAt.gte).
    • Each alert id is emitted once per stream. A resume replays from the cursor minus the overlap; that's at-least-once delivery, and the client dedupes on eventId (OpenCode does).
    • Heartbeats run on their own clock, every SOCKET_MCP_EVENTS_HEARTBEAT_MS (default 10s). A 401 or 403 sends terminated, and other upstream errors send a recoverable error. Cancelling stops the loop.
  • Skills (lib/skills.mts, new). The server advertises the skills extension and resources, and ships two skills at skill://socket/<name>/SKILL.md:

    • watch-socket-alerts teaches an agent to find the org, pick the right event, and create the automation, with a reaction prompt for each event.
    • apply-socket-patch teaches the socket-patch workflow with or without an event: find, preview, pick vendored or hosted mode (pnpm 11+ caveats), reinstall cleanly, verify with list, vex and the upstream regression test in an isolated fixture (never an exploit payload from the project root), and roll back.

    skills/list and skills/get return manifests with sha256 digests and sizes. Each SKILL.md is served through resources/list and resources/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.mts gains a patchStatus filter. lib/server.mts gains two imports and two calls, registerEventHandlers and registerSkillHandlers. 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

  • No SDK support yet. @modelcontextprotocol/server 2.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-argument setRequestHandler, and params are validated by hand. Swap them for the SDK API once it lands.
  • Rebased on main after the Sentry tracing work (feat(http): trace tool calls to Sentry #246). The only conflict was the ./error-reporting.mts import in lib/server.mts; both sides are kept.
  • The server now declares resources, which the skills spec requires. It serves only the skill file.
  • Remaining shortcuts:
    • A tick fetches at most 20 pages of 1000 alerts. A poll with more pages continues on the next tick from the page cursor with the same time window, and the stream cursor moves only after the last page. Heartbeats keep running while a poll is in flight, and each request has a 30s timeout and stops when the stream closes.
    • Dedupe is in memory, per stream.
    • The patch event assumes that gaining a patch bumps the alert's updatedAt. I haven't confirmed that in depscan; if it doesn't, such an alert only fires after its next update.
    • events/poll, webhooks and list_changed are not implemented.
  • The alert shape and filters were checked against depscan's code, not the live API. I read workspaces/api-v0/src/endpoints/orgs/alerts/list.ts and list-schema.ts (items, endCursor, locations[].patch, sort: undefined), and the stateful alert field definitions in analytics-shared (cvePatchStatus, alertCreatedAt and alertUpdatedAt with gte).
  • mcp-tada's probe logs "resources/list failed: Method not found", but pnpm run mcp:schema:check still 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 project opencode.json points at this build in file mode and turns on OpenCode's experimental mcp_skills flag, which is required for OpenCode to load MCP skills.

  1. Ask in plain words: "Watch this project's Socket org for new vulnerabilities that have a Socket Certified Patch. When one arrives, preview the patch and wait for my go-ahead." OpenCode's first tool call was skill socket:watch-socket-alerts. It then created an automation on socket.patch.available whose prompt previews the patch and waits.
  2. Fire the alert: pnpm socket:alert appends a critical minimist alert carrying the real patch uuid. About 3 seconds later the session woke up, confirmed minimist@1.2.2 is a direct dependency used in src/server.js, ran socket-patch get <uuid> --dry-run, and stopped to wait.
  3. Approve it: "Go ahead: apply it in vendored mode, reinstall, and verify." The agent vendored the patch, reinstalled, and verified it:
    • socket-patch list shows the patch;
    • socket-patch vex reports not_affected;
    • the prototype pollution exploit no longer works;
    • the app still boots.

Testing

  • pnpm test, rebased on main: 76 files and 709 tests pass. They cover:
    • Events (test/repo/integration/events.test.mts):
      • events/list returns both events;
      • a new alert is emitted exactly once over nock-mocked polls;
      • -32023 for an unknown event;
      • fake-file baseline, severity filter and dedupe;
      • heartbeats between slow polls;
      • socket.patch.available fires only for patchable alerts, with patches[];
      • every poll is time-filtered, scoped by repoSlug and artifactName, and follows endCursor pages;
      • the patch event baselines everything patchable, then fires only for an alert that gains a patch;
      • the fake file applies the repo filter;
      • a normal poll and a patch baseline over the 20-page limit each finish every page before the cursor moves;
      • an unreadable fake file reports an error and keeps the same window;
      • heartbeats keep flowing while a slow poll is in flight.
    • Skills (test/repo/integration/skills.test.mts):
      • capabilities advertise events, skills and resources together;
      • both skills are listed, and each manifest digest matches the bytes resources/read serves;
      • skills/get and resources/read return -32602 for unknown URIs.
  • pnpm run check is clean, and pnpm run mcp:schema:check matches the golden.
  • End to end in OpenCode 2.4.2, as described in the Demo section above. In the latest run, two conversations set up their own watches from the skill: socket.alert.created with repo_slug and severity: high, and socket.patch.available with repo_slug. Each received only its own alert.
  • The demo's server config points SOCKET_API_BASE_URL at 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") loaded socket:apply-socket-patch, previewed the patch, chose vendored mode for pnpm 12, and changed nothing.
  • Not covered: the live Socket alerts API, which was never called with a real token. The patch step made unauthenticated requests to Socket's public patch service.

Slides

cover

gap

flow

skills

wire

demo

headsup

verify

Gerardo Sabetta (gerardosabetta) added a commit that referenced this pull request Nov 27, 2026
@gerardosabetta Gerardo Sabetta (gerardosabetta) changed the title feat(events): add MCP Events push stream for new Socket alerts feat(events): add MCP Events and Skills for new Socket alerts and certified patches Nov 27, 2026
Gerardo Sabetta (gerardosabetta) added a commit that referenced this pull request Nov 28, 2026
@gerardosabetta
Gerardo Sabetta (gerardosabetta) marked this pull request as ready for review November 28, 2026 00:11
@cursor

cursor Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

PR Summary

Medium Risk
Introduces long-lived event streams and repeated org-scoped API polling with user credentials; behavior is new and substantial though gated by existing auth and covered by integration tests.

Overview
Adds MCP Events (Beta) to the local stdio/--http server so clients can subscribe via events/stream to socket.alert.created and socket.patch.available. Push delivery polls the org alerts API with the caller's token (time-filtered pages, dedupe, heartbeats), with optional NDJSON demo mode via SOCKET_MCP_EVENTS_FAKE_ALERTS_FILE.

Adds MCP Skills with watch-socket-alerts and apply-socket-patch, exposed through skills/list, skills/get, and resources/read at skill://socket/.../SKILL.md. lib/server.mts wires both extensions at boot.

lib/alerts.mts gains patchStatus, createdAtGte, and updatedAtGte filters for event polling. The README documents events, skills, env tuning, and an OpenCode automation recipe. New integration tests cover streaming, patch baselines, fake alerts, and skill manifests.

Reviewed by Cursor Bugbot for commit 0837fb9. Configure here.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ 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.

Comment thread lib/events.mts Resolved

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[agent] Please keep the polling window open until every page has been processed. The current checkpoint can permanently skip alerts on busy organizations.

Comment thread lib/events.mts Resolved
Comment thread lib/events.mts Resolved
Comment thread lib/skills.mts Resolved
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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See suggestions

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline review comments for the event delivery and protocol issues.

Comment thread lib/events.mts
return streamAlerts(params, ctx, {
pollMs,
heartbeatMs,
poll: (query, page) => source(query, token ?? '', userAgent, page),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
poll: (query, page) => source(query, token ?? '', userAgent, page),
poll: (query, page) =>
source(
query,
resolveScopedAuthToken(ctx.http?.authInfo?.token) ?? '',
userAgent,
page,
),

Comment thread lib/events.mts
continue
}
seen.add(alert.id)
if (needsBaseline) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
if (needsBaseline) {
if (needsBaseline && timeOf(alert, 'updatedAt') <= startedAt) {
continue
}

Comment thread lib/events.mts
}
// The overlap window reaches back before the stream started; those
// alerts already existed when the user subscribed.
if (!resumed && !patchEvent && timeOf(alert, 'createdAt') <= startedAt) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
if (!resumed && !patchEvent && timeOf(alert, 'createdAt') <= startedAt) {
if (!resumed && !patchEvent && timeOf(alert, 'createdAt') < startedAt) {

Comment thread lib/events.mts
const timeField = patchEvent ? 'updatedAt' : 'createdAt'
const startedAt = new Date().toISOString()
const resumed = params.cursor !== null
let cursor = params.cursor ?? startedAt

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
let cursor = params.cursor ?? startedAt
let cursor = params.cursor === null
? startedAt
: clampReplayCursor(params.cursor, params.maxAgeMs, startedAt)

Comment thread lib/events.mts
data: {
org_slug: params.arguments.org_slug,
alert,
...(patchEvent ? { patches: availablePatches(alert) } : {}),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
...(patchEvent ? { patches: availablePatches(alert) } : {}),
...(patchEvent
? { patches: availablePatches(alert, params.arguments.repo_slug) }
: {}),

Comment thread lib/events.mts
() => ({ events: EVENT_DEFINITIONS }),
)

server.setRequestHandler(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
server.setRequestHandler(
'events/stream',
{
params: passthrough(parseStreamParams),
validateRequest: requireMcpNameHeader,
},

@MattStypa

Copy link
Copy Markdown

[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 createdAt is within 5 minutes of the previous poll (POLL_OVERLAP_MS), but depscan stamps createdAt with the scan time and only writes the alert row later: by default 30 minutes after the first snapshot on paid orgs, 24 hours on free. An alert that surfaces with a createdAt older than the window is never delivered. Worth confirming against the live alerts API, which the PR says was not called.

Trace (socket-mcp at d00e0fd, depscan master)
  • lib/alerts.mts sends createdAtGte as filters.alertCreatedAt.gte, which filters on stateful_alerts.alert_created_at (workspaces/analytics-shared/src/api/fields/field-definitions.ts).
  • workspaces/analytics/src/stateful-alerts/runCreateStatefulAlertsJob.ts fills alert_created_at and alert_updated_at from consolidated_alerts.scanned_at, not from the time the job runs. runUpdateStatefulAlertsJob.ts does the same for alert_updated_at, which the socket.patch.available window uses.
  • enqueueRealtimeStatefulAlertsJob.ts delays that job by statefulAlertsRealtimeMinIntervalSecondsPaid (default 30 * 60) or ...Free (default 24 * 60 * 60) after the first snapshot. Later snapshots fold into the same run, so only alerts scanned in the last few minutes before it fires fit the window.
  • In tick(), since = cursor - POLL_OVERLAP_MS, and for a fresh socket.alert.created stream the createdAt <= startedAt check also drops any alert scanned before the stream opened, even if it only became visible afterwards.
  • Not checked: the actual lag in production, the feature-flag values there, and orgs that are not on the realtime stateful-alerts path.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread README.md
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread lib/events.mts
const ordered = batch.alerts.toSorted((a, b) =>
timeOf(a, timeField).localeCompare(timeOf(b, timeField)),
)
for (const alert of ordered) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
for (const alert of ordered) {
for (const alert of ordered) {
if (signal.aborted) {
return 'closed'
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants