Skip to content

Commit e860eae

Browse files
Add dune query alert for the MCP's setQueryAlert
core#8168 added setQueryAlert to the Dune MCP server. 'dune query alert' calls it: it sets the query's schedule and creates or replaces the alert for one channel (email, Slack, Discord, or a webhook). The result carries no webhook URL, so the command prints it as it is. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a2147b-3c2e-76b3-aeaf-0aafbe53d879
1 parent a62760f commit e860eae

4 files changed

Lines changed: 190 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ Manage and execute Dune queries.
5757
| `query archive <query-id>` | Archive a saved query |
5858
| `query run <query-id> [--param key=value] [--performance small\|medium\|large] [--limit] [--timeout] [--no-wait]` | Execute a saved query and display results |
5959
| `query run-sql --sql <sql> [--param key=value] [--performance small\|medium\|large] [--limit] [--timeout] [--no-wait]` | Execute raw SQL directly |
60+
| `query alert <query-id> --cron <expr> --performance small\|medium\|large --email <addr>... \| --slack-webhook <url> \| --discord-webhook <url> \| --webhook <url>` | Schedule a query and get notified each time a run returns rows |
6061

6162
### `dune matview` (alias: `mv`)
6263

‎cmd/query/alert.go‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
package query
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"strconv"
7+
8+
"github.com/duneanalytics/cli/cmdutil"
9+
"github.com/duneanalytics/cli/output"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
// alertChannels maps each channel flag to the channel type setQueryAlert takes.
14+
var alertChannels = map[string]string{
15+
"slack-webhook": "slack",
16+
"discord-webhook": "discord",
17+
"webhook": "webhook",
18+
}
19+
20+
func newAlertCmd() *cobra.Command {
21+
cmd := &cobra.Command{
22+
Use: "alert <query-id>",
23+
Short: "Notify you each time a saved query's scheduled run returns rows",
24+
Long: `Put a saved query on a schedule and send a notification each time a run
25+
returns rows. This sets the query's schedule (creating it or replacing its
26+
frequency and tier) and creates or replaces the alert for the chosen channel.
27+
28+
Write the query so it returns rows only when the event happened in the latest
29+
period, such as the last hour for an hourly schedule.
30+
31+
Choose one channel:
32+
--email a@x.com --email b@x.com up to 5 addresses
33+
--slack-webhook <url> Slack incoming webhook
34+
--discord-webhook <url> Discord webhook
35+
--webhook <url> HTTPS URL that receives a JSON POST per fire
36+
37+
- A query has one alert per channel; this replaces that channel's alert.
38+
- Every scheduled run is charged credits at --performance, so use the smallest
39+
tier and the lowest frequency that catch the event in time.
40+
- You need to own the query or be an editor or admin of the team that owns it.
41+
The owner's plan limits how many queries can have alerts and schedules.
42+
- Recipients receive the query name, a link to it and its charts.
43+
44+
Supported cron expressions (5-part, UTC):
45+
"*/15 * * * *", "*/20 * * * *", "*/30 * * * *" every 15, 20 or 30 minutes
46+
"0 * * * *" hourly
47+
"0 */N * * *" with N in 2, 3, 4, 6, 8, 12 every N hours
48+
"M H * * *" daily at H:M
49+
"M H * * D" weekly on day D (0 = Sunday)
50+
where M is 0 or 30 and H is 0-23.
51+
52+
To stop the schedule, use 'dune schedule delete --query-id <id>'.
53+
54+
Examples:
55+
dune query alert 12345 --cron "0 * * * *" --performance small --email me@example.com
56+
dune query alert 12345 --cron "*/30 * * * *" --performance small --slack-webhook "$SLACK_URL"`,
57+
Args: cobra.ExactArgs(1),
58+
RunE: runAlert,
59+
}
60+
61+
cmd.Flags().String("cron", "", "when to run, as a supported 5-part UTC cron expression (required)")
62+
cmd.Flags().String("performance", "", `engine tier for each run: "small", "medium", or "large" (required)`)
63+
cmd.Flags().StringArray("email", nil, "address to notify; repeat for up to 5")
64+
cmd.Flags().String("slack-webhook", "", "Slack incoming webhook URL")
65+
cmd.Flags().String("discord-webhook", "", "Discord webhook URL")
66+
cmd.Flags().String("webhook", "", "HTTPS URL that receives a JSON POST for each fire")
67+
_ = cmd.MarkFlagRequired("cron")
68+
_ = cmd.MarkFlagRequired("performance")
69+
cmd.MarkFlagsOneRequired("email", "slack-webhook", "discord-webhook", "webhook")
70+
cmd.MarkFlagsMutuallyExclusive("email", "slack-webhook", "discord-webhook", "webhook")
71+
output.AddFormatFlag(cmd, "text")
72+
73+
return cmd
74+
}
75+
76+
func runAlert(cmd *cobra.Command, args []string) error {
77+
queryID, err := strconv.Atoi(args[0])
78+
if err != nil || queryID <= 0 {
79+
return fmt.Errorf("invalid query ID %q: must be a positive integer", args[0])
80+
}
81+
82+
var channel map[string]any
83+
if cmd.Flags().Changed("email") {
84+
emails, _ := cmd.Flags().GetStringArray("email")
85+
channel = map[string]any{"type": "email", "emails": emails}
86+
}
87+
for flag, typ := range alertChannels {
88+
if cmd.Flags().Changed(flag) {
89+
url, _ := cmd.Flags().GetString(flag)
90+
if url == "" {
91+
return fmt.Errorf("--%s must not be empty", flag)
92+
}
93+
channel = map[string]any{"type": typ, "url": url}
94+
}
95+
}
96+
if channel == nil {
97+
return errors.New("choose a channel: --email, --slack-webhook, --discord-webhook, or --webhook")
98+
}
99+
100+
toolArgs := cmdutil.ToolArgs(cmd, map[string]string{"cron": "cron_expression", "performance": "performance"})
101+
toolArgs["query_id"] = queryID
102+
toolArgs["channel"] = channel
103+
104+
// The result has no webhook URL, so it is safe to print as it is.
105+
var res struct {
106+
AlertID string `json:"alert_id"`
107+
Channel string `json:"channel"`
108+
CronExpression string `json:"cron_expression"`
109+
NextExecutionTime string `json:"next_execution_time"`
110+
}
111+
raw, err := cmdutil.CallTool(cmd, "setQueryAlert", toolArgs, &res)
112+
if err != nil {
113+
return err
114+
}
115+
w := cmd.OutOrStdout()
116+
if output.FormatFromCmd(cmd) == output.FormatJSON {
117+
return output.PrintRawJSON(w, raw)
118+
}
119+
fmt.Fprintf(w, "Set %s alert %s on query %d\n", res.Channel, res.AlertID, queryID)
120+
fmt.Fprintf(w, "Schedule: %s (UTC), next run %s\n", res.CronExpression, res.NextExecutionTime)
121+
return nil
122+
}

‎cmd/query/alert_test.go‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package query_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/duneanalytics/cli/dunemcp/dunemcptest"
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
const alertResult = `{"alert_id":"a-1","query_id":42,"channel":"slack","cron_expression":"0 * * * *",
12+
"next_execution_time":"2026-11-26T10:00:00Z"}`
13+
14+
func runAlert(fake *dunemcptest.Fake, args ...string) (string, error) {
15+
root, buf := newMCPRoot(fake)
16+
root.SetArgs(append([]string{"query", "alert"}, args...))
17+
err := root.Execute()
18+
return buf.String(), err
19+
}
20+
21+
func TestAlertSendsEmailChannel(t *testing.T) {
22+
fake := &dunemcptest.Fake{Results: map[string]string{"setQueryAlert": alertResult}}
23+
_, err := runAlert(fake, "42", "--cron", "0 * * * *", "--performance", "small",
24+
"--email", "a@x.com", "--email", "b@x.com")
25+
require.NoError(t, err)
26+
assert.Equal(t, "setQueryAlert", fake.Last().Tool)
27+
assert.JSONEq(t, `{"query_id":42,"cron_expression":"0 * * * *","performance":"small",
28+
"channel":{"type":"email","emails":["a@x.com","b@x.com"]}}`, fake.Last().Args)
29+
}
30+
31+
func TestAlertWebhookChannelsAndOutputHideTheURL(t *testing.T) {
32+
for flag, typ := range map[string]string{"--slack-webhook": "slack", "--discord-webhook": "discord", "--webhook": "webhook"} {
33+
fake := &dunemcptest.Fake{Results: map[string]string{"setQueryAlert": alertResult}}
34+
out, err := runAlert(fake, "42", "--cron", "0 * * * *", "--performance", "small", flag, "https://hooks.example/SECRET")
35+
require.NoError(t, err)
36+
assert.JSONEq(t, `{"query_id":42,"cron_expression":"0 * * * *","performance":"small",
37+
"channel":{"type":"`+typ+`","url":"https://hooks.example/SECRET"}}`, fake.Last().Args)
38+
assert.NotContains(t, out, "SECRET")
39+
}
40+
}
41+
42+
func TestAlertPrintsAlertAndSchedule(t *testing.T) {
43+
fake := &dunemcptest.Fake{Results: map[string]string{"setQueryAlert": alertResult}}
44+
out, err := runAlert(fake, "42", "--cron", "0 * * * *", "--performance", "small", "--slack-webhook", "https://h")
45+
require.NoError(t, err)
46+
assert.Equal(t, "Set slack alert a-1 on query 42\nSchedule: 0 * * * * (UTC), next run 2026-11-26T10:00:00Z\n", out)
47+
}
48+
49+
func TestAlertRejectsBadInputBeforeCalling(t *testing.T) {
50+
for name, args := range map[string][]string{
51+
"no channel": {"42", "--cron", "0 * * * *", "--performance", "small"},
52+
"two channels": {"42", "--cron", "0 * * * *", "--performance", "small", "--email", "a@x.com", "--webhook", "https://h"},
53+
"empty webhook": {"42", "--cron", "0 * * * *", "--performance", "small", "--webhook", ""},
54+
"no cron": {"42", "--performance", "small", "--email", "a@x.com"},
55+
"bad query id": {"0", "--cron", "0 * * * *", "--performance", "small", "--email", "a@x.com"},
56+
} {
57+
t.Run(name, func(t *testing.T) {
58+
fake := &dunemcptest.Fake{}
59+
_, err := runAlert(fake, args...)
60+
require.Error(t, err)
61+
assert.Empty(t, fake.Calls)
62+
})
63+
}
64+
}

‎cmd/query/query.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ func NewQueryCmd() *cobra.Command {
1616
" update - Modify a query's SQL, title, description, privacy, tags, or parameters\n" +
1717
" archive - Hide a query from the library (still retrievable by ID)\n" +
1818
" run - Execute a saved query by ID and display results\n" +
19-
" run-sql - Execute raw DuneSQL inline without saving a query",
19+
" run-sql - Execute raw DuneSQL inline without saving a query\n" +
20+
" alert - Schedule a query and get notified when a run returns rows",
2021
}
2122
cmd.AddCommand(newCreateCmd())
2223
cmd.AddCommand(newCreateAndRunCmd())
@@ -26,5 +27,6 @@ func NewQueryCmd() *cobra.Command {
2627
cmd.AddCommand(newArchiveCmd())
2728
cmd.AddCommand(newRunCmd())
2829
cmd.AddCommand(newRunSQLCmd())
30+
cmd.AddCommand(newAlertCmd())
2931
return cmd
3032
}

0 commit comments

Comments
 (0)