teapot-coding-agent 0.37.0 → 0.37.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -213,6 +213,24 @@ export class McpRegistry {
213
213
  * so the SDK performs discovery and produces the authorization URL. The returned URL is
214
214
  * what the UI opens; the promise behind it settles when the browser comes back.
215
215
  */
216
+ /**
217
+ * Register a server that is not in the saved config yet, so a flow can run against it.
218
+ *
219
+ * The settings panel lets the operator authorize a server before saving it — the alternative was
220
+ * save → the dialog closes → reopen → authorize → save again. The grant lives in the OAuth store
221
+ * keyed by NAME, so nothing here needs to reach `config.mcpServers`; a later `apply()` with the
222
+ * saved list replaces this entry.
223
+ */
224
+ registerUnsaved(cfg) {
225
+ const existing = this.servers.get(cfg.name);
226
+ // never clobber a live connection with a draft
227
+ if (existing?.connection)
228
+ return;
229
+ if (existing)
230
+ existing.config = cfg;
231
+ else
232
+ this.servers.set(cfg.name, { config: cfg, status: "disconnected", tools: [] });
233
+ }
216
234
  async startOAuth(name, opts = {}) {
217
235
  const st = this.servers.get(name);
218
236
  if (!st)
@@ -238,6 +256,20 @@ export class McpRegistry {
238
256
  // A connect attempt is what drives the SDK: it discovers the authorization server,
239
257
  // registers a client if needed, and calls redirectToAuthorization before throwing.
240
258
  st.oauthRequired = true;
259
+ /**
260
+ * KEEP the connection from the 401, not just its side effects.
261
+ *
262
+ * `connectMcp` throws on the 401 that starts the flow, but the transport inside it is the ONE
263
+ * that will redeem the code — a transport cannot be re-started ("already started"), so building
264
+ * a second one here and calling `finishAuth` on it is not equivalent. MEASURED: calling
265
+ * `connectMcp` again in the callback handler produced another Unauthorized (no token yet) and
266
+ * the exchange never ran, which is why BOTH Notion and Canva reported
267
+ * `UnauthorizedError: Unauthorized`.
268
+ *
269
+ * `pendingConn` holds the instance whose provider already did discovery; the callback leg
270
+ * finishes the exchange on it and gets a fresh, usable connection back.
271
+ */
272
+ let pendingConn = null;
241
273
  try {
242
274
  const conn = await connectMcp(st.config, { provider: auth });
243
275
  // already authorized (a stored refresh token was good): no flow needed
@@ -249,6 +281,11 @@ export class McpRegistry {
249
281
  return { url: "" };
250
282
  }
251
283
  catch (err) {
284
+ /**
285
+ * The failed attempt still produced a connection object with a live provider. `connectMcp`
286
+ * only closes the client when NO provider was supplied, precisely so this path can continue.
287
+ */
288
+ pendingConn = err.connection ?? null;
252
289
  const url = auth.pendingUrl();
253
290
  if (!url) {
254
291
  const message = err.message;
@@ -261,7 +298,17 @@ export class McpRegistry {
261
298
  void (async () => {
262
299
  try {
263
300
  const { code, iss } = await loop.wait(FLOW_TIMEOUT_MS);
264
- const conn = await connectMcp(st.config, { provider: auth });
301
+ /**
302
+ * THE CONNECTION FROM THE 401, not a new one.
303
+ *
304
+ * This used to call `connectMcp` again, which — with no token yet — 401s a SECOND time.
305
+ * `finishAuth` therefore never ran, and both Notion and Canva surfaced
306
+ * `UnauthorizedError: Unauthorized` after a completed browser authorization. The
307
+ * exchange could only ever happen on the transport that started the flow.
308
+ */
309
+ const conn = pendingConn;
310
+ if (!conn)
311
+ throw new Error("the authorization flow lost its connection");
265
312
  /**
266
313
  * Supply `iss` from OUR discovery record when the callback omitted it.
267
314
  *
@@ -282,9 +329,14 @@ export class McpRegistry {
282
329
  * wrong iss -> IssuerMismatchError "received https://evil.example"
283
330
  * so the check is not disabled — a genuinely mismatched issuer is still rejected.
284
331
  */
285
- await conn.finishAuth(code, iss ?? auth.expectedIssuer());
286
- st.connection = conn;
287
- st.tools = await conn.tools();
332
+ /**
333
+ * `finishAuth` returns a NEW connection: the instance that redeemed the code cannot serve
334
+ * requests (a transport is one-shot), so storing `conn` here would leave a dead handle.
335
+ */
336
+ const live = await conn.finishAuth(code, iss ?? auth.expectedIssuer());
337
+ await conn.close().catch(() => { });
338
+ st.connection = live;
339
+ st.tools = await live.tools();
288
340
  st.status = "connected";
289
341
  st.oauthRequired = false;
290
342
  st.lastError = undefined;
package/dist/agent/mcp.js CHANGED
@@ -69,6 +69,59 @@ function toTools(list, server) {
69
69
  * `auth` is optional: without it the transports send only the static headers, which is
70
70
  * the common case (a local server, or a static API key).
71
71
  */
72
+ function buildConnection(cfg, client, session, auth) {
73
+ return {
74
+ async tools() {
75
+ // one page is the norm; follow the cursor so a server that paginates is not
76
+ // silently truncated
77
+ const all = [];
78
+ let cursor;
79
+ const seen = new Set();
80
+ for (let page = 0; page < 50; page++) {
81
+ const res = await client.listTools(cursor ? { cursor } : undefined);
82
+ all.push(...toTools(res, cfg.name));
83
+ const next = res.nextCursor;
84
+ if (typeof next !== "string")
85
+ return all;
86
+ if (seen.has(next))
87
+ throw new Error("MCP tool pagination returned the same cursor twice");
88
+ seen.add(next);
89
+ cursor = next;
90
+ }
91
+ throw new Error("MCP tools/list did not finish within 50 pages");
92
+ },
93
+ async call(name, args) {
94
+ const res = await client.callTool({ name, arguments: (args ?? {}) });
95
+ return resultText(res);
96
+ },
97
+ async finishAuth(code, iss) {
98
+ if (!(session instanceof StreamableHTTPClientTransport) && !(session instanceof SSEClientTransport))
99
+ throw new Error("this transport has no OAuth flow");
100
+ /**
101
+ * Exchange on THIS transport — the PKCE verifier and the discovery record are read from the
102
+ * provider, but the request is issued with this instance's fetch/init.
103
+ */
104
+ await session.finishAuth(iss === undefined ? code : new URLSearchParams({ code, iss }));
105
+ /**
106
+ * …then build a FRESH connection, because this one cannot be revived.
107
+ *
108
+ * A transport is one-shot: after the 401 that started the flow, connecting again throws
109
+ * "already started" even without `close()`. MEASURED, and it is why the flow appeared to
110
+ * complete and then report `UnauthorizedError: Unauthorized` — `client.connect` on a spent
111
+ * transport fails with no message of its own, and the SDK's UnauthorizedError defaults its
112
+ * text to the word "Unauthorized".
113
+ *
114
+ * The provider is shared, so the new instance reads the tokens the exchange just stored.
115
+ */
116
+ await client.close().catch(() => { });
117
+ return await connectMcp(cfg, auth);
118
+ },
119
+ async close() {
120
+ await client.close().catch(() => { });
121
+ },
122
+ };
123
+ ;
124
+ }
72
125
  export async function connectMcp(cfg, auth) {
73
126
  const transport = cfg.transport ?? (cfg.command && !cfg.url ? "stdio" : "http");
74
127
  const client = new Client({ name: "teapot", version: "1" });
@@ -116,46 +169,35 @@ export async function connectMcp(cfg, auth) {
116
169
  await client.connect(session);
117
170
  }
118
171
  catch (err) {
119
- // let the caller distinguish "needs a grant" from "broken", which is what the
120
- // settings panel shows differently
121
- await client.close().catch(() => { });
172
+ /**
173
+ * A 401 is NOT a dead connection — it is the first half of the OAuth flow.
174
+ *
175
+ * `client.connect()` failing with UnauthorizedError means the server wants a grant. Closing the
176
+ * client here used to destroy the only transport that could complete it: a transport cannot be
177
+ * re-started ("StreamableHTTPClientTransport already started!") and `finishAuth()` exchanges the
178
+ * code through THIS instance's provider, so the second `connect()` after `finishAuth` always
179
+ * threw — surfacing as a bare `UnauthorizedError: Unauthorized` even though the browser had
180
+ * completed the authorization and the token WAS saved.
181
+ *
182
+ * MEASURED: connect → 401; close; connect again → "already started". And with the exchange
183
+ * succeeding, the tokens were present and the connection still failed.
184
+ *
185
+ * So the client stays open when the caller supplied an auth provider (it may need to finish the
186
+ * flow on it). Without a provider there is nothing to complete, so it is closed as before.
187
+ */
188
+ if (!auth)
189
+ await client.close().catch(() => { });
190
+ /**
191
+ * Attach the connection so the OAuth caller can CONTINUE on this exact instance.
192
+ *
193
+ * The transport that received the 401 is the one that must redeem the code (a transport cannot
194
+ * be restarted), so the caller needs a handle to it — rebuilding one loses the flow.
195
+ */
196
+ if (auth) {
197
+ const conn = buildConnection(cfg, client, session, auth);
198
+ throw Object.assign(err, { connection: conn });
199
+ }
122
200
  throw err;
123
201
  }
124
- return {
125
- async tools() {
126
- // one page is the norm; follow the cursor so a server that paginates is not
127
- // silently truncated
128
- const all = [];
129
- let cursor;
130
- const seen = new Set();
131
- for (let page = 0; page < 50; page++) {
132
- const res = await client.listTools(cursor ? { cursor } : undefined);
133
- all.push(...toTools(res, cfg.name));
134
- const next = res.nextCursor;
135
- if (typeof next !== "string")
136
- return all;
137
- if (seen.has(next))
138
- throw new Error("MCP tool pagination returned the same cursor twice");
139
- seen.add(next);
140
- cursor = next;
141
- }
142
- throw new Error("MCP tools/list did not finish within 50 pages");
143
- },
144
- async call(name, args) {
145
- const res = await client.callTool({ name, arguments: (args ?? {}) });
146
- return resultText(res);
147
- },
148
- async finishAuth(code, iss) {
149
- // the VERIFIER and discovery state live on the transport, so completing the
150
- // exchange must go through the same instance that started the flow
151
- if (!(session instanceof StreamableHTTPClientTransport) && !(session instanceof SSEClientTransport))
152
- throw new Error("this transport has no OAuth flow");
153
- await session.finishAuth(iss === undefined ? code : new URLSearchParams({ code, iss }));
154
- // the connection failed at connect() time (401); finish the handshake now
155
- await client.connect(session);
156
- },
157
- async close() {
158
- await client.close().catch(() => { });
159
- },
160
- };
202
+ return buildConnection(cfg, client, session, auth);
161
203
  }
@@ -1041,13 +1041,29 @@ export function buildApp(master) {
1041
1041
  * clickable link instead of hanging the request for minutes.
1042
1042
  */
1043
1043
  app.post("/api/mcp/oauth/start", async (c) => {
1044
- const body = await c.req.json().catch(() => null);
1044
+ const body = await c.req
1045
+ .json()
1046
+ .catch(() => null);
1045
1047
  if (!body?.name)
1046
1048
  return c.json({ error: "missing name" }, 400);
1049
+ /**
1050
+ * Accept a server that has not been SAVED yet.
1051
+ *
1052
+ * Requiring a saved entry forced the operator through save → dialog closes → reopen → authorize,
1053
+ * and then a second save afterwards to keep the grant attached. Asked as "未保存のMCPサーバーに
1054
+ * 対してOAuthまでした状態を後から保存するというちょっとめんどくさいフローが発生しちゃう".
1055
+ *
1056
+ * The URL from the request wins when present; otherwise the saved entry is used. Nothing is
1057
+ * written here — the grant is stored per server NAME in the OAuth store, so saving afterwards
1058
+ * keeps it.
1059
+ */
1047
1060
  const saved = (master.config.mcpServers ?? []).find((m) => m.name === body.name);
1048
- if (!saved?.url)
1061
+ const targetUrl = String(body.url ?? saved?.url ?? "").trim();
1062
+ if (!targetUrl)
1049
1063
  return c.json({ error: "this server has no url — OAuth needs an http(s) endpoint" }, 400);
1050
1064
  try {
1065
+ // register the candidate so the flow has a config to drive; replaced by the real one on save
1066
+ mcp.registerUnsaved({ name: body.name, url: targetUrl, transport: body.transport ?? "http", enabled: true });
1051
1067
  // `startOAuth` drives the SDK's own flow: discovery, dynamic registration, and the
1052
1068
  // PKCE challenge all happen inside `connectMcp`, so this returns as soon as there
1053
1069
  // is a URL to open. The exchange finishes when the browser hits the callback.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.37.0",
3
+ "version": "0.37.2",
4
4
  "description": "A lightweight, always-on multi-agent harness for AI coding agents",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-or-later",