Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/web/changelog/web/error-codes-wherever-they-sit.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"title": "Error codes read wherever they sit",
"items": [
"The hosted MCP server, through SDK 1.31.2, reads an API error's code from its `error` wherever it sits in the JSON body, should an answer ever put `message` first, so its cursor and busy-search hints keep working",
"The changelog lists SDK 1.31.2 and the Python and Go SDKs 0.10.2"
]
}
35 changes: 32 additions & 3 deletions apps/web/lib/changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ const RELEASE = release as { version: string | null; entries: ChangelogEntry[] }

export const APP_VERSION: string = RELEASE.version ?? "dev";
export const CLI_VERSION = "1.20.1";
export const SDK_VERSION = "1.31.1";
export const PYTHON_SDK_VERSION = "0.10.1";
export const GO_SDK_VERSION = "0.10.1";
export const SDK_VERSION = "1.31.2";
export const PYTHON_SDK_VERSION = "0.10.2";
export const GO_SDK_VERSION = "0.10.2";
export const MCP_VERSION = "2.5.0";

export const CHANGELOG: ChangelogEntry[] = [
Expand Down Expand Up @@ -2546,6 +2546,15 @@ export const CHANGELOG: ChangelogEntry[] = [
},

// ─── SDK ────────────────────────────────────────────────────────────
{
version: "1.31.2",
date: "2026-11-16",
title: "Error Codes Read Wherever They Sit",
track: "sdk",
items: [
'An error\'s `code` is read from the body\'s `error` wherever it sits in the JSON object, not only when it comes first, so `{ "message": "...", "error": "invalid_cursor" }` still has the code `invalid_cursor`',
],
},
{
version: "1.31.1",
date: "2026-11-16",
Expand Down Expand Up @@ -3042,6 +3051,16 @@ export const CHANGELOG: ChangelogEntry[] = [
},

// ─── Python SDK ─────────────────────────────────────────────────────
{
version: "0.10.2",
date: "2026-11-16",
title: "Error Codes And Hints Match The TypeScript SDK",
track: "python",
items: [
'`RateLimitError.code` (and the code behind `InvalidCursorError`) is only ever a code such as `search_busy`, never a sentence: a 429 answering `{"error": "Too many requests"}` has no code',
"A short 401 or 404 message gets its recovery hint below 30 UTF-16 units, as in the TypeScript SDK, so messages with emoji get the same hint in both",
],
},
{
version: "0.10.1",
date: "2026-11-16",
Expand Down Expand Up @@ -3195,6 +3214,16 @@ export const CHANGELOG: ChangelogEntry[] = [
},

// ─── Go SDK ─────────────────────────────────────────────────────────
{
version: "0.10.2",
date: "2026-11-16",
title: "Error Codes And Hints Match The TypeScript SDK",
track: "go",
items: [
"The code behind `errors.Is(err, ErrInvalidCursor)` and a busy search is only ever a code such as `invalid_cursor`, never a sentence",
"A short 401 or 404 message gets its recovery hint below 30 UTF-16 units, as in the TypeScript SDK, rather than 30 bytes, so a short message with accented letters gets its hint",
],
},
{
version: "0.10.1",
date: "2026-11-16",
Expand Down
28 changes: 18 additions & 10 deletions packages/sdk-go/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf16"
"unicode/utf8"

"webhooks.cc/go/agent"
Expand Down Expand Up @@ -564,10 +565,7 @@ func errorText(body []byte) (string, bool) {
// withHint adds a recovery hint to a short message: "Not found: Use
// Endpoints.List ...", with the separators the TypeScript and Python SDKs
// use. Unlike them, Go trims the message (as JavaScript's trim() does)
// before it adds the hint, and errorFromResponse calls a message short
// when it is under 30 bytes, where they count characters (UTF-16 units in
// TypeScript, code points in Python), so a short message with non-ASCII
// text can get no hint here and one there.
// before it adds the hint.
func withHint(message, separator, hint string) string {
message = webtext.JSTrim(message)
if message == "" {
Expand All @@ -576,23 +574,33 @@ func withHint(message, separator, hint string) string {
return message + separator + hint
}

func errorFromResponse(response *apiResponse, path string) *Error {
message, ok := errorText(response.body)
// plainErrorText is what the API said, as plain text, before any hint: the
// text of a JSON error body (see errorText), else the body itself cut to 200
// characters.
func plainErrorText(status int, body []byte) string {
message, ok := errorText(body)
if !ok {
message = string(response.body)
message = string(body)
if utf8.RuneCountInString(message) > 200 {
message = string([]rune(message)[:200]) + "..."
}
} else if bareCode.MatchString(message) {
// A bare code ({"error": "not_found"}) is no sentence: say the status (see codeText).
message = codeText(response.status, message)
message = codeText(status, message)
}
generic := len(message) < 30
return message
}

func errorFromResponse(response *apiResponse, path string) *Error {
message := plainErrorText(response.status, response.body)
// Short in UTF-16 units, as the TypeScript SDK counts them.
generic := len(utf16.Encode([]rune(message))) < 30
apiErr := &Error{StatusCode: response.status, Message: message}
var coded struct {
Error string `json:"error"`
}
if json.Unmarshal(response.body, &coded) == nil {
// Only a code (invalid_cursor), never a sentence.
if json.Unmarshal(response.body, &coded) == nil && bareCode.MatchString(coded.Error) {
apiErr.code = coded.Error
}
switch response.status {
Expand Down
25 changes: 5 additions & 20 deletions packages/sdk-go/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1258,29 +1258,14 @@ func TestErrorMessagesAreThePlainTextOfTheBody(t *testing.T) {
body string
message string
}{
// What the API said, in every case, is in the shared vectors
// (errors_conformance_test.go); these pin this SDK's own hint wording.
{404, `{"error":"Endpoint not found"}`, "Endpoint not found: Use Endpoints.List to see your endpoints"},
{400, `{"error":"invalid_input","message":"name is too long"}`, "name is too long"},
{502, "Bad gateway", "Bad gateway"},
{401, `{"error":"Unauthorized"}`, "Unauthorized. Get an API key at https://webhooks.cc/account/api-keys"},
{400, `{"error":"invalid_input","message":"` + strings.Repeat("y ", 125) + `"}`, strings.Repeat("y ", 125)},
{500, strings.Repeat("z", 400), strings.Repeat("z", 200) + "..."},
// A message only JavaScript's trim() calls blank (U+FEFF) gives way to the error.
{400, `{"message":"\ufeff ","error":"name is too long"}`, "name is too long"},
// A short message is trimmed as JavaScript trims it before its hint.
{404, "\ufeffNot found\ufeff", "Not found: Use Endpoints.List to see your endpoints"},
// A bare code is no sentence: the status is said in words instead.
{404, `{"error":"not_found"}`, "Not found: Use Endpoints.List to see your endpoints"},
{404, `{"error":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints"},
{404, `{"error":"not_found","message":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints"},
{401, `{"error":"unauthorized"}`, "Unauthorized. Get an API key at https://webhooks.cc/account/api-keys"},
{403, `{"error":"forbidden"}`, "Forbidden"},
{409, `{"error":"conflict"}`, "Conflict"},
// A code that says more than the status stays, in brackets.
{400, `{"error":"invalid_since"}`, "Bad request (invalid_since)"},
{409, `{"error":"slug_exists"}`, "Conflict (slug_exists)"},
{500, `{"error":"internal_error"}`, "Server error (internal_error)"},
{410, `{"error":"expired"}`, "Request failed with HTTP 410 (expired)"},
{410, `{"message":"expired"}`, "Request failed with HTTP 410 (expired)"},
// A short message is trimmed as JavaScript trims it before its hint.
{404, "\ufeffNot found\ufeff", "Not found: Use Endpoints.List to see your endpoints"},
{404, `{"error":" not_found "}`, "not_found: Use Endpoints.List to see your endpoints"},
}
for _, c := range cases {
api := newFakeAPI(t)
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk-go/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@
package webhookscc

// Version is the SDK's version.
const Version = "0.10.1"
const Version = "0.10.2"
3 changes: 2 additions & 1 deletion packages/sdk-go/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ type Error struct {
RetryAfter time.Duration
// RateLimit is set on a 429 that carried all the X-RateLimit headers.
RateLimit *RateLimit
// code is the "error" of a JSON error body ("search_busy", "invalid_cursor").
// code is the "error" of a JSON error body when it is a code (lower case,
// digits, underscores: "search_busy", "invalid_cursor"), never a sentence.
code string
}

Expand Down
110 changes: 110 additions & 0 deletions packages/sdk-go/errors_conformance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package webhookscc

import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

"webhooks.cc/go/internal/conformance"
"webhooks.cc/go/internal/webtext"
)

// Where this SDK differs from the TypeScript one, and why, by vector name.
// Go reads a code only from "error", never from a "code" field.
var errorCodeDiffers = map[string]string{
"502 a code field beside a sentence": "the code field is not read",
"429 search_busy as a code field": "the code field is not read",
}

// Not compared at all: a 429's message is this SDK's own rate-limit text.
// Go trims a message, as JavaScript's trim() does, before its hint, so a
// hinted message starts with the trimmed text.

func TestErrorsConformance(t *testing.T) {
var file struct {
Version int `json:"version"`
Vectors []struct {
Name string `json:"name"`
Status int `json:"status"`
Body string `json:"body"`
Expected struct {
Message string `json:"message"`
Code *string `json:"code"`
Hinted bool `json:"hinted"`
} `json:"expected"`
} `json:"vectors"`
}
conformance.Load(t, "errors.json", &file)
if file.Version != 1 {
t.Fatalf("errors.json version %d; this test reads version 1", file.Version)
}
if len(file.Vectors) == 0 {
t.Fatal("no vectors")
}
names := map[string]bool{}
for _, vector := range file.Vectors {
names[vector.Name] = true
t.Run(vector.Name, func(t *testing.T) {
status, body, want := vector.Status, []byte(vector.Body), vector.Expected
plain := plainErrorText(status, body)
if plain != want.Message {
t.Fatalf("message %q, want %q", plain, want.Message)
}

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/endpoints/acme" {
t.Errorf("path %s", r.URL.Path)
}
w.WriteHeader(status)
_, _ = w.Write(body)
}))
defer server.Close()
client, err := New(WithAPIKey("whcc_conformance"), WithBaseURL(server.URL+"/"))
if err != nil {
t.Fatal(err)
}
_, err = client.Endpoints.Get(context.Background(), "acme")
var apiErr *Error
if !errors.As(err, &apiErr) {
t.Fatalf("error %v", err)
}
if apiErr.StatusCode != status {
t.Errorf("status %d", apiErr.StatusCode)
}

code := ""
if want.Code != nil {
code = *want.Code
}
codeAgrees := apiErr.code == code &&
errors.Is(apiErr, ErrInvalidCursor) == (status == http.StatusBadRequest && apiErr.code == "invalid_cursor") &&
isBusySearch(apiErr) == (status == http.StatusTooManyRequests && apiErr.code == "search_busy")
// A listed difference that no longer differs fails too, so the list stays true.
if _, differs := errorCodeDiffers[vector.Name]; codeAgrees == differs {
t.Errorf("code %q, want %q, listed as a difference %v", apiErr.code, code, differs)
}

if status == http.StatusTooManyRequests {
return
}
hinted := (status == http.StatusUnauthorized || status == http.StatusNotFound) && apiErr.Message != plain
if hinted != want.Hinted {
t.Fatalf("hinted %v, want %v (message %q)", hinted, want.Hinted, apiErr.Message)
}
if hinted && !strings.HasPrefix(apiErr.Message, webtext.JSTrim(plain)) {
t.Errorf("message %q does not start with %q", apiErr.Message, plain)
}
if !hinted && apiErr.Message != plain {
t.Errorf("message %q, want %q", apiErr.Message, plain)
}
})
}
for name := range errorCodeDiffers {
if !names[name] {
t.Errorf("no vector named %q", name)
}
}
}
16 changes: 0 additions & 16 deletions packages/sdk-go/internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,22 +316,6 @@ func TestSearchCollectsMoreThanAPageHolds(t *testing.T) {
}
}

// A bare code gives way to the status in words, and stays the error's code.
func TestABareCodeIsKeptAsTheCode(t *testing.T) {
cases := []struct {
body, message, code string
}{
{`{"error":"not_found"}`, "Not found: Use Endpoints.List to see your endpoints", "not_found"},
{`{"error":"not_found","message":"Request not found"}`, "Request not found: Use Endpoints.List to see your endpoints", "not_found"},
}
for _, c := range cases {
err := errorFromResponse(&apiResponse{status: http.StatusNotFound, body: []byte(c.body)}, "/requests/r1")
if err.Message != c.message || err.code != c.code {
t.Errorf("%s: message %q, code %q", c.body, err.Message, err.code)
}
}
}

// An error on a later page is the call's error, never a short result.
func TestAnErrorOnALaterPageIsReturned(t *testing.T) {
ctx := context.Background()
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk-python/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "webhooks-cc"
version = "0.10.1"
version = "0.10.2"
description = "Python SDK for webhooks.cc: capture, wait for, sign and verify webhooks and test emails"
readme = "README.md"
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk-python/src/webhooks_cc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
Every signature check for each provider is in :mod:`webhooks_cc.verify`.
"""

__version__ = "0.10.1"
__version__ = "0.10.2"

from .agent import AgentAuthError, ClaimAttempt
from .client import (
Expand Down
27 changes: 18 additions & 9 deletions packages/sdk-python/src/webhooks_cc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,8 @@ def _map_error(
) -> WebhooksCCError:
"""``message`` is the plain text; ``body`` the whole answer, to find its code in."""
raw = message if body is None else body
generic = len(message) < 30
# Short in UTF-16 units, as the TypeScript SDK counts them.
generic = len(message.encode("utf-16-le", "surrogatepass")) // 2 < 30
if status == 401:
return UnauthorizedError(
f"{message}. Get an API key at https://webhooks.cc/account/api-keys"
Expand All @@ -278,13 +279,14 @@ def _map_error(


def _error_code(message: str) -> str | None:
"""The ``error`` of a JSON error body, when it is one."""
"""The ``error`` of a JSON error body, when it is a code (``invalid_cursor``),
not a sentence."""
try:
parsed = json.loads(message)
except ValueError:
return None
code = parsed.get("error") if isinstance(parsed, dict) else None
return code if isinstance(code, str) else None
return code if isinstance(code, str) and _BARE_CODE.fullmatch(code) else None


# Longest text taken from a JSON error body, so one answer cannot make a huge message.
Expand Down Expand Up @@ -336,18 +338,25 @@ def _error_text(body: str) -> str | None:
return None


def _plain_error_text(status: int, text: str) -> str:
"""What the API said, as plain text, before any hint: the text of a JSON
error body (see ``_error_text``), else the body itself cut to 200 characters."""
plain = _error_text(text)
if plain is None:
return text[:200] + "..." if len(text) > 200 else text
if _BARE_CODE.fullmatch(plain):
# A bare code ({"error": "not_found"}) is no sentence: say the status (see _code_text).
return _code_text(status, plain)
return plain


def _error_from_response(response: httpx.Response) -> WebhooksCCError:
text = response.text
try:
path = response.request.url.path
except RuntimeError: # a response built without its request
path = ""
plain = _error_text(text)
if plain is None:
plain = text[:200] + "..." if len(text) > 200 else text
elif _BARE_CODE.fullmatch(plain):
# A bare code ({"error": "not_found"}) is no sentence: say the status (see _code_text).
plain = _code_text(response.status_code, plain)
plain = _plain_error_text(response.status_code, text)
return _map_error(response.status_code, plain, response.headers, path, text)


Expand Down
Loading
Loading