From 20fab0cad64b7d8e569844b081fc17278982c8d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:18:06 +0000 Subject: [PATCH 1/3] Let an API client pin its Cronitor-Version APIClient.APIVersion, when set, is sent instead of the configured CRONITOR_API_VERSION, for endpoints that need a minimum API version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B4Z4DjjwWh9BgvdzdFoMnc --- lib/api_client.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/api_client.go b/lib/api_client.go index 9fed7ca1..e38f89ca 100644 --- a/lib/api_client.go +++ b/lib/api_client.go @@ -42,6 +42,9 @@ type APIClient struct { UserAgent string IsDev bool Logger func(string) + // APIVersion, when set, is sent as Cronitor-Version in place of the + // configured CRONITOR_API_VERSION. + APIVersion string } // APIResponse wraps the raw response with metadata @@ -109,7 +112,11 @@ func (c *APIClient) Request(method, endpoint string, body []byte, queryParams ma // Set headers req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", c.UserAgent) - if apiVersion := viper.GetString("CRONITOR_API_VERSION"); apiVersion != "" { + apiVersion := c.APIVersion + if apiVersion == "" { + apiVersion = viper.GetString("CRONITOR_API_VERSION") + } + if apiVersion != "" { req.Header.Set("Cronitor-Version", apiVersion) } From d6cab61bddaaa73907967a32b9a58a331ca973f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:20:22 +0000 Subject: [PATCH 2/3] Add `cronitor monitor mcp` to create or update MCP checks Creates a check with type "check", platform "mcp" for a remote MCP server URL, or updates the check named by --key when it exists. Auth is --header "Name: value" (repeatable; values are sent write-only and redacted from verbose logs) or --oauth, which starts a sign-in at /monitors/mcp/oauth/start, prints the authorize URL, opens the browser and polls the connection every 2s until it is ready, failed or expired, then saves the monitor with mcp.oauth_connection. Also --tools, --include-descriptions and --accept-baseline. Requests send Cronitor-Version 2025-11-28. Prints the key, protocol version, auth, watched tools and baseline tools; 400s show the server's mcp messages. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B4Z4DjjwWh9BgvdzdFoMnc --- cmd/monitor_mcp.go | 372 ++++++++++++++++++++++++++++++++++++++++ cmd/monitor_mcp_test.go | 135 +++++++++++++++ 2 files changed, 507 insertions(+) create mode 100644 cmd/monitor_mcp.go create mode 100644 cmd/monitor_mcp_test.go diff --git a/cmd/monitor_mcp.go b/cmd/monitor_mcp.go new file mode 100644 index 00000000..b3365221 --- /dev/null +++ b/cmd/monitor_mcp.go @@ -0,0 +1,372 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "net/url" + "regexp" + "sort" + "strings" + "time" + + "github.com/cronitorio/cronitor-cli/lib" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +const mcpAPIVersion = "2025-11-28" + +var monitorMcpCmd = &cobra.Command{ + Use: "mcp [url]", + Short: "Create or update an MCP server check", + Long: `Create or update a check that monitors a remote MCP server: it connects, lists the +server's tools and alerts when the tools change from the saved baseline. + +Without --key a new check is created. With --key the check is updated if it exists, +otherwise it is created with that key. The URL can be left out when updating. + +Authenticate with --header (repeatable; values are stored write-only and never printed) +or with --oauth, which prints a sign-in URL, opens it in your browser and waits for you +to finish signing in (press Ctrl-C to stop waiting). + +Examples: + cronitor monitor mcp https://mcp.example.com/mcp --key docs-mcp --header "Authorization: Bearer $TOKEN" + cronitor monitor mcp https://mcp.example.com/mcp --key docs-mcp --oauth + cronitor monitor mcp https://mcp.example.com/mcp --tools search,fetch --include-descriptions + cronitor monitor mcp --key docs-mcp --accept-baseline`, + Args: cobra.MaximumNArgs(1), + Run: func(cmd *cobra.Command, args []string) { + mcpURL := "" + if len(args) == 1 { + mcpURL = args[0] + } + runMonitorMcp(cmd.Flags(), mcpURL) + }, +} + +var ( + mcpKey string + mcpName string + mcpHeaders []string + mcpOAuth bool + mcpTools []string + mcpIncludeDescriptions bool + mcpAcceptBaseline bool +) + +func init() { + monitorCmd.AddCommand(monitorMcpCmd) + f := monitorMcpCmd.Flags() + f.StringVar(&mcpKey, "key", "", "Monitor key; updates the check when it exists") + f.StringVar(&mcpName, "name", "", "Monitor name") + f.StringArrayVar(&mcpHeaders, "header", nil, `Request header as "Name: value" (repeatable)`) + f.BoolVar(&mcpOAuth, "oauth", false, "Sign in to the MCP server with OAuth in a browser") + f.StringSliceVar(&mcpTools, "tools", nil, "Only watch these tools (comma-separated)") + f.BoolVar(&mcpIncludeDescriptions, "include-descriptions", false, "Alert when tool descriptions change") + f.BoolVar(&mcpAcceptBaseline, "accept-baseline", false, "Save the server's current tools as the new baseline (existing check)") +} + +func resetMcpFlags() { + mcpKey, mcpName, mcpHeaders, mcpOAuth = "", "", nil, false + mcpTools, mcpIncludeDescriptions, mcpAcceptBaseline = nil, false, false + monitorMcpCmd.Flags().VisitAll(func(f *pflag.Flag) { f.Changed = false }) +} + +type mcpMonitor struct { + Key string `json:"key"` + Request struct { + URL string `json:"url"` + } `json:"request"` + Mcp struct { + Auth string `json:"auth"` + Headers []string `json:"headers"` + Tools []string `json:"tools"` + ProtocolVersion string `json:"protocol_version"` + BaselineTools []string `json:"baseline_tools"` + Oauth *struct { + Issuer string `json:"issuer"` + } `json:"oauth"` + } `json:"mcp"` +} + +func runMonitorMcp(flags *pflag.FlagSet, mcpURL string) { + if mcpOAuth && len(mcpHeaders) > 0 { + failAndExit("Use --header or --oauth, not both") + return + } + headers, err := parseMcpHeaders(mcpHeaders) + if err != nil { + failAndExit(err.Error()) + return + } + + client := lib.NewAPIClient(dev, log) + client.APIVersion = mcpAPIVersion + + var existing *mcpMonitor + if mcpKey != "" { + existing, err = getMcpMonitor(client, mcpKey) + if err != nil { + failAndExit(err.Error()) + return + } + } + if existing == nil && mcpAcceptBaseline { + failAndExit("--accept-baseline needs --key of an existing MCP check") + return + } + if existing == nil && mcpURL == "" { + failAndExit("The MCP server URL is required to create a check") + return + } + + mcp := map[string]interface{}{} + if headers != nil { + mcp["headers"] = headers + } + if flags.Changed("tools") { + mcp["tools"] = mcpTools + } + if flags.Changed("include-descriptions") { + mcp["include_descriptions"] = mcpIncludeDescriptions + } + if mcpAcceptBaseline { + mcp["accept_baseline"] = true + } + if mcpOAuth { + signInURL := mcpURL + if signInURL == "" { + signInURL = existing.Request.URL + } + connection, err := mcpOAuthSignIn(client, signInURL, existing != nil) + if err != nil { + failAndExit(err.Error()) + return + } + mcp["oauth_connection"] = connection + } + + body := map[string]interface{}{"mcp": mcp} + if mcpURL != "" { + body["request"] = map[string]string{"url": mcpURL} + } + if mcpName != "" { + body["name"] = mcpName + } + + var resp *lib.APIResponse + payload := func() []byte { b, _ := json.Marshal(body); return b } + if existing != nil { + resp, err = client.PUT("/monitors/"+url.PathEscape(mcpKey), payload(), nil) + } else { + body["type"], body["platform"] = "check", "mcp" + if mcpKey != "" { + body["key"] = mcpKey + } + resp, err = client.POST("/monitors", payload(), nil) + } + if err != nil { + failAndExit(fmt.Sprintf("Failed to save MCP check: %s", err)) + return + } + if !resp.IsSuccess() { + failAndExit(fmt.Sprintf("API Error (%d): %s", resp.StatusCode, mcpErrorText(resp))) + return + } + + var saved mcpMonitor + if err := json.Unmarshal(resp.Body, &saved); err != nil { + failAndExit(fmt.Sprintf("Failed to parse response: %s", err)) + return + } + verb := "created" + if existing != nil { + verb = "updated" + } + Success(fmt.Sprintf("MCP check '%s' %s", saved.Key, verb)) + printMcpSummary(saved) +} + +// parseMcpHeaders turns "Name: value" flags into a map. Errors never include +// the value. +func parseMcpHeaders(raw []string) (map[string]string, error) { + if len(raw) == 0 { + return nil, nil + } + headers := map[string]string{} + for _, h := range raw { + name, value, ok := strings.Cut(h, ":") + name, value = strings.TrimSpace(name), strings.TrimSpace(value) + if !ok || name == "" || value == "" || strings.ContainsAny(name, " \t") { + return nil, fmt.Errorf(`Invalid --header: use "Name: value"`) + } + rememberSecret(value) + headers[name] = value + } + return headers, nil +} + +func getMcpMonitor(client *lib.APIClient, key string) (*mcpMonitor, error) { + resp, err := client.GET("/monitors/"+url.PathEscape(key), nil) + if err != nil { + return nil, fmt.Errorf("Failed to get monitor: %s", err) + } + if resp.IsNotFound() { + return nil, nil + } + if !resp.IsSuccess() { + return nil, fmt.Errorf("API Error (%d): %s", resp.StatusCode, resp.ParseError()) + } + var m mcpMonitor + if err := json.Unmarshal(resp.Body, &m); err != nil { + return nil, fmt.Errorf("Failed to parse monitor: %s", err) + } + return &m, nil +} + +// mcpOAuthSignIn starts an OAuth sign-in, shows the URL and waits until the +// connection is ready. It returns the connection id to attach to the monitor. +func mcpOAuthSignIn(client *lib.APIClient, mcpURL string, forExisting bool) (string, error) { + start := map[string]string{"url": mcpURL} + if forExisting { + start["monitor"] = mcpKey + } + body, _ := json.Marshal(start) + resp, err := client.POST("/monitors/mcp/oauth/start", body, nil) + if err != nil { + return "", fmt.Errorf("Failed to start OAuth sign-in: %s", err) + } + if !resp.IsSuccess() { + return "", fmt.Errorf("API Error (%d): %s", resp.StatusCode, resp.ParseError()) + } + var started struct { + AuthorizeURL string `json:"authorize_url"` + Connection string `json:"connection"` + ExpiresIn int `json:"expires_in"` + } + if json.Unmarshal(resp.Body, &started) != nil || started.AuthorizeURL == "" || started.Connection == "" { + return "", fmt.Errorf("OAuth start did not return authorize_url and connection") + } + + fmt.Println("Open this URL to sign in:") + fmt.Println() + fmt.Println(" " + started.AuthorizeURL) + fmt.Println() + openBrowserFn(started.AuthorizeURL) + + timeout := time.Duration(started.ExpiresIn) * time.Second + if timeout <= 0 { + timeout = 15 * time.Minute + } + deadline := nowFn().Add(timeout) + Info("Waiting for you to finish signing in (Ctrl-C to cancel)...") + for { + resp, err := client.GET("/monitors/mcp/oauth/connections/"+url.PathEscape(started.Connection), nil) + if err != nil { + return "", fmt.Errorf("Failed to check sign-in status: %s", err) + } + if !resp.IsSuccess() { + return "", fmt.Errorf("API Error (%d): %s", resp.StatusCode, resp.ParseError()) + } + var st struct { + Status string `json:"status"` + Error string `json:"error"` + Issuer string `json:"issuer"` + } + json.Unmarshal(resp.Body, &st) + switch st.Status { + case "ready": + if st.Issuer != "" { + Success("Signed in to " + st.Issuer) + } else { + Success("Signed in") + } + return started.Connection, nil + case "failed": + return "", fmt.Errorf("%s", mcpOAuthErrorMessage(st.Error)) + case "expired": + return "", fmt.Errorf("%s", mcpOAuthErrorMessage("expired")) + } + sleepForPoll(2*time.Second, deadline) + if !nowFn().Before(deadline) { + return "", fmt.Errorf("Timed out waiting for the OAuth sign-in. Run the command again to retry.") + } + } +} + +var mcpOAuthErrors = map[string]string{ + "expired": "The sign-in expired. Run the command again to retry.", + "access_denied": "Sign-in was denied or cancelled.", + "wrong_issuer": "The sign-in response did not come from the expected authorization server.", + "failed": "Sign-in could not be completed. Please try again.", +} + +var mcpOAuthCode = regexp.MustCompile(`^[a-z_]{1,32}$`) + +func mcpOAuthErrorMessage(code string) string { + if msg, ok := mcpOAuthErrors[code]; ok { + return msg + } + if mcpOAuthCode.MatchString(code) { + return "Sign-in was not completed: " + code + } + return mcpOAuthErrors["failed"] +} + +// mcpErrorText prints the messages of a validation error such as +// {"mcp": ["Auth failed: server returned 401"]} or +// {"mcp": {"oauth_connection": "..."}} without the field names. +func mcpErrorText(resp *lib.APIResponse) string { + var body map[string]interface{} + if json.Unmarshal(resp.Body, &body) != nil || body["mcp"] == nil { + return resp.ParseError() + } + var messages []string + var walk func(v interface{}) + walk = func(v interface{}) { + switch node := v.(type) { + case string: + messages = append(messages, node) + case []interface{}: + for _, child := range node { + walk(child) + } + case map[string]interface{}: + keys := make([]string, 0, len(node)) + for k := range node { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + walk(node[k]) + } + } + } + walk(body["mcp"]) + if len(messages) == 0 { + return resp.ParseError() + } + return strings.Join(messages, "; ") +} + +func printMcpSummary(m mcpMonitor) { + auth := m.Mcp.Auth + switch { + case auth == "headers": + auth += " (" + strings.Join(m.Mcp.Headers, ", ") + ")" + case auth == "oauth" && m.Mcp.Oauth != nil && m.Mcp.Oauth.Issuer != "": + auth += " (" + m.Mcp.Oauth.Issuer + ")" + } + watched := "all" + if m.Mcp.Tools != nil { + watched = strings.Join(m.Mcp.Tools, ", ") + } + baseline := strings.Join(m.Mcp.BaselineTools, ", ") + if baseline == "" { + baseline = "none" + } + fmt.Printf(" Protocol: %s\n", m.Mcp.ProtocolVersion) + fmt.Printf(" Auth: %s\n", auth) + fmt.Printf(" Watching: %s\n", watched) + fmt.Printf(" Baseline: %s\n", baseline) +} diff --git a/cmd/monitor_mcp_test.go b/cmd/monitor_mcp_test.go new file mode 100644 index 00000000..ccd543e8 --- /dev/null +++ b/cmd/monitor_mcp_test.go @@ -0,0 +1,135 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const mcpSavedJSON = `{"key":"docs-mcp","request":{"url":"https://mcp.example.com/mcp"},"mcp":{"auth":"%s","headers":%s,"tools":null,"protocol_version":"2025-11-25","baseline_tools":["fetch","search"],"oauth":%s}}` + +func withMcpTest(t *testing.T, handler http.HandlerFunc) (*[]string, func()) { + t.Helper() + var calls []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + calls = append(calls, r.Method+" "+r.URL.Path+" "+string(body)) + if v := r.Header.Get("Cronitor-Version"); v != "2025-11-28" { + t.Errorf("Cronitor-Version = %q", v) + } + handler(w, r) + })) + cleanup := withConnectTest(t, server.URL) + resetMcpFlags() + return &calls, func() { + resetMcpFlags() + cleanup() + server.Close() + } +} + +func TestMonitorMcp_HeaderCreate_HidesValues(t *testing.T) { + calls, cleanup := withMcpTest(t, func(w http.ResponseWriter, r *http.Request) { + switch r.Method + " " + r.URL.Path { + case "GET /monitors/docs-mcp": + http.NotFound(w, r) + case "POST /monitors": + w.WriteHeader(201) + fmtWrite(w, fmt.Sprintf(mcpSavedJSON, "headers", `["x-api-key"]`, "null")) + } + }) + defer cleanup() + verbose = true + + output, code, err := executeWithExit("monitor", "mcp", "https://mcp.example.com/mcp", "--key", "docs-mcp", + "--header", "X-Api-Key: s3cret-value") + if err != nil || code != 0 { + t.Fatalf("exit %d, err %v\n%s", code, err, output) + } + if strings.Contains(output, "s3cret-value") { + t.Errorf("header value printed:\n%s", output) + } + for _, want := range []string{"docs-mcp", "2025-11-25", "fetch, search", "x-api-key"} { + if !strings.Contains(output, want) { + t.Errorf("output missing %q:\n%s", want, output) + } + } + var sent map[string]interface{} + json.Unmarshal([]byte(strings.SplitN((*calls)[1], " ", 3)[2]), &sent) + headers := sent["mcp"].(map[string]interface{})["headers"].(map[string]interface{}) + if sent["type"] != "check" || sent["platform"] != "mcp" || headers["X-Api-Key"] != "s3cret-value" { + t.Errorf("unexpected create body: %v", sent) + } +} + +func TestMonitorMcp_OAuth_StartPendingReadyCreate(t *testing.T) { + polls := 0 + var opened []string + calls, cleanup := withMcpTest(t, func(w http.ResponseWriter, r *http.Request) { + switch r.Method + " " + r.URL.Path { + case "POST /monitors/mcp/oauth/start": + fmtWrite(w, `{"authorize_url":"https://auth.example.com/authorize?state=x","connection":"conn_1","expires_in":900}`) + case "GET /monitors/mcp/oauth/connections/conn_1": + polls++ + if polls == 1 { + fmtWrite(w, `{"status":"pending","error":null,"issuer":null}`) + return + } + fmtWrite(w, `{"status":"ready","error":null,"issuer":"https://auth.example.com"}`) + case "POST /monitors": + w.WriteHeader(201) + fmtWrite(w, fmt.Sprintf(mcpSavedJSON, "oauth", "[]", `{"issuer":"https://auth.example.com"}`)) + } + }) + defer cleanup() + openBrowserFn = func(u string) { opened = append(opened, u) } + + output, code, err := executeWithExit("monitor", "mcp", "https://mcp.example.com/mcp", "--oauth") + if err != nil || code != 0 { + t.Fatalf("exit %d, err %v\n%s", code, err, output) + } + if !strings.Contains(output, "Open this URL to sign in:") || len(opened) != 1 || polls != 2 { + t.Errorf("opened %v, polls %d:\n%s", opened, polls, output) + } + last := (*calls)[len(*calls)-1] + if !strings.HasPrefix(last, "POST /monitors ") || !strings.Contains(last, `"oauth_connection":"conn_1"`) { + t.Errorf("expected create with the connection, got %s", last) + } + if !strings.Contains((*calls)[0], `{"url":"https://mcp.example.com/mcp"}`) { + t.Errorf("unexpected start body: %s", (*calls)[0]) + } +} + +func TestMonitorMcp_OAuthFailed_ExitsNonZero(t *testing.T) { + calls, cleanup := withMcpTest(t, func(w http.ResponseWriter, r *http.Request) { + switch r.Method + " " + r.URL.Path { + case "POST /monitors/mcp/oauth/start": + fmtWrite(w, `{"authorize_url":"https://auth.example.com/authorize","connection":"conn_1","expires_in":900}`) + case "GET /monitors/mcp/oauth/connections/conn_1": + fmtWrite(w, `{"status":"failed","error":"access_denied","issuer":null}`) + } + }) + defer cleanup() + + output, code, _ := executeWithExit("monitor", "mcp", "https://mcp.example.com/mcp", "--oauth") + if code != 1 || !strings.Contains(output, "Sign-in was denied or cancelled.") { + t.Errorf("exit %d:\n%s", code, output) + } + if len(*calls) != 2 { + t.Errorf("expected no monitor write, got %v", *calls) + } +} + +func TestMonitorMcp_HeaderAndOAuthAreExclusive(t *testing.T) { + calls, cleanup := withMcpTest(t, func(w http.ResponseWriter, r *http.Request) {}) + defer cleanup() + + output, code, _ := executeWithExit("monitor", "mcp", "https://mcp.example.com/mcp", "--oauth", "--header", "X-Key: v") + if code != 1 || !strings.Contains(output, "Use --header or --oauth, not both") || len(*calls) != 0 { + t.Errorf("exit %d, calls %v:\n%s", code, *calls, output) + } +} From 4d635613c9ef7571b37b7e5527729f9dbbf36dec Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 06:20:45 +0000 Subject: [PATCH 3/3] Document `cronitor monitor mcp` in the README Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B4Z4DjjwWh9BgvdzdFoMnc --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 2103e51a..c449c99a 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,25 @@ cronitor monitor pause --hours 24 # Pause for 24 hours cronitor monitor unpause ``` +#### MCP server checks + +`cronitor monitor mcp` creates a check that connects to a remote MCP server, lists its tools and alerts +when they change. With `--key` it updates that check if it exists. + +```bash +# Authenticate with a header; values are stored write-only and never printed +cronitor monitor mcp https://mcp.example.com/mcp --key docs-mcp --header "Authorization: Bearer $MCP_TOKEN" + +# Sign in with OAuth: prints a URL, opens your browser, and waits until you finish signing in +cronitor monitor mcp https://mcp.example.com/mcp --key docs-mcp --oauth + +cronitor monitor mcp --key docs-mcp --tools search,fetch --include-descriptions +cronitor monitor mcp --key docs-mcp --accept-baseline # Save the current tools as the baseline +``` + +Use `--header` or `--oauth`, not both. Values passed with `--header` are visible in shell history; use an environment +variable as above. With `--oauth`, Cronitor keeps the tokens; the CLI only sees the sign-in URL. + #### Status Pages ```bash