teapot-coding-agent 0.37.1 → 0.37.3

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.
@@ -3819,7 +3819,27 @@ export class Agent {
3819
3819
  if (call.function.name === "report_progress") {
3820
3820
  await this.recordProgress(call.function.arguments);
3821
3821
  }
3822
- this.messages.push({ role: "tool", tool_call_id: call.id, content: "progress recorded" });
3822
+ /**
3823
+ * EVERY tool call needs a `tool` message, but only `report_progress` was a report.
3824
+ *
3825
+ * This loop used to answer `"progress recorded"` to whatever the model called, so a `bash`
3826
+ * invocation came back with the text "progress recorded" and `durationMs: 0` — it never ran.
3827
+ * MEASURED in this session (seq 62247/62248): the assistant turn carried exactly one tool
3828
+ * call, `bash <npm view polling loop>`, and its result was `"progress recorded"`, while the
3829
+ * very next `progress` row read "(no report produced)". The command's real output appeared
3830
+ * only on the NEXT turn, which is what made it look like a stray duplicate.
3831
+ *
3832
+ * The model did nothing wrong: it was asked for a progress report and chose to run its work
3833
+ * instead. Answering that call with the report text both lies to the model (the tool result
3834
+ * is its only view of what happened) and drops the command's output.
3835
+ *
3836
+ * A non-report call is answered with a plain acknowledgement — it is NOT executed here,
3837
+ * because this path has no tool context and must not run side effects a second time. The
3838
+ * round then continues and the model sees that it still owes a report.
3839
+ */
3840
+ const isReport = call.function.name === "report_progress";
3841
+ const answer = isReport ? "progress recorded" : "not run — this turn was a progress request";
3842
+ this.messages.push({ role: "tool", tool_call_id: call.id, content: answer });
3823
3843
  // log both sides so restores replay the exact exchange (meta-style)
3824
3844
  await this.log.append("tool_call", this.currentSession, this.currentBranch, {
3825
3845
  callId: call.id,
@@ -3830,9 +3850,10 @@ export class Agent {
3830
3850
  await this.log.append("tool_result", this.currentSession, this.currentBranch, {
3831
3851
  callId: call.id,
3832
3852
  name: call.function.name,
3853
+ // a not-run answer is not a FAILURE, so `ok` stays true — the row must not read as an error
3833
3854
  ok: true,
3834
3855
  durationMs: 0,
3835
- result: "progress recorded",
3856
+ result: answer,
3836
3857
  });
3837
3858
  }
3838
3859
  if (!reported && !(res.message.content ?? "").trim()) {
@@ -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
  *
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" });
@@ -134,56 +187,17 @@ export async function connectMcp(cfg, auth) {
134
187
  */
135
188
  if (!auth)
136
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
+ }
137
200
  throw err;
138
201
  }
139
- return {
140
- async tools() {
141
- // one page is the norm; follow the cursor so a server that paginates is not
142
- // silently truncated
143
- const all = [];
144
- let cursor;
145
- const seen = new Set();
146
- for (let page = 0; page < 50; page++) {
147
- const res = await client.listTools(cursor ? { cursor } : undefined);
148
- all.push(...toTools(res, cfg.name));
149
- const next = res.nextCursor;
150
- if (typeof next !== "string")
151
- return all;
152
- if (seen.has(next))
153
- throw new Error("MCP tool pagination returned the same cursor twice");
154
- seen.add(next);
155
- cursor = next;
156
- }
157
- throw new Error("MCP tools/list did not finish within 50 pages");
158
- },
159
- async call(name, args) {
160
- const res = await client.callTool({ name, arguments: (args ?? {}) });
161
- return resultText(res);
162
- },
163
- async finishAuth(code, iss) {
164
- if (!(session instanceof StreamableHTTPClientTransport) && !(session instanceof SSEClientTransport))
165
- throw new Error("this transport has no OAuth flow");
166
- /**
167
- * Exchange on THIS transport — the PKCE verifier and the discovery record are read from the
168
- * provider, but the request is issued with this instance's fetch/init.
169
- */
170
- await session.finishAuth(iss === undefined ? code : new URLSearchParams({ code, iss }));
171
- /**
172
- * …then build a FRESH connection, because this one cannot be revived.
173
- *
174
- * A transport is one-shot: after the 401 that started the flow, connecting again throws
175
- * "already started" even without `close()`. MEASURED, and it is why the flow appeared to
176
- * complete and then report `UnauthorizedError: Unauthorized` — `client.connect` on a spent
177
- * transport fails with no message of its own, and the SDK's UnauthorizedError defaults its
178
- * text to the word "Unauthorized".
179
- *
180
- * The provider is shared, so the new instance reads the tokens the exchange just stored.
181
- */
182
- await client.close().catch(() => { });
183
- return await connectMcp(cfg, auth);
184
- },
185
- async close() {
186
- await client.close().catch(() => { });
187
- },
188
- };
202
+ return buildConnection(cfg, client, session, auth);
189
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.1",
3
+ "version": "0.37.3",
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",