teapot-coding-agent 0.29.32 → 0.29.34

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.
@@ -1,28 +1,28 @@
1
1
  /**
2
- * The MCP server registry (#67): keeps connections, discovers tools, and dispatches
3
- * calls.
2
+ * The MCP server registry (#67): connections, tool discovery, dispatch, and the OAuth
3
+ * flow's plumbing.
4
4
  *
5
5
  * Why a registry instead of connecting per agent: several agents usually want the same
6
- * server, and a stdio server is a PROCESS. One connection per agent would spawn one
7
- * server per agent, each with its own state and its own startup cost. The pool keys by
8
- * server name, so N agents share one connection — and a `tools/call` is still
9
- * per-agent, because the arguments are.
6
+ * server, and a stdio server is a PROCESS. The pool keys by server name, so N agents share
7
+ * one connection — and a `tools/call` is still per-agent, because the arguments are.
10
8
  *
11
9
  * Naming. Two servers may both expose `search`, and a server may expose a name that
12
- * collides with a built-in tool (`bash`, `read_file`). Every MCP tool is therefore
13
- * exposed to the model as `mcp__<server>__<tool>`, which cannot collide with a
14
- * built-in (those have no `__`) and tells the model where the result came from. The
15
- * original name is what gets sent to the server.
10
+ * collides with a built-in tool (`bash`, `read_file`). Every MCP tool is therefore exposed
11
+ * as `mcp__<server>__<tool>`, which cannot collide with a built-in (those have no `__`)
12
+ * and tells the model where a result came from.
13
+ *
14
+ * OAuth lives here because it is per SERVER (one grant, shared by every agent) while the
15
+ * protocol itself belongs to the SDK — see `mcp-oauth-manager.ts` for the provider.
16
16
  */
17
- import { connectMcp, McpError } from "./mcp.js";
18
- import { oauth } from "./mcp-oauth-manager.js";
17
+ import { connectMcp } from "./mcp.js";
18
+ import { FLOW_TIMEOUT_MS, McpAuthStore, ServerAuth, listenForCallback, } from "./mcp-oauth-manager.js";
19
19
  /** the prefix a model-visible MCP tool name carries */
20
20
  export const MCP_PREFIX = "mcp__";
21
21
  /** `mcp__server__tool` — the flat name handed to the LLM */
22
22
  export function flattenToolName(server, tool) {
23
23
  // `__` is the separator, so a server or tool name containing it would be ambiguous.
24
- // Collapse runs rather than rejecting: a server called "my__server" is unusual but
25
- // not worth failing over, and the mapping stays stable.
24
+ // Collapse runs rather than rejecting: a server called "my__server" is unusual but not
25
+ // worth failing over, and the mapping stays stable.
26
26
  const s = server.replace(/__/g, "_");
27
27
  return `${MCP_PREFIX}${s}__${tool}`;
28
28
  }
@@ -38,10 +38,19 @@ export function splitToolName(flat) {
38
38
  }
39
39
  export class McpRegistry {
40
40
  servers = new Map();
41
+ auths = new Map();
42
+ store = null;
43
+ flows = new Map();
44
+ /**
45
+ * Point the registry at its grant store. Called once at boot; until then OAuth is
46
+ * inert (no grant is read from an assumed location).
47
+ */
48
+ init(dataDir) {
49
+ this.store = new McpAuthStore(dataDir);
50
+ }
41
51
  /** replace the configured server list (on boot and after a settings save) */
42
52
  apply(configs) {
43
53
  const wanted = new Set(configs.map((c) => c.name));
44
- // drop connections for servers that were removed or renamed
45
54
  for (const [name, st] of this.servers) {
46
55
  if (!wanted.has(name)) {
47
56
  void st.connection?.close();
@@ -56,17 +65,15 @@ export class McpRegistry {
56
65
  void prev.connection?.close();
57
66
  const reuse = prev && !changed;
58
67
  const status = cfg.enabled === false ? "disabled" : reuse ? prev.status : "disconnected";
59
- const next = {
60
- config: cfg,
61
- tools: reuse ? prev.tools : [],
62
- status,
63
- };
68
+ const next = { config: cfg, tools: reuse ? prev.tools : [], status };
64
69
  if (reuse && prev.connection)
65
70
  next.connection = prev.connection;
66
71
  if (reuse && prev.lastError)
67
72
  next.lastError = prev.lastError;
68
73
  if (reuse && prev.lastChecked)
69
74
  next.lastChecked = prev.lastChecked;
75
+ if (reuse && prev.oauthRequired)
76
+ next.oauthRequired = true;
70
77
  this.servers.set(cfg.name, next);
71
78
  }
72
79
  }
@@ -76,23 +83,36 @@ export class McpRegistry {
76
83
  states() {
77
84
  return [...this.servers.values()];
78
85
  }
79
- /** the OAuth state for one server, for the settings panel */
86
+ /** the OAuth state of one server, for the settings panel */
80
87
  oauthStatus(name) {
81
- return oauth.status(name);
88
+ return this.auths.get(name)?.status() ?? { pending: false, authorized: false, expiresAt: null, hasRefreshToken: false, flow: { phase: "idle" } };
82
89
  }
83
90
  /**
84
- * Connect one server (idempotent) and discover its tools.
91
+ * The provider for one server, created on demand.
85
92
  *
86
- * A 401 is not the end of the story: an OAuth-protected server answers with a Bearer
87
- * challenge, so on auth failure we DETECT and RECORD that, which is what lets the
88
- * settings panel offer "authorize" instead of showing a bare "error". Detection is
89
- * tried BEFORE the challenge reaches the operator — the reference implementations do
90
- * the same, and it turns "it just says 401" into "click authorize".
93
+ * The redirect URL is a placeholder until a flow starts — the SDK reads it when it
94
+ * builds the authorization request, and by then `startOAuth` has set the real loopback
95
+ * port. Keeping one long-lived placeholder would pin a port that is not listening.
91
96
  */
97
+ async authFor(name) {
98
+ if (!this.store)
99
+ return undefined;
100
+ const existing = this.auths.get(name);
101
+ if (existing)
102
+ return existing;
103
+ const stored = await this.store.get(name);
104
+ // a flow needs a redirect; the SDK only reads it during authorize, and
105
+ // `startOAuth` replaces the instance with one carrying the real port
106
+ const auth = new ServerAuth(name, "http://127.0.0.1/callback", (server, data) => this.store.set(server, data));
107
+ await auth.hydrate(stored);
108
+ this.auths.set(name, auth);
109
+ return auth;
110
+ }
111
+ /** connect one server (idempotent) and discover its tools */
92
112
  async connect(name) {
93
113
  const st = this.servers.get(name);
94
114
  if (!st)
95
- throw new McpError(`no such MCP server: ${name}`);
115
+ throw new Error(`no such MCP server: ${name}`);
96
116
  if (st.config.enabled === false) {
97
117
  st.status = "disabled";
98
118
  return st;
@@ -101,20 +121,15 @@ export class McpRegistry {
101
121
  return st;
102
122
  st.status = "connecting";
103
123
  st.lastError = undefined;
104
- // Attach the OAuth authorization when a grant exists, resolved PER REQUEST so a
105
- // refreshed token takes effect without reconnecting.
106
- const withOAuth = {
107
- ...st.config,
108
- oauthAuthorization: () => oauth.authorization(name),
109
- onUnauthorized: () => oauth.invalidate(name),
110
- };
124
+ const auth = await this.authFor(name);
125
+ const authArg = auth ? { provider: auth } : undefined;
111
126
  try {
112
- const conn = await connectMcp(withOAuth);
113
- const tools = await conn.tools();
127
+ const conn = await connectMcp(st.config, authArg);
114
128
  st.connection = conn;
115
- st.tools = tools;
129
+ st.tools = await conn.tools();
116
130
  st.status = "connected";
117
131
  st.lastChecked = Date.now();
132
+ st.oauthRequired = false;
118
133
  return st;
119
134
  }
120
135
  catch (err) {
@@ -123,28 +138,20 @@ export class McpRegistry {
123
138
  st.lastChecked = Date.now();
124
139
  st.connection = undefined;
125
140
  st.tools = [];
126
- // A 401 means "find out what auth this wants" — the challenge names it. Only for
127
- // HTTP transports: a stdio server has no OAuth to discover.
128
- if (err instanceof McpError && err.authRequired && st.config.url) {
129
- try {
130
- const d = await oauth.detect(name, st.config.url, {
131
- ...(st.config.headers ? { headers: st.config.headers } : {}),
132
- });
133
- if (d.requiresOAuth) {
134
- st.oauthRequired = true;
135
- st.lastError =
136
- `this server requires OAuth` +
137
- (d.authServer
138
- ? ` (authorization server: ${new URL(d.authServer.authorizationEndpoint).host})`
139
- : d.reason
140
- ? ` — ${d.reason}`
141
- : "") +
142
- " — use “authorize” in ⚙ settings → MCP servers";
143
- }
144
- }
145
- catch {
146
- /* detection is best-effort: the original error stands */
147
- }
141
+ // The SDK reports a missing grant as an UnauthorizedError (or an HTTP 401); both
142
+ // mean "authorize", which is a different situation from "broken".
143
+ // The SDK reports a missing grant as an HTTP error carrying the STATUS. Reading
144
+ // `status` is reliable; matching the message text is not, because the SDK's message
145
+ // is just "Error POSTing to endpoint: <body>" and a server may send an empty body —
146
+ // MEASURED with a bare 401, which produced no "401" anywhere in the text.
147
+ const status = err.status;
148
+ const msg = err.message ?? "";
149
+ const needsAuth = status === 401 ||
150
+ status === 403 ||
151
+ /unauthoriz|invalid_token|authorization required/i.test(msg);
152
+ if (needsAuth) {
153
+ st.oauthRequired = true;
154
+ st.lastError = "this server requires OAuth — use 🔑 authorize in ⚙ settings → MCP servers";
148
155
  }
149
156
  throw err;
150
157
  }
@@ -174,9 +181,8 @@ export class McpRegistry {
174
181
  const st = this.servers.get(parts.server);
175
182
  if (!st)
176
183
  return { ok: false, text: `no such MCP server: ${parts.server}` };
177
- // a call for a server that is configured but not yet connected should connect on
178
- // demand rather than fail: the operator adding a tool mid-session must not need a
179
- // restart, and auto-connect is cheap for the HTTP transports
184
+ // a call for a configured-but-unconnected server connects on demand: adding one
185
+ // mid-session must not need a restart
180
186
  if (st.status !== "connected" || !st.connection) {
181
187
  try {
182
188
  await this.connect(parts.server);
@@ -193,9 +199,107 @@ export class McpRegistry {
193
199
  return { ok: false, text: `MCP call failed: ${err.message}` };
194
200
  }
195
201
  }
202
+ /**
203
+ * Start an OAuth flow.
204
+ *
205
+ * Opens the loopback listener, points the provider at it, and makes a connect attempt
206
+ * so the SDK performs discovery and produces the authorization URL. The returned URL is
207
+ * what the UI opens; the promise behind it settles when the browser comes back.
208
+ */
209
+ async startOAuth(name, opts = {}) {
210
+ const st = this.servers.get(name);
211
+ if (!st)
212
+ throw new Error(`no such MCP server: ${name}`);
213
+ if (!st.config.url)
214
+ throw new Error("OAuth needs an http(s) url; a stdio server has no authorizer");
215
+ const existing = this.flows.get(name);
216
+ if (existing)
217
+ await this.finishFlow(name, existing);
218
+ const loop = await listenForCallback();
219
+ // a provider bound to THIS listener's port
220
+ const auth = new ServerAuth(name, loop.redirectUrl, (server, data) => this.store.set(server, data));
221
+ if (this.store)
222
+ await auth.hydrate(await this.store.get(name));
223
+ this.auths.set(name, auth);
224
+ const pending = {
225
+ server: name,
226
+ redirectUrl: loop.redirectUrl,
227
+ wait: loop.wait,
228
+ close: loop.close,
229
+ };
230
+ this.flows.set(name, pending);
231
+ // A connect attempt is what drives the SDK: it discovers the authorization server,
232
+ // registers a client if needed, and calls redirectToAuthorization before throwing.
233
+ st.oauthRequired = true;
234
+ try {
235
+ const conn = await connectMcp(st.config, { provider: auth });
236
+ // already authorized (a stored refresh token was good): no flow needed
237
+ st.connection = conn;
238
+ st.tools = await conn.tools();
239
+ st.status = "connected";
240
+ st.oauthRequired = false;
241
+ await this.finishFlow(name, pending);
242
+ return { url: "" };
243
+ }
244
+ catch (err) {
245
+ const url = auth.pendingUrl();
246
+ if (!url) {
247
+ const message = err.message;
248
+ auth.markError(message);
249
+ await this.finishFlow(name, pending);
250
+ throw new Error(`could not start the authorization flow: ${message}`);
251
+ }
252
+ st.status = "authorizing";
253
+ // complete in the background once the browser arrives
254
+ void (async () => {
255
+ try {
256
+ const { code, iss } = await loop.wait(FLOW_TIMEOUT_MS);
257
+ const conn = await connectMcp(st.config, { provider: auth });
258
+ await conn.finishAuth(code, iss);
259
+ st.connection = conn;
260
+ st.tools = await conn.tools();
261
+ st.status = "connected";
262
+ st.oauthRequired = false;
263
+ st.lastError = undefined;
264
+ await this.finishFlow(name, pending);
265
+ }
266
+ catch (e) {
267
+ auth.markError(e.message);
268
+ if (st.status === "authorizing")
269
+ st.status = "error";
270
+ st.lastError = e.message;
271
+ await this.finishFlow(name, pending);
272
+ }
273
+ })();
274
+ return { url };
275
+ }
276
+ }
277
+ /** close a flow's listener and record its outcome */
278
+ async finishFlow(name, f) {
279
+ if (this.flows.get(name) === f)
280
+ this.flows.delete(name);
281
+ await f.close().catch(() => { });
282
+ }
283
+ /** forget a grant (disconnect) */
284
+ async disconnect(name) {
285
+ const auth = this.auths.get(name);
286
+ if (auth)
287
+ await auth.clear();
288
+ const st = this.servers.get(name);
289
+ if (st) {
290
+ await st.connection?.close().catch(() => { });
291
+ st.connection = undefined;
292
+ st.tools = [];
293
+ st.status = st.config.enabled === false ? "disabled" : "disconnected";
294
+ st.oauthRequired = false;
295
+ }
296
+ }
196
297
  async closeAll() {
298
+ for (const f of this.flows.values())
299
+ await f.close().catch(() => { });
300
+ this.flows.clear();
197
301
  for (const st of this.servers.values())
198
- await st.connection?.close();
302
+ await st.connection?.close().catch(() => { });
199
303
  for (const st of this.servers.values()) {
200
304
  st.connection = undefined;
201
305
  st.status = st.config.enabled === false ? "disabled" : "disconnected";