antechamber 0.2.4 → 0.2.6

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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,40 @@ and this project uses [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.6] - 2026-10-15
11
+
12
+ - fix(omo-graph): stop ending the pan on blur and lost capture
13
+
14
+ ## [0.2.5] - 2026-10-15
15
+
16
+ ### Added
17
+
18
+ - OmO terminal monitors now appear in OpenChamber as read-only child sessions of
19
+ the session that started them. They are listed under Subagents and keep a live
20
+ sidebar dot while the watch runs, and their transcript shows the watched
21
+ command, filter, event count and how the watch ended. A session with a live
22
+ watch is no longer evicted as idle, which used to stop the watch.
23
+ - MCP servers configured in OmO now appear in OpenChamber's MCP status, and the
24
+ Authorize button for a server that needs sign-in runs OmO's native
25
+ `/mcp auth` flow in the running session. Status and authorization use the
26
+ most recently used live session in the directory. The flow never adds a
27
+ message to the conversation, and it never revives a dormant session.
28
+ - Completing an MCP sign-in with a pasted code or redirect URL (OpenChamber's
29
+ callback page or paste box) now works through `/mcp/{name}/auth/callback`.
30
+ The code goes to OmO's waiting loopback listener, or to
31
+ `/mcp auth-complete` when OmO parked the flow.
32
+ - OpenChamber 2.x now lists OmO MCP servers (`GET /api/mcp`) and can sign in
33
+ through `mcp_*` integrations. These run OmO's headless `/mcp auth-start` and
34
+ `/mcp auth-complete` with a paste-the-code step. A completed sign-in emits
35
+ `mcp.status.changed`.
36
+
37
+ ### Fixed
38
+
39
+ - OmO Graph: dragging the graph no longer stops after a fraction of a second.
40
+ The previous stuck-pan fix also ended the drag when the panel lost focus or
41
+ pointer capture, which can happen while the button is still held; the drag
42
+ now ends only on release, cancel, or a move without the button held.
43
+
10
44
  ## [0.2.4] - 2026-10-15
11
45
 
12
46
  ### Added
@@ -30,6 +30,7 @@ export declare class SessionLifecycle {
30
30
  private stopping;
31
31
  constructor(sessions: () => Iterable<ManagedSession>, options?: LifecycleOptions);
32
32
  touch(s: ManagedSession): void;
33
+ lastUsed(s: ManagedSession): number;
33
34
  private idle;
34
35
  /** Protect the caller across awaits, including admission of a dormant session. */
35
36
  use<T>(s: ManagedSession, action: () => Promise<T>): Promise<T>;
package/dist/lifecycle.js CHANGED
@@ -45,6 +45,9 @@ export class SessionLifecycle {
45
45
  touch(s) {
46
46
  this.used.set(s, this.clock.now());
47
47
  }
48
+ lastUsed(s) {
49
+ return this.used.get(s) ?? 0;
50
+ }
48
51
  idle(s) {
49
52
  return (!this.active.has(s) &&
50
53
  s.pi !== undefined &&
@@ -52,6 +55,7 @@ export class SessionLifecycle {
52
55
  s.status.type === "idle" &&
53
56
  !s.hasPendingInteraction() &&
54
57
  !s.hasRunningChildren() &&
58
+ !s.hasBackgroundWork?.() &&
55
59
  s.piSessionId !== undefined &&
56
60
  s.piPath !== undefined);
57
61
  }
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * OpenCode MCP routes (v1 `/mcp*`, v2 `/api/mcp` and `mcp_*` integrations) backed by OmO's MCP service.
3
+ *
4
+ * OpenChamber scopes MCP calls by directory only, while OmO owns MCP per session process.
5
+ * Everything therefore targets the most recently used LIVE session in the directory; a
6
+ * dormant session is never revived just to answer an MCP request.
7
+ *
8
+ * Status comes from the read-only `get_loaded_surfaces` RPC. Authorization drives OmO's
9
+ * documented `/mcp` subcommands (docs/mcp.md "Auth"):
10
+ * - `/mcp auth <name>`: OmO opens a loopback listener and the browser, exchanges the code
11
+ * and reconnects. With `mcp.oauthCallbackUrl` set it parks a pending flow instead.
12
+ * - `/mcp auth-start <name>` then `/mcp auth-complete <name> <redirect-url>`: the headless
13
+ * paste flow; the pending PKCE state lives in that session process, so completion must
14
+ * reach the same process.
15
+ * Commands are sent straight to the agent, outside the conversation queue: they neither
16
+ * wait behind a running turn nor create a user message, and the session is held active so
17
+ * the reaper cannot stop the process (and its listener or pending state) mid-flow.
18
+ */
19
+ import type { RouteServices } from "./route-services.js";
20
+ type OCMcpStatus = {
21
+ status: "connected";
22
+ } | {
23
+ status: "disabled";
24
+ } | {
25
+ status: "failed";
26
+ error: string;
27
+ } | {
28
+ status: "needs_auth";
29
+ } | {
30
+ status: "needs_client_registration";
31
+ error: string;
32
+ };
33
+ type V2McpStatus = {
34
+ status: "connected";
35
+ } | {
36
+ status: "pending";
37
+ } | {
38
+ status: "disabled";
39
+ } | {
40
+ status: "failed";
41
+ error: string;
42
+ } | {
43
+ status: "needs_auth";
44
+ error: string;
45
+ };
46
+ interface OmoMcpServer {
47
+ name: string;
48
+ status?: string;
49
+ authStatus?: string;
50
+ }
51
+ interface RouteResult {
52
+ status: number;
53
+ body?: unknown;
54
+ }
55
+ /** OmO's loopback listener gives up after 5 minutes; leave room for the reconnect that follows. */
56
+ export declare const MCP_AUTH_COMMAND_TIMEOUT_MS: number;
57
+ /** OmO's runtime states fold onto OpenCode's; lazy servers are usable, so they read as connected. */
58
+ export declare function openCodeMcpStatus(server: OmoMcpServer): OCMcpStatus;
59
+ export declare function v2McpStatus(server: OmoMcpServer): V2McpStatus;
60
+ /** The URL OmO prints on its own line after naming the server (`auth` and `auth-start` both do). */
61
+ export declare function authorizationUrl(text: string, name: string): string | undefined;
62
+ /**
63
+ * The redirect `/mcp auth-complete` expects. OpenChamber sends either the bare code (callback
64
+ * page, v1 paste box) or the whole redirect address; a bare code is rebuilt from the
65
+ * authorization request's own `redirect_uri` and `state`.
66
+ */
67
+ export declare function redirectInput(authorization: string, input: string): string | undefined;
68
+ export declare function mcpRoute(services: RouteServices, method: string, path: string, directory: string, body: () => Promise<unknown>): Promise<RouteResult | undefined>;
69
+ export declare function mcpRouteV2(services: RouteServices, method: string, path: string, directory: string, body: () => Promise<unknown>): Promise<RouteResult | undefined>;
70
+ export {};
package/dist/mcp.js ADDED
@@ -0,0 +1,494 @@
1
+ /**
2
+ * OpenCode MCP routes (v1 `/mcp*`, v2 `/api/mcp` and `mcp_*` integrations) backed by OmO's MCP service.
3
+ *
4
+ * OpenChamber scopes MCP calls by directory only, while OmO owns MCP per session process.
5
+ * Everything therefore targets the most recently used LIVE session in the directory; a
6
+ * dormant session is never revived just to answer an MCP request.
7
+ *
8
+ * Status comes from the read-only `get_loaded_surfaces` RPC. Authorization drives OmO's
9
+ * documented `/mcp` subcommands (docs/mcp.md "Auth"):
10
+ * - `/mcp auth <name>`: OmO opens a loopback listener and the browser, exchanges the code
11
+ * and reconnects. With `mcp.oauthCallbackUrl` set it parks a pending flow instead.
12
+ * - `/mcp auth-start <name>` then `/mcp auth-complete <name> <redirect-url>`: the headless
13
+ * paste flow; the pending PKCE state lives in that session process, so completion must
14
+ * reach the same process.
15
+ * Commands are sent straight to the agent, outside the conversation queue: they neither
16
+ * wait behind a running turn nor create a user message, and the session is held active so
17
+ * the reaper cannot stop the process (and its listener or pending state) mid-flow.
18
+ */
19
+ import { randomUUID } from "node:crypto";
20
+ import { errorBody } from "./http.js";
21
+ /** Bounds how long an HTTP caller waits on a read-only RPC; the transport keeps its own budget. */
22
+ const MCP_READ_WAIT_MS = 5_000;
23
+ /** OmO announces the authorization URL before it waits for the browser. */
24
+ const MCP_AUTH_URL_WAIT_MS = 30_000;
25
+ /** OmO's loopback listener gives up after 5 minutes; leave room for the reconnect that follows. */
26
+ export const MCP_AUTH_COMMAND_TIMEOUT_MS = 10 * 60_000;
27
+ /** A pending paste flow is forgotten after this; OmO's own state is replaced by the next start. */
28
+ const MCP_AUTH_ATTEMPT_TTL_MS = 10 * 60_000;
29
+ /** Names are passed as one slash-command argument, so they must not split or quote. */
30
+ const SERVER_NAME = /^[^\s"'\\]+$/;
31
+ const INTEGRATION_PREFIX = "mcp_";
32
+ const OAUTH_METHOD_ID = "oauth";
33
+ const flows = new Map();
34
+ const admissions = new Map();
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+ function errorMessage(error) {
39
+ return error instanceof Error ? error.message : String(error);
40
+ }
41
+ const flowKey = (directory, name) => `${directory}\0${name}`;
42
+ /** OmO's runtime states fold onto OpenCode's; lazy servers are usable, so they read as connected. */
43
+ export function openCodeMcpStatus(server) {
44
+ if (server.status === "needs_client_registration")
45
+ return {
46
+ status: "needs_client_registration",
47
+ error: "OAuth client registration is required; configure a client ID for this server in OmO",
48
+ };
49
+ if (server.status === "needs_auth")
50
+ return { status: "needs_auth" };
51
+ if (server.status === "disabled" || server.status === "untrusted")
52
+ return { status: "disabled" };
53
+ if (server.status === "degraded")
54
+ return { status: "failed", error: "MCP server is degraded; see /mcp logs in OmO" };
55
+ if (server.status !== "connected" && server.authStatus === "notLoggedIn")
56
+ return { status: "needs_auth" };
57
+ return { status: "connected" };
58
+ }
59
+ export function v2McpStatus(server) {
60
+ const status = openCodeMcpStatus(server);
61
+ if (status.status === "needs_auth")
62
+ return { status: "needs_auth", error: "Sign-in required" };
63
+ if (status.status === "needs_client_registration")
64
+ return { status: "needs_auth", error: status.error };
65
+ if (status.status === "connected" && server.status === "connecting")
66
+ return { status: "pending" };
67
+ return status;
68
+ }
69
+ const oauthCapable = (server) => server.authStatus === "notLoggedIn" || server.authStatus === "oAuth";
70
+ function liveSession(sessions, directory) {
71
+ const s = sessions.liveSessions(directory)[0];
72
+ return s?.pi === undefined ? undefined : { s, pi: s.pi };
73
+ }
74
+ async function loadedServers(pi) {
75
+ const response = await pi.command({ type: "get_loaded_surfaces" }, undefined, AbortSignal.timeout(MCP_READ_WAIT_MS));
76
+ // Older OmO builds have no loaded-surfaces RPC: report no servers rather than a failure.
77
+ if (!response.success || !isRecord(response.data) || !Array.isArray(response.data.mcpServers))
78
+ return [];
79
+ return response.data.mcpServers.flatMap((server) => isRecord(server) && typeof server.name === "string"
80
+ ? [
81
+ {
82
+ name: server.name,
83
+ ...(typeof server.status === "string" ? { status: server.status } : {}),
84
+ ...(typeof server.authStatus === "string" ? { authStatus: server.authStatus } : {}),
85
+ },
86
+ ]
87
+ : []);
88
+ }
89
+ async function directoryServers(sessions, directory) {
90
+ const live = liveSession(sessions, directory);
91
+ return live === undefined ? [] : loadedServers(live.pi).catch(() => []);
92
+ }
93
+ async function hasMcpCommand(pi) {
94
+ const response = await pi.command({ type: "get_commands" }, undefined, AbortSignal.timeout(MCP_READ_WAIT_MS));
95
+ if (!response.success || !isRecord(response.data) || !Array.isArray(response.data.commands))
96
+ return false;
97
+ return response.data.commands.some((command) => isRecord(command) && command.name === "mcp" && command.source === "extension");
98
+ }
99
+ /** The URL OmO prints on its own line after naming the server (`auth` and `auth-start` both do). */
100
+ export function authorizationUrl(text, name) {
101
+ if (!text.includes(name))
102
+ return undefined;
103
+ const candidate = /(?:^|\n)(https?:\/\/\S+)/.exec(text)?.[1];
104
+ if (candidate === undefined)
105
+ return undefined;
106
+ try {
107
+ return new URL(candidate).toString();
108
+ }
109
+ catch {
110
+ return undefined;
111
+ }
112
+ }
113
+ /**
114
+ * The redirect `/mcp auth-complete` expects. OpenChamber sends either the bare code (callback
115
+ * page, v1 paste box) or the whole redirect address; a bare code is rebuilt from the
116
+ * authorization request's own `redirect_uri` and `state`.
117
+ */
118
+ export function redirectInput(authorization, input) {
119
+ const pasted = input.trim();
120
+ if (pasted === "" || /\s/.test(pasted))
121
+ return undefined;
122
+ try {
123
+ const url = new URL(pasted);
124
+ if (url.searchParams.has("code") || url.searchParams.has("error"))
125
+ return url.toString();
126
+ }
127
+ catch {
128
+ // Not an address: treat it as the authorization code itself.
129
+ }
130
+ const request = new URL(authorization).searchParams;
131
+ const redirect = request.get("redirect_uri");
132
+ if (redirect === null)
133
+ return undefined;
134
+ const url = new URL(redirect);
135
+ url.searchParams.set("code", pasted);
136
+ const state = request.get("state");
137
+ if (state !== null)
138
+ url.searchParams.set("state", state);
139
+ return url.toString();
140
+ }
141
+ /** Only the listener OmO announced for this flow may receive the pasted redirect. */
142
+ function sameCallback(target, authorization) {
143
+ const announced = new URL(authorization).searchParams.get("redirect_uri");
144
+ if (announced === null)
145
+ return false;
146
+ const expected = new URL(announced);
147
+ return target.origin === expected.origin && target.pathname === expected.pathname;
148
+ }
149
+ function runMcpCommand(sessions, s, pi, name, args, observe = {}) {
150
+ const errors = [];
151
+ const onEvent = (event) => {
152
+ const entry = event.entry;
153
+ if (event.type !== "entry_appended" || !isRecord(entry))
154
+ return;
155
+ if (entry.type !== "custom" || entry.customType !== "mcp-auth" || typeof entry.data !== "string")
156
+ return;
157
+ const done = `MCP server ${name} `;
158
+ if (entry.data.startsWith(`${done}authorized`) || entry.data.startsWith(`${done}authenticated`))
159
+ observe.authorized?.();
160
+ const found = authorizationUrl(entry.data, name);
161
+ if (found !== undefined)
162
+ observe.url?.(found);
163
+ };
164
+ const onNotify = (request) => {
165
+ if (request.method !== "notify" || request.notifyType !== "error" || typeof request.message !== "string")
166
+ return;
167
+ if (request.message.includes(`MCP server ${name} `) || request.message.includes(`MCP server: ${name}`))
168
+ errors.push(request.message);
169
+ };
170
+ pi.onEvent(onEvent);
171
+ pi.onExtensionUI(onNotify);
172
+ return sessions.lifecycle
173
+ .use(s, () => pi.command({ type: "prompt", message: `/mcp ${args}`, expandPromptTemplates: true }, MCP_AUTH_COMMAND_TIMEOUT_MS))
174
+ .then((response) => {
175
+ if (!response.success)
176
+ throw new Error(response.error ?? "OmO rejected the /mcp command");
177
+ const disposition = isRecord(response.data) ? response.data.disposition : undefined;
178
+ if (disposition !== "handled")
179
+ throw new Error(`OmO did not handle /mcp (disposition: ${String(disposition)})`);
180
+ if (errors.length > 0)
181
+ throw new Error(errors.join("\n"));
182
+ })
183
+ .finally(() => {
184
+ pi.off("event", onEvent);
185
+ pi.off("extension_ui_request", onNotify);
186
+ });
187
+ }
188
+ function announce(services, directory, name) {
189
+ services.broadcast(directory, { type: "mcp.tools.changed", properties: { server: name } });
190
+ }
191
+ function pruneFlows() {
192
+ const now = Date.now();
193
+ for (const [key, flow] of flows)
194
+ if (!flow.running && (flow.s.pi !== flow.pi || now - flow.created > MCP_AUTH_ATTEMPT_TTL_MS))
195
+ flows.delete(key);
196
+ }
197
+ /** Concurrent clicks share one admission, so a second `/mcp auth` never races the first. */
198
+ function admitFlow(services, directory, name, command) {
199
+ const key = flowKey(directory, name);
200
+ const pending = admissions.get(key);
201
+ if (pending !== undefined)
202
+ return pending.then((admission) => "flow" in admission && admission.flow.command !== command ? inProgress(name) : admission);
203
+ const admission = startFlow(services, directory, name, command).finally(() => admissions.delete(key));
204
+ admissions.set(key, admission);
205
+ return admission;
206
+ }
207
+ const inProgress = (name) => ({
208
+ error: { status: 409, body: errorBody("McpAuthError", `MCP server ${name} authorization is already in progress`) },
209
+ });
210
+ /** Validates the target and starts (or joins) a flow; never sends a prompt without a `/mcp` command. */
211
+ async function startFlow(services, directory, name, command) {
212
+ if (!SERVER_NAME.test(name))
213
+ return { error: { status: 400, body: errorBody("InvalidRequestError", "invalid MCP server name") } };
214
+ const live = liveSession(services.sessions, directory);
215
+ if (live === undefined)
216
+ return {
217
+ error: {
218
+ status: 400,
219
+ body: errorBody("McpUnavailableError", "MCP authorization needs a running OmO session in this directory"),
220
+ },
221
+ };
222
+ const { s, pi } = live;
223
+ const key = flowKey(directory, name);
224
+ pruneFlows();
225
+ const existing = flows.get(key);
226
+ if (existing?.running && existing.pi === pi)
227
+ return existing.command === command ? { flow: existing } : inProgress(name);
228
+ const servers = await loadedServers(pi);
229
+ if (!servers.some((server) => server.name === name))
230
+ return { error: { status: 404, body: errorBody("McpServerNotFoundError", `MCP server not found: ${name}`) } };
231
+ if (!(await hasMcpCommand(pi)))
232
+ return { error: { status: 400, body: errorBody("UnsupportedError", "This OmO build has no /mcp command") } };
233
+ const url = Promise.withResolvers();
234
+ const flow = {
235
+ s,
236
+ pi,
237
+ command,
238
+ attemptID: randomUUID(),
239
+ created: Date.now(),
240
+ url: url.promise,
241
+ done: Promise.resolve(),
242
+ running: true,
243
+ authorized: false,
244
+ };
245
+ flow.done = runMcpCommand(services.sessions, s, pi, name, `${command} ${name}`, {
246
+ url: (found) => {
247
+ flow.authorizationUrl ??= found;
248
+ url.resolve(found);
249
+ },
250
+ authorized: () => {
251
+ flow.authorized = true;
252
+ },
253
+ })
254
+ .then(() => {
255
+ if (flow.authorized)
256
+ announce(services, directory, name);
257
+ })
258
+ .catch((error) => {
259
+ flow.error = errorMessage(error);
260
+ throw error;
261
+ })
262
+ .finally(() => {
263
+ flow.running = false;
264
+ });
265
+ // The caller that started the flow may already have its URL; a later failure is still reported.
266
+ void flow.done.catch((error) => console.error(`[mcp] authorization of ${name} failed: ${errorMessage(error)}`));
267
+ flows.set(key, flow);
268
+ return { flow };
269
+ }
270
+ async function awaitAuthorizationUrl(flow, name) {
271
+ const wait = AbortSignal.timeout(MCP_AUTH_URL_WAIT_MS);
272
+ const timedOut = new Promise((resolve) => wait.addEventListener("abort", () => resolve("timeout")));
273
+ try {
274
+ const url = await Promise.race([flow.url, flow.done.then(() => undefined), timedOut]);
275
+ if (url === "timeout")
276
+ return { error: `OmO did not produce an authorization URL for ${name}` };
277
+ if (url === undefined)
278
+ return { error: `MCP server ${name} finished without a browser step` };
279
+ return { url };
280
+ }
281
+ catch (error) {
282
+ return { error: errorMessage(error) };
283
+ }
284
+ }
285
+ async function currentStatus(pi, name) {
286
+ return (await loadedServers(pi)).find((server) => server.name === name);
287
+ }
288
+ /**
289
+ * Finishes a flow with the code or redirect the browser produced. A flow still waiting on
290
+ * OmO's loopback listener receives the redirect there (antechamber always runs beside its
291
+ * agent); a parked flow is finished with `/mcp auth-complete` in the process that holds its state.
292
+ */
293
+ async function completeFlow(services, directory, name, input) {
294
+ const key = flowKey(directory, name);
295
+ const flow = flows.get(key);
296
+ const fail = (status, name_, message) => ({
297
+ error: { status, body: errorBody(name_, message) },
298
+ });
299
+ if (flow === undefined || flow.s.pi !== flow.pi || Date.now() - flow.created > MCP_AUTH_ATTEMPT_TTL_MS)
300
+ return fail(400, "McpAuthError", `No pending authorization for ${name}; start it again`);
301
+ if (flow.authorized)
302
+ return { server: await currentStatus(flow.pi, name) };
303
+ if (flow.error !== undefined)
304
+ return fail(400, "McpAuthError", `Authorization of ${name} failed (${flow.error}); start it again`);
305
+ if (typeof input !== "string" || flow.authorizationUrl === undefined)
306
+ return fail(400, "InvalidRequestError", "code is required");
307
+ const redirect = redirectInput(flow.authorizationUrl, input);
308
+ if (redirect === undefined)
309
+ return fail(400, "InvalidRequestError", "code must be an authorization code or redirect URL");
310
+ try {
311
+ if (flow.running && flow.command === "auth") {
312
+ const target = new URL(redirect);
313
+ if (!sameCallback(target, flow.authorizationUrl))
314
+ return fail(400, "McpAuthError", `OmO is waiting for ${name} on its loopback callback; paste that redirect`);
315
+ const delivered = await fetch(target, { redirect: "manual", signal: AbortSignal.timeout(MCP_READ_WAIT_MS) });
316
+ if (!delivered.ok) {
317
+ // OmO ends the flow on a rejected callback; settle it so a retry cannot join the dead flow.
318
+ await flow.done.catch(() => undefined);
319
+ return fail(400, "McpAuthError", `OmO rejected the authorization response for ${name}; start it again`);
320
+ }
321
+ await flow.done;
322
+ }
323
+ else {
324
+ await runMcpCommand(services.sessions, flow.s, flow.pi, name, `auth-complete ${name} ${redirect}`, {
325
+ authorized: () => {
326
+ flow.authorized = true;
327
+ },
328
+ });
329
+ announce(services, directory, name);
330
+ }
331
+ }
332
+ catch (error) {
333
+ flow.error = errorMessage(error);
334
+ return fail(400, "McpAuthError", flow.error);
335
+ }
336
+ if (!flow.authorized)
337
+ return fail(400, "McpAuthError", flow.error ?? `MCP server ${name} did not complete authorization`);
338
+ return { server: await currentStatus(flow.pi, name) };
339
+ }
340
+ function decodeName(raw) {
341
+ try {
342
+ return decodeURIComponent(raw);
343
+ }
344
+ catch {
345
+ return undefined;
346
+ }
347
+ }
348
+ const invalidName = { status: 400, body: errorBody("InvalidRequestError", "invalid MCP server name") };
349
+ export async function mcpRoute(services, method, path, directory, body) {
350
+ if (method === "GET" && path === "/mcp") {
351
+ const servers = await directoryServers(services.sessions, directory);
352
+ return { status: 200, body: Object.fromEntries(servers.map((server) => [server.name, openCodeMcpStatus(server)])) };
353
+ }
354
+ const match = /^\/mcp\/([^/]+)\/auth(\/authenticate|\/callback)?$/.exec(path);
355
+ if (method !== "POST" || match === null)
356
+ return undefined;
357
+ const name = decodeName(match[1]);
358
+ if (name === undefined)
359
+ return invalidName;
360
+ if (match[2] === "/callback") {
361
+ const payload = await body();
362
+ const result = await completeFlow(services, directory, name, isRecord(payload) ? payload.code : undefined);
363
+ if ("error" in result)
364
+ return result.error;
365
+ return {
366
+ status: 200,
367
+ body: result.server === undefined ? { status: "disabled" } : openCodeMcpStatus(result.server),
368
+ };
369
+ }
370
+ const admitted = await admitFlow(services, directory, name, "auth");
371
+ if ("error" in admitted)
372
+ return admitted.error;
373
+ const { flow } = admitted;
374
+ if (match[2] === "/authenticate") {
375
+ try {
376
+ await flow.done;
377
+ }
378
+ catch (error) {
379
+ return { status: 400, body: errorBody("McpAuthError", errorMessage(error)) };
380
+ }
381
+ if (!flow.authorized)
382
+ return {
383
+ status: 400,
384
+ body: errorBody("McpAuthError", `MCP server ${name} is waiting for its authorization code; paste it to finish`),
385
+ };
386
+ const server = await currentStatus(flow.pi, name);
387
+ return { status: 200, body: server === undefined ? { status: "disabled" } : openCodeMcpStatus(server) };
388
+ }
389
+ const announced = await awaitAuthorizationUrl(flow, name);
390
+ if ("error" in announced)
391
+ return { status: 400, body: errorBody("McpAuthError", announced.error) };
392
+ return {
393
+ status: 200,
394
+ body: { authorizationUrl: announced.url, oauthState: new URL(announced.url).searchParams.get("state") ?? "" },
395
+ };
396
+ }
397
+ function integrationInfo(server) {
398
+ return {
399
+ id: `${INTEGRATION_PREFIX}${server.name}`,
400
+ name: server.name,
401
+ metadata: { source: "mcp" },
402
+ methods: [{ id: OAUTH_METHOD_ID, type: "oauth", label: "Sign in with OAuth" }],
403
+ connections: [],
404
+ };
405
+ }
406
+ function attemptTime(flow) {
407
+ return { created: flow.created, expires: flow.created + MCP_AUTH_ATTEMPT_TTL_MS };
408
+ }
409
+ function flowForAttempt(directory, name, attemptID) {
410
+ const flow = flows.get(flowKey(directory, name));
411
+ return flow?.attemptID === attemptID ? flow : undefined;
412
+ }
413
+ export async function mcpRouteV2(services, method, path, directory, body) {
414
+ const located = (status, data) => ({ status, body: { location: { directory }, data } });
415
+ if (method === "GET" && path === "/api/mcp") {
416
+ const servers = await directoryServers(services.sessions, directory);
417
+ return located(200, servers.map((server) => ({
418
+ name: server.name,
419
+ status: v2McpStatus(server),
420
+ ...(oauthCapable(server) ? { integrationID: `${INTEGRATION_PREFIX}${server.name}` } : {}),
421
+ })));
422
+ }
423
+ if (method === "GET" && path === "/api/integration") {
424
+ const servers = await directoryServers(services.sessions, directory);
425
+ return located(200, servers.filter(oauthCapable).map(integrationInfo));
426
+ }
427
+ const match = /^\/api\/integration\/mcp_([^/]+)(\/connect\/oauth(?:\/([^/]+)(\/complete)?)?)?$/.exec(path);
428
+ if (match === null)
429
+ return undefined;
430
+ const name = decodeName(match[1]);
431
+ if (name === undefined)
432
+ return invalidName;
433
+ const [, , connect, rawAttempt, complete] = match;
434
+ if (connect === undefined) {
435
+ if (method !== "GET")
436
+ return undefined;
437
+ const server = (await directoryServers(services.sessions, directory)).find((candidate) => candidate.name === name && oauthCapable(candidate));
438
+ if (server === undefined)
439
+ return { status: 404, body: errorBody("NotFoundError", `integration not found: ${INTEGRATION_PREFIX}${name}`) };
440
+ return located(200, integrationInfo(server));
441
+ }
442
+ if (rawAttempt === undefined) {
443
+ if (method !== "POST")
444
+ return undefined;
445
+ const payload = await body();
446
+ if (isRecord(payload) && payload.methodID !== undefined && payload.methodID !== OAUTH_METHOD_ID)
447
+ return { status: 404, body: errorBody("IntegrationMethodNotFoundError", "unknown integration method") };
448
+ const admitted = await admitFlow(services, directory, name, "auth-start");
449
+ if ("error" in admitted)
450
+ return admitted.error;
451
+ const announced = await awaitAuthorizationUrl(admitted.flow, name);
452
+ if ("error" in announced)
453
+ return { status: 400, body: errorBody("McpAuthError", announced.error) };
454
+ return located(200, {
455
+ attemptID: admitted.flow.attemptID,
456
+ url: announced.url,
457
+ instructions: "Approve access in the browser, then paste the final redirect URL (or the code it carries) to finish.",
458
+ mode: "code",
459
+ time: attemptTime(admitted.flow),
460
+ });
461
+ }
462
+ const attemptID = decodeName(rawAttempt);
463
+ const flow = attemptID === undefined ? undefined : flowForAttempt(directory, name, attemptID);
464
+ const missing = {
465
+ status: 404,
466
+ body: errorBody("IntegrationAttemptNotFoundError", `authorization attempt not found: ${rawAttempt}`),
467
+ };
468
+ if (complete !== undefined) {
469
+ if (method !== "POST")
470
+ return undefined;
471
+ if (flow === undefined)
472
+ return missing;
473
+ const payload = await body();
474
+ const result = await completeFlow(services, directory, name, isRecord(payload) ? payload.code : undefined);
475
+ return "error" in result ? result.error : { status: 204 };
476
+ }
477
+ if (method === "DELETE") {
478
+ if (flow !== undefined)
479
+ flows.delete(flowKey(directory, name));
480
+ return { status: 204 };
481
+ }
482
+ if (method !== "GET")
483
+ return undefined;
484
+ if (flow === undefined)
485
+ return missing;
486
+ const time = attemptTime(flow);
487
+ if (flow.authorized)
488
+ return located(200, { status: "complete", time });
489
+ if (flow.error !== undefined)
490
+ return located(200, { status: "failed", message: flow.error, time });
491
+ if (Date.now() > time.expires)
492
+ return located(200, { status: "expired", time });
493
+ return located(200, { status: "pending", time });
494
+ }
@@ -45,15 +45,14 @@ export async function miscRoute(method, path, url, directory) {
45
45
  if (method === "GET" && ["/skill", "/lsp", "/formatter", "/experimental/tool/ids"].includes(path)) {
46
46
  return { status: 200, body: [] };
47
47
  }
48
- if (method === "GET" && ["/provider/auth", "/mcp"].includes(path))
48
+ if (method === "GET" && path === "/provider/auth")
49
49
  return { status: 200, body: {} };
50
50
  if ((method === "PUT" && /^\/auth\/[^/]+$/.test(path)) ||
51
51
  (method === "POST" && /^\/provider\/[^/]+\/oauth\/(authorize|callback)$/.test(path)) ||
52
52
  (method === "PATCH" && path === "/config")) {
53
53
  return unsupported("Not supported with OmO; configure providers in OmO");
54
54
  }
55
- if ((["POST", "DELETE"].includes(method) &&
56
- /^\/mcp\/[^/]+\/(connect|disconnect|auth(?:\/(?:callback|authenticate))?)$/.test(path)) ||
55
+ if ((["POST", "DELETE"].includes(method) && /^\/mcp\/[^/]+\/(connect|disconnect|auth)$/.test(path)) ||
57
56
  (method === "POST" && path === "/experimental/control-plane/move-session")) {
58
57
  return unsupported("Not supported with OmO; configure MCP and session directories in OmO");
59
58
  }