mcpauth: a server never reached says it is the network, and is asked twice (CHENGJIAHEGOXIS on X)

CHENGJIAHEGOXIS on X clicked Sign in on the Library's Notion server
(https://mcp.notion.com/mcp) and got "couldn't reach mcp.notion.com: Post
"https://mcp.notion.com/mcp": EOF", then asked whether the server supports
sign-in at all. It does (Notion answers 401 with OAuth metadata, checked
with curl from here); the first request's connection was cut on their
side of the network.

- discover asks the initialize probe once more when it gets no answer:
  Go never sends a POST again by itself, so a kept-alive connection that
  a proxy or the server closed reads EOF and failed the sign-in.
- The failure is mcpauth.UnreachableError, with the host and the proxy
  the request went through (redacted) or none. api.go says it with an
  i18n key (unreachableSaid): the network, not the server's sign-in, with
  the way it went and what to do, Go's words kept in brackets. zh,
  zh-TW, ja, de.

Run at this head's tree on mica (mote at load 33):
- go test ./internal/mcpauth/ ./internal/gui/ ./internal/library/: ok
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on
  internal/mcpauth and internal/gui: ok
- GUI: mcp-*.test.cjs, i18n-*.test.cjs, signin-browser-down: 328/328,
  Chromium and WebKit; mcp-signin gains the direct and proxy cases in en
  and zh.
Broken by hand: without the second ask, TestSignInAsksAgainAfterACut
Connection and TestSignInUnreachableSaysTheWay/direct go red, the first
with exactly the reporter's message.
Rebased on f6a538ece (also i18n.js): go test -run Budget|I18n
./internal/gui/ and i18n-keys, mcp-signin, image-resolution GUI
(32/32) run again at this head on mica: ok.
Not tried: a real cut connection to mcp.notion.com from the reporter's
network; the full Go and GUI suites.
This commit is contained in:
yetone
2026-11-19 00:32:47 +08:00
parent f6a538ece9
commit 1bd1a08a3a
5 changed files with 220 additions and 10 deletions
+19
View File
@@ -3802,6 +3802,16 @@ func fail(rw http.ResponseWriter, err error) {
out["detail"] = redactProxyErr(why.Err.Error())
}
}
// a remote MCP server whose sign-in magpie never got an answer from:
// the network, said in the reader's language with the way it went,
// not Go's words alone (CHENGJIAHEGOXIS on X)
var unreachable *mcpauth.UnreachableError
if errors.As(err, &unreachable) {
out["code"], out["host"], out["proxy"] = "unreachable", unreachable.Host, unreachable.Proxy
out["detail"] = redactProxyErr(unreachable.Err.Error())
out["error"] = redactProxyErr(out["error"])
out["said"] = unreachableSaid[unreachable.Proxy != ""]
}
var noModels *agent.NoModelsError
if errors.As(err, &noModels) {
out["code"] = "no_models"
@@ -3933,6 +3943,15 @@ var bunSaid = map[string]string{
"cpu": "Bun, which runs plugins, can't start on this computer's processor: it needs an x64 processor with SSE4.2 (Intel or AMD from 2008 on; in a virtual machine, a CPU type that passes it through). Run magpie on such a processor to use plugins, or set MAGPIE_BUN to a bun that runs here.",
}
// unreachableSaid is what the page says for a remote MCP server magpie
// got no answer from when starting its sign-in, by whether the request
// went through a proxy: an i18n.js key like bunSaid's, with {host},
// {proxy} and {detail} filled from the reply
var unreachableSaid = map[bool]string{
false: "magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})",
true: "magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})",
}
// linkSaid is what the page says for an app's import link that nothing
// here opens, by whether it names a program that is gone: an i18n.js key
// like bunSaid's, with {app} and {exe} filled from the reply
+8
View File
@@ -2849,6 +2849,8 @@ const I18N = {
"this server already works without signing in, so there is nothing to sign in to: the agents given it can use it as it is. A key it takes goes in Headers; a server that signs in at another address (as Exa's ?login) needs that URL": "此服务器无需登录即可使用,分配到它的 agent 可直接使用。所需密钥填在请求头中;需在另一地址登录的服务器(如 Exa 的 ?login)请填该 URL",
"this server's sign-in admits only the apps it lists and turned magpie away, so magpie can't sign in for the agents. The agents given it still have the server's own address: sign in from each agent itself (in Claude Code, run /mcp and pick the server)": "此服务器的登录只接受它列出的应用,拒绝了 magpie,所以 magpie 无法替 agent 登录。分配到它的 agent 拿到的仍是服务器自己的地址:请在各个 agent 里自行登录(Claude Code 中运行 /mcp 并选中该服务器)",
"a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings": "服务器前面的防火墙拦下了 magpie 的请求(403),服务器还没来得及提供登录。它是按请求来自的网络判断的:换一个网络再试,或在设置里给 magpie 配一个代理",
"magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})": "magpie 直连(未用代理){host} 没有得到回应,所以登录没能开始。问题不在服务器的登录,而在这台电脑到 {host} 的网络。请在 设置 › 网络与共享 给 magpie 设置代理,或换个网络,再点 登录({detail})",
"magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})": "magpie 通过代理 {proxy} 访问 {host} 没有得到回应,所以登录没能开始。问题不在服务器的登录,而在到 {host} 的线路。请确认该代理能访问 {host},或在 设置 › 网络与共享 换一个代理,再点 登录({detail})",
"1 tool": "1 个工具",
"needs sign-in": "需要登录",
"can't start": "无法启动",
@@ -8331,6 +8333,8 @@ const I18N = {
"this server already works without signing in, so there is nothing to sign in to: the agents given it can use it as it is. A key it takes goes in Headers; a server that signs in at another address (as Exa's ?login) needs that URL": "此伺服器無需登入即可使用,分配到它的 agent 可直接使用。所需金鑰填在請求頭中;需在另一位址登入的伺服器(如 Exa 的 ?login)請填該 URL",
"this server's sign-in admits only the apps it lists and turned magpie away, so magpie can't sign in for the agents. The agents given it still have the server's own address: sign in from each agent itself (in Claude Code, run /mcp and pick the server)": "此伺服器的登入只接受它列出的應用,拒絕了 magpie,所以 magpie 無法替 agent 登入。分配到它的 agent 拿到的仍是伺服器自己的位址:請在各個 agent 裡自行登入(Claude Code 中執行 /mcp 並選取該伺服器)",
"a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings": "伺服器前面的防火牆攔下了 magpie 的請求(403),伺服器還沒來得及提供登入。它是依請求來自的網路判斷的:換一個網路再試,或在設定裡給 magpie 設一個代理",
"magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})": "magpie 直連(未用代理){host} 沒有得到回應,所以登入沒能開始。問題不在伺服器的登入,而在這台電腦到 {host} 的網路。請在 設定 › 網路與共享 給 magpie 設定代理,或換個網路,再點 登入({detail})",
"magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})": "magpie 透過代理 {proxy} 存取 {host} 沒有得到回應,所以登入沒能開始。問題不在伺服器的登入,而在到 {host} 的線路。請確認該代理能存取 {host},或在 設定 › 網路與共享 換一個代理,再點 登入({detail})",
"1 tool": "1 個工具",
"needs sign-in": "需要登入",
"can't start": "無法啟動",
@@ -13782,6 +13786,8 @@ const I18N = {
"this server already works without signing in, so there is nothing to sign in to: the agents given it can use it as it is. A key it takes goes in Headers; a server that signs in at another address (as Exa's ?login) needs that URL": "このサーバーはサインインなしで既に使えるため、サインインする対象がありません。割り当てられたエージェントはそのまま使えます。必要なキーはヘッダーに入れてください。別のアドレスでサインインするサーバー(Exa の ?login など)はその URL が必要です",
"this server's sign-in admits only the apps it lists and turned magpie away, so magpie can't sign in for the agents. The agents given it still have the server's own address: sign in from each agent itself (in Claude Code, run /mcp and pick the server)": "このサーバーのサインインは登録済みのアプリしか受け付けず、magpie を拒否したため、magpie はエージェントの代わりにサインインできません。割り当てられたエージェントにはサーバー自身のアドレスが渡されています。各エージェントから直接サインインしてください(Claude Code では /mcp を実行してサーバーを選択)",
"a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings": "サーバーの前にあるファイアウォールが magpie のリクエストを拒否しました(403)。サーバーがサインインを示す前です。リクエスト元のネットワークで判断しているため、別のネットワークで試すか、設定で magpie にプロキシを指定してください",
"magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})": "magpie はプロキシなしの直接接続で {host} から応答を得られず、サインインを開始できませんでした。問題はサーバーのサインインではなく、このコンピューターと {host} の間のネットワークです。設定 › ネットワークと共有 で magpie にプロキシを設定するか、別のネットワークで、もう一度 サインイン をクリックしてください({detail})",
"magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})": "magpie はプロキシ {proxy} 経由で {host} から応答を得られず、サインインを開始できませんでした。問題はサーバーのサインインではなく、{host} への経路です。そのプロキシが {host} に届くか確認するか、設定 › ネットワークと共有 で別のプロキシを選び、もう一度 サインイン をクリックしてください({detail})",
"1 tool": "1 個のツール",
"needs sign-in": "サインインが必要",
"can't start": "起動できません",
@@ -19276,6 +19282,8 @@ const I18N = {
"this server already works without signing in, so there is nothing to sign in to: the agents given it can use it as it is. A key it takes goes in Headers; a server that signs in at another address (as Exa's ?login) needs that URL": "dieser Server funktioniert bereits ohne Anmeldung, es gibt also nichts anzumelden: Die zugewiesenen Agenten können ihn direkt nutzen. Ein Schlüssel, den er erwartet, gehört unter Header; ein Server, der sich an einer anderen Adresse anmeldet (wie Exa mit ?login), braucht diese URL",
"this server's sign-in admits only the apps it lists and turned magpie away, so magpie can't sign in for the agents. The agents given it still have the server's own address: sign in from each agent itself (in Claude Code, run /mcp and pick the server)": "die Anmeldung dieses Servers lässt nur die von ihm gelisteten Apps zu und hat magpie abgewiesen, daher kann magpie sich nicht für die Agenten anmelden. Die zugewiesenen Agenten erhalten weiterhin die eigene Adresse des Servers: Melden Sie sich in jedem Agenten selbst an (in Claude Code /mcp ausführen und den Server wählen)",
"a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings": "Eine Firewall vor diesem Server hat die Anfrage von magpie abgewiesen (403), bevor der Server eine Anmeldung anbieten konnte. Sie beurteilt das Netzwerk, aus dem die Anfrage kommt: Versuche es in einem anderen Netzwerk oder gib magpie in den Einstellungen einen Proxy",
"magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})": "magpie hat von {host} bei direkter Verbindung ohne Proxy keine Antwort erhalten, daher konnte die Anmeldung nicht beginnen. Das Problem ist nicht die Anmeldung des Servers, sondern das Netzwerk zwischen diesem Computer und {host}. Gib magpie unter Einstellungen › Netzwerk und Freigabe einen Proxy oder versuche ein anderes Netzwerk und klicke dann erneut auf Anmelden ({detail})",
"magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})": "magpie hat von {host} über den Proxy {proxy} keine Antwort erhalten, daher konnte die Anmeldung nicht beginnen. Das Problem ist nicht die Anmeldung des Servers, sondern der Weg zu {host}. Prüfe, ob der Proxy {host} erreicht, oder wähle unter Einstellungen › Netzwerk und Freigabe einen anderen und klicke dann erneut auf Anmelden ({detail})",
"1 tool": "1 Tool",
"needs sign-in": "Anmeldung nötig",
"can't start": "Start nicht möglich",
+34 -2
View File
@@ -23,6 +23,8 @@ const base = () => ({
{ name: "exa", transport: "http", url: "https://mcp.exa.ai/mcp", agents: ["codex"], signIn: { signedIn: false } },
{ name: "figma", transport: "http", url: "https://mcp.figma.com/mcp", agents: ["claude"], signIn: { signedIn: false } },
{ name: "sofa", transport: "http", url: "https://agents.stackoverflow.com/mcp", agents: ["claude"], signIn: { signedIn: false } },
{ name: "notion", transport: "http", url: "https://mcp.notion.com/mcp", agents: ["claude"], signIn: { signedIn: false } },
{ name: "linear", transport: "http", url: "https://mcp.linear.app/mcp", agents: ["claude"], signIn: { signedIn: false } },
],
});
// mcpauth.ErrNoSignIn, as the API says it
@@ -34,6 +36,18 @@ const refused = "this server's sign-in admits only the apps it lists and turned
// (fremontdango on Discord, Cloudflare at agents.stackoverflow.com)
const turnedAway = "a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings";
// mcpauth.UnreachableError as api.go says it: the key of unreachableSaid
// by whether a proxy was used, with the host, the proxy and Go's words
// (CHENGJIAHEGOXIS on X read Notion's bare "couldn't reach mcp.notion.com:
// Post …: EOF" as Notion having no sign-in)
const unreachable = (host, proxy) => ({
code: "unreachable", host, proxy, detail: `Post "https://${host}/mcp": EOF`,
error: `couldn't reach ${host} (${proxy ? "through the proxy " + proxy : "directly, with no proxy"}): Post "https://${host}/mcp": EOF`,
said: proxy
? "magpie got no answer from {host} through the proxy {proxy}, so the sign-in couldn't start. The server's sign-in isn't the problem: the way to {host} is. Check that the proxy reaches {host}, or pick another in Settings › Network and sharing, then click Sign in again ({detail})"
: "magpie got no answer from {host}, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem: the network between this computer and {host} is. Give magpie a proxy in Settings › Network and sharing, or try another network, then click Sign in again ({detail})",
});
function server(lang, calls) {
const lib = base();
let polls = 0;
@@ -52,6 +66,8 @@ function server(lang, calls) {
if (s.url === "https://mcp.exa.ai/mcp") return route.fulfill({ status: 400, json: { error: noSignIn } });
if (s.url === "https://mcp.figma.com/mcp") return route.fulfill({ status: 400, json: { error: refused } });
if (s.url === "https://agents.stackoverflow.com/mcp") return route.fulfill({ status: 400, json: { error: turnedAway } });
if (s.url === "https://mcp.notion.com/mcp") return route.fulfill({ status: 400, json: unreachable("mcp.notion.com", "") });
if (s.url === "https://mcp.linear.app/mcp") return route.fulfill({ status: 400, json: unreachable("mcp.linear.app", "http://127.0.0.1:7890") });
polls = 0;
// no url: the test's browser opens no window
return route.fulfill({ json: { id: "s-" + name, server: name, state: "waiting" } });
@@ -87,8 +103,10 @@ function server(lang, calls) {
}
const words = {
en: { signIn: "Sign in", signOut: "Sign out", signed: "Signed in", label: "Sign-in", done: "Signed in to neon — the agents given it use magpie's sign-in", out: "Signed out of neon — the agents are given the server's own address again", exaDone: "Signed in to exa — the agents given it use magpie's sign-in", noSignIn: "already works without signing in", refused: "admits only the apps it lists", turnedAway: "a firewall in front of this server", saveSignIn: "Save and sign in" },
zh: { signIn: "登录", signOut: "退出登录", signed: "已登录", label: "登录", done: "已登录 neon,分配到它的 agent 共用 magpie 的登录", out: "已退出 neon,agent 改回使用服务器自身的地址", exaDone: "已登录 exa,分配到它的 agent 共用 magpie 的登录", noSignIn: "无需登录即可使用", refused: "只接受它列出的应用", turnedAway: "服务器前面的防火墙拦下了", saveSignIn: "保存并登录" },
en: { signIn: "Sign in", signOut: "Sign out", signed: "Signed in", label: "Sign-in", done: "Signed in to neon — the agents given it use magpie's sign-in", out: "Signed out of neon — the agents are given the server's own address again", exaDone: "Signed in to exa — the agents given it use magpie's sign-in", noSignIn: "already works without signing in", refused: "admits only the apps it lists", turnedAway: "a firewall in front of this server", saveSignIn: "Save and sign in",
direct: "magpie got no answer from mcp.notion.com, going direct with no proxy, so the sign-in couldn't start. The server's sign-in isn't the problem", viaProxy: "magpie got no answer from mcp.linear.app through the proxy http://127.0.0.1:7890, so the sign-in couldn't start" },
zh: { signIn: "登录", signOut: "退出登录", signed: "已登录", label: "登录", done: "已登录 neon,分配到它的 agent 共用 magpie 的登录", out: "已退出 neon,agent 改回使用服务器自身的地址", exaDone: "已登录 exa,分配到它的 agent 共用 magpie 的登录", noSignIn: "无需登录即可使用", refused: "只接受它列出的应用", turnedAway: "服务器前面的防火墙拦下了", saveSignIn: "保存并登录",
direct: "magpie 直连(未用代理)mcp.notion.com 没有得到回应,所以登录没能开始。问题不在服务器的登录", viaProxy: "magpie 通过代理 http://127.0.0.1:7890 访问 mcp.linear.app 没有得到回应" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -189,6 +207,20 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(calls.slice(7), ["start sofa"]);
await page.keyboard.press("Escape");
await page.locator("#modal .lib-editor").waitFor({ state: "detached" });
// a server magpie got no answer from: the network, said with the
// way it went and Go's words, in the reader's language, never read
// as the server having no sign-in
for (const [name, want] of [["notion", w.direct], ["linear", w.viaProxy]]) {
await row(name).click();
const box = page.locator("#modal .lib-signin");
await box.getByRole("button", { name: w.signIn, exact: true }).click();
await box.locator(".lib-signin-err", { hasText: want }).waitFor();
assert.match(await box.locator(".lib-signin-err").textContent(), /mcp": EOF/);
await page.keyboard.press("Escape");
await page.locator("#modal .lib-editor").waitFor({ state: "detached" });
}
assert.deepEqual(calls.slice(8), ["start notion", "start linear"]);
assert.equal(await scrolled(), before, "no click moved the page");
await ctx.close();
});
+48 -8
View File
@@ -95,6 +95,28 @@ var ErrClientRefused = errors.New("this server's sign-in admits only the apps it
// sign-in"). The GUI has it in every language.
var ErrTurnedAway = errors.New("a firewall in front of this server turned magpie's request away (403) before the server could offer a sign-in. It judges the network the request came from: try again on another network, or give magpie a proxy in Settings")
// UnreachableError is a server magpie's first request to never got an
// answer from: the connection was cut, refused or timed out, so the server
// never said whether or how it signs in. It is the network between this
// computer and Host, not the sign-in (CHENGJIAHEGOXIS on X read Notion's
// "couldn't reach mcp.notion.com: Post …: EOF" as Notion having no
// sign-in). Proxy is the proxy the request went through, redacted, "" when
// it went direct; the GUI says it in every language.
type UnreachableError struct {
Host, Proxy string
Err error
}
func (e *UnreachableError) Error() string {
via := "directly, with no proxy"
if e.Proxy != "" {
via = "through the proxy " + e.Proxy
}
return fmt.Sprintf("couldn't reach %s (%s): %v", e.Host, via, e.Err)
}
func (e *UnreachableError) Unwrap() error { return e.Err }
// ErrNoRegistration is a server whose sign-in doesn't let an app register
// itself (GitHub's, 新v学员 on Discord): magpie signs in to it only as an
// OAuth app of the user's own, made with the server's vendor, as Claude
@@ -740,16 +762,34 @@ func discover(ctx context.Context, serverURL string) (meta, error) {
}
// ask it something, as an agent would: its 401 says where to sign in
body := `{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"` + protocolVersion + `","capabilities":{},"clientInfo":{"name":"magpie","version":"1"}}}`
req, err := http.NewRequestWithContext(ctx, http.MethodPost, serverURL, strings.NewReader(body))
if err != nil {
return meta{}, err
ask := func() (*http.Response, *http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, serverURL, strings.NewReader(body))
if err != nil {
return nil, nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("MCP-Protocol-Version", protocolVersion)
resp, err := Client.Do(req)
return resp, req, err
}
resp, req, err := ask()
if err != nil && req != nil && ctx.Err() == nil {
// Go doesn't send a POST again on its own when a kept-alive
// connection the server or a proxy had closed reads EOF: this one
// asks nothing of the account, so it is asked once more, on a
// new connection
resp, req, err = ask()
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("MCP-Protocol-Version", protocolVersion)
resp, err := Client.Do(req)
if err != nil {
return meta{}, fmt.Errorf("couldn't reach %s: %w", su.Host, err)
if req == nil {
return meta{}, err
}
via := ""
if p, perr := netproxy.Func(req); perr == nil && p != nil {
via = netproxy.Redact(p.String())
}
return meta{}, &UnreachableError{Host: su.Host, Proxy: via, Err: err}
}
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
+111
View File
@@ -0,0 +1,111 @@
package mcpauth_test
import (
"errors"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/mcpauth"
"github.com/yetone/magpie/internal/settings"
)
// dropper accepts each connection, reads the request's first bytes and
// closes it without a word, as a proxy or a network that cuts the way to
// a server does: Go reads EOF (CHENGJIAHEGOXIS on X, mcp.notion.com).
func dropper(t *testing.T) (addr string, seen *atomic.Int32) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
seen = new(atomic.Int32)
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
seen.Add(1)
c.Read(make([]byte, 512))
c.Close()
}
}()
return ln.Addr().String(), seen
}
// A first request whose connection is cut is asked once more on a new
// connection: Go doesn't send a POST again by itself, and a kept-alive
// connection a server or proxy closed reads EOF on it.
func TestSignInAsksAgainAfterACutConnection(t *testing.T) {
home(t)
settings.Save(settings.Settings{Proxy: "direct"})
var n atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if n.Add(1) == 1 {
c, _, err := w.(http.Hijacker).Hijack()
if err == nil {
c.Close()
}
return
}
w.WriteHeader(http.StatusOK) // asks for no sign-in
}))
defer srv.Close()
_, err := mcpauth.Start(t.Context(), "notion", srv.URL+"/mcp")
if !errors.Is(err, mcpauth.ErrNoSignIn) {
t.Fatalf("after one cut connection: %v", err)
}
if got := n.Load(); got != 2 {
t.Fatalf("server asked %d times, want 2", got)
}
}
// A server never reached is the network, not the server's sign-in: the
// error says the host and the way the request went, direct or through
// which proxy (its password left out), with Go's words kept.
func TestSignInUnreachableSaysTheWay(t *testing.T) {
home(t)
t.Run("direct", func(t *testing.T) {
settings.Save(settings.Settings{Proxy: "direct"})
addr, seen := dropper(t)
_, err := mcpauth.Start(t.Context(), "notion", "http://"+addr+"/mcp")
var u *mcpauth.UnreachableError
if !errors.As(err, &u) {
t.Fatalf("error %T %v", err, err)
}
if u.Host != addr || u.Proxy != "" || u.Err == nil {
t.Fatalf("got %+v", u)
}
if !strings.Contains(err.Error(), "couldn't reach "+addr+" (directly, with no proxy)") || !strings.Contains(err.Error(), "EOF") {
t.Fatalf("error %v", err)
}
if got := seen.Load(); got != 2 {
t.Fatalf("asked %d times, want 2", got)
}
})
t.Run("proxy", func(t *testing.T) {
addr, _ := dropper(t)
if err := settings.Save(settings.Settings{Proxy: "http://amy:hunter2@" + addr}); err != nil {
t.Fatal(err)
}
// an address on no one's LAN, never dialled: the proxy cuts it
_, err := mcpauth.Start(t.Context(), "notion", "http://203.0.113.5/mcp")
var u *mcpauth.UnreachableError
if !errors.As(err, &u) {
t.Fatalf("error %T %v", err, err)
}
if u.Host != "203.0.113.5" || !strings.Contains(u.Proxy, addr) {
t.Fatalf("got %+v", u)
}
if strings.Contains(u.Proxy, "hunter2") || strings.Contains(err.Error(), "hunter2") {
t.Fatalf("proxy password shown: %v", err)
}
if !strings.Contains(err.Error(), "through the proxy") {
t.Fatalf("error %v", err)
}
})
}