@omercnet/paseo-omp 5.3.0 → 5.4.0

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.
@@ -0,0 +1,487 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { realpathSync } from "node:fs";
3
+ import type { OmpLoginStep } from "../shared/omp-accounts";
4
+ import {
5
+ type OmpMcpAction,
6
+ type OmpMcpAddResult,
7
+ type OmpMcpAuth,
8
+ type OmpMcpCheck,
9
+ type OmpMcpServer,
10
+ OmpMcpServerSchema,
11
+ type OmpMcpsView,
12
+ } from "../shared/omp-mcps";
13
+ import type { OmpStore } from "../shared/omp-store";
14
+ import { SerialMutationQueue } from "./mutation-queue";
15
+ import {
16
+ isOpen,
17
+ OmpAccountsError,
18
+ type OmpCommand,
19
+ OmpRpcProcess,
20
+ publicMessage,
21
+ resolveCommand,
22
+ } from "./omp-accounts";
23
+ import { currentOmpEnvironment, ompAgentDir, withOmpStore } from "./paths";
24
+ import { buildStatefulCommandEnv } from "./provider-diagnostics";
25
+
26
+ /**
27
+ * The directory omp reads for a store, resolved from the environment omp is started with: that
28
+ * environment does not carry every variable the plugin itself reads for its own file access. Two
29
+ * selectors can name the same directory (the default store and an explicit agent directory equal
30
+ * to it, or a symlink to it) and then share one config, so a guard keyed by the selector could be
31
+ * bypassed through the other.
32
+ */
33
+ function storeIdentity(store: OmpStore | undefined): string {
34
+ let directory: string;
35
+ try {
36
+ directory = withOmpStore(store, () =>
37
+ ompAgentDir(buildStatefulCommandEnv(currentOmpEnvironment())),
38
+ );
39
+ } catch {
40
+ throw new OmpAccountsError("The selected OMP store is not valid");
41
+ }
42
+ let real = directory;
43
+ try {
44
+ real = realpathSync(directory);
45
+ } catch {
46
+ // A directory omp has not created yet has no real path; its own path is the identity.
47
+ }
48
+ return process.platform === "win32" ? real.toLowerCase() : real;
49
+ }
50
+
51
+ const SLASH_TIMEOUT_MS = 60_000;
52
+ /** omp answers a prompt before some commands print; it prints nothing for others. */
53
+ const OUTPUT_GRACE_MS = 2_000;
54
+ /** omp gives up on a browser authorization after five minutes. */
55
+ const AUTH_TIMEOUT_MS = 6 * 60_000;
56
+ const FINISHED_AUTH_TTL_MS = 10 * 60_000;
57
+ /** Listing starts an omp process, so a quick re-read (a poll, a reopened tab) reuses the last one. */
58
+ const LIST_TTL_MS = 30_000;
59
+ const CALLBACK_TIMEOUT_MS = 10_000;
60
+ const LOOPBACK_HOSTS: readonly string[] = ["localhost", "127.0.0.1", "[::1]"];
61
+
62
+ /** `/mcp list` prints one `name | transport | state | target [source]` line per server. */
63
+ const LIST_LINE = /^([^|]+?) \| ([^|]+?) \| ([^|]+?) \| (.*) \[([^\]]*)\]$/u;
64
+ const EMPTY_LIST = /^No MCP servers/iu;
65
+
66
+ export function parseMcpList(text: string): OmpMcpServer[] {
67
+ return text.split("\n").flatMap((line) => {
68
+ const match = LIST_LINE.exec(line.trim());
69
+ if (!match) return [];
70
+ const [, name, transport, state, target, source] = match;
71
+ const parsed = OmpMcpServerSchema.safeParse({ name, transport, state, target, source });
72
+ return parsed.success ? [parsed.data] : [];
73
+ });
74
+ }
75
+
76
+ /** omp reports a failed command only in its text; quoted server names are not read as words. */
77
+ export function reportsFailure(text: string): boolean {
78
+ return /\b(?:fail(?:ed|ure)|not found|unknown option|invalid)\b|\busage:/iu.test(
79
+ text.replace(/"[^"]*"/gu, ""),
80
+ );
81
+ }
82
+
83
+ /**
84
+ * Reads the status line of `/mcp test`. Only the first line says how the connection went: the lines
85
+ * after it list tool names, which can be any word, including "failed". A 401 means something is
86
+ * there and wants a sign-in; any other failure means nothing there is a working MCP server.
87
+ */
88
+ export function readConnectionCheck(text: string): OmpMcpCheck {
89
+ const status = text.trim().split("\n")[0] ?? "";
90
+ if (/\bHTTP 401\b/u.test(status)) return "needs-authorization";
91
+ return status === "" || reportsFailure(status) ? "failed" : "connected";
92
+ }
93
+
94
+ /** What one line of `/mcp reauth` output means for the authorization it belongs to. */
95
+ export type AuthOutput =
96
+ | { kind: "url"; url: string; instructions: string | null }
97
+ | { kind: "progress" }
98
+ | { kind: "done"; message: string }
99
+ | { kind: "failed"; message: string };
100
+
101
+ const AUTH_URL = /https?:\/\/\S+/u;
102
+
103
+ /** omp's own terminal message for a reauth that was canceled; a server may be named "cancel-tools". */
104
+ const OMP_AUTH_ENDED = /^Reauthorization cancelled for /u;
105
+ /** Terminal answers omp prints for a reauth it will not start; they end the command like a failure. */
106
+ const OMP_AUTH_REFUSAL = /is disabled\. Run \/mcp enable|reauthorization is not required/iu;
107
+
108
+ /**
109
+ * omp's rpc mode sends no `open_url` request for a reauthorization: the page address, the result
110
+ * and every progress line arrive as printed text.
111
+ */
112
+ export function readAuthOutput(text: string): AuthOutput {
113
+ const printed = text.trim();
114
+ const url = printed.includes("OAuth Authorization Required") ? AUTH_URL.exec(printed)?.[0] : null;
115
+ if (url) {
116
+ const instructions = printed.slice(printed.indexOf(url) + url.length).trim();
117
+ return { kind: "url", url, instructions: instructions || null };
118
+ }
119
+ if (printed.startsWith("\u2713")) return { kind: "done", message: printed };
120
+ if (reportsFailure(printed) || OMP_AUTH_ENDED.test(printed) || OMP_AUTH_REFUSAL.test(printed)) {
121
+ return { kind: "failed", message: printed };
122
+ }
123
+ return { kind: "progress" };
124
+ }
125
+
126
+ /**
127
+ * The address omp's local callback server should be asked for, from what the person pasted: the
128
+ * full redirect URL, or just the authorization code. Only omp's own loopback redirect is ever
129
+ * called, whatever was pasted.
130
+ */
131
+ export function callbackUrl(authorizationUrl: string, pasted: string): URL | null {
132
+ const params = new URL(authorizationUrl).searchParams;
133
+ const redirect = params.get("redirect_uri");
134
+ if (!redirect) return null;
135
+ const target = new URL(redirect);
136
+ if (!LOOPBACK_HOSTS.includes(target.hostname)) return null;
137
+ const input = pasted.trim();
138
+ if (URL.canParse(input)) {
139
+ const given = new URL(input);
140
+ return given.origin === target.origin && given.pathname === target.pathname ? given : null;
141
+ }
142
+ target.searchParams.set("code", input);
143
+ const state = params.get("state");
144
+ if (state) target.searchParams.set("state", state);
145
+ return target;
146
+ }
147
+
148
+ /** One slash command in a short-lived bare omp rpc session; returns what it printed. */
149
+ async function runSlash(command: OmpCommand, line: string): Promise<string> {
150
+ const printed: string[] = [];
151
+ const first = Promise.withResolvers<void>();
152
+ const rpc = new OmpRpcProcess(command, {
153
+ onOutput: (text) => {
154
+ printed.push(text);
155
+ first.resolve();
156
+ },
157
+ });
158
+ try {
159
+ await rpc.request({ type: "prompt", message: line }, SLASH_TIMEOUT_MS);
160
+ const grace = setTimeout(first.resolve, OUTPUT_GRACE_MS);
161
+ await first.promise;
162
+ clearTimeout(grace);
163
+ return printed.join("\n");
164
+ } finally {
165
+ rpc.close();
166
+ }
167
+ }
168
+
169
+ function actionResult(printed: string, action: string): { ok: boolean; message: string } {
170
+ const message = printed.trim();
171
+ if (message === "") return { ok: false, message: `omp gave no answer to /mcp ${action}` };
172
+ // Only the status line counts; `/mcp test` lists tool names on the lines after it.
173
+ return { ok: !reportsFailure(message.split("\n")[0] ?? ""), message };
174
+ }
175
+
176
+ interface AuthState {
177
+ id: string;
178
+ /** The agent directory omp reads, not the selector that named it. */
179
+ directory: string;
180
+ name: string;
181
+ step: OmpLoginStep;
182
+ url: string | null;
183
+ instructions: string | null;
184
+ codePrompt: string | null;
185
+ message: string | null;
186
+ process: OmpRpcProcess | null;
187
+ timer: ReturnType<typeof setTimeout> | undefined;
188
+ endedAt: number | null;
189
+ }
190
+
191
+ function toAuth(auth: AuthState): OmpMcpAuth {
192
+ return {
193
+ id: auth.id,
194
+ name: auth.name,
195
+ step: auth.step,
196
+ url: auth.url,
197
+ instructions: auth.instructions,
198
+ codePrompt: auth.codePrompt,
199
+ message: auth.message,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Lists, adds, toggles, tests and removes OMP's MCP servers and runs their OAuth sign-in, all
205
+ * through OMP's own `/mcp` commands so the files it writes stay the ones it reads.
206
+ */
207
+ export class OmpMcps {
208
+ private readonly auths = new Map<string, AuthState>();
209
+ private readonly listings = new Map<string, { servers: OmpMcpServer[]; at: number }>();
210
+ /** Bumped by every change, so a listing that began before one cannot be stored after it. */
211
+ private generation = 0;
212
+ /** One config write at a time, so each one edits the file the previous one wrote. */
213
+ private readonly writes = new SerialMutationQueue();
214
+
215
+ async list(store: OmpStore | undefined, refresh: boolean): Promise<OmpMcpsView> {
216
+ let key: string;
217
+ try {
218
+ key = storeIdentity(store);
219
+ } catch (error) {
220
+ return { installed: true, servers: [], auths: [], error: publicMessage(error) };
221
+ }
222
+ const auths = [...this.auths.values()].filter((auth) => auth.directory === key).map(toAuth);
223
+ let command: OmpCommand;
224
+ try {
225
+ command = await resolveCommand();
226
+ } catch (error) {
227
+ return { installed: false, servers: [], auths, error: publicMessage(error) };
228
+ }
229
+ const cached = this.listings.get(key);
230
+ if (cached && !refresh && Date.now() - cached.at < LIST_TTL_MS) {
231
+ return { installed: true, servers: cached.servers, auths, error: null };
232
+ }
233
+ try {
234
+ const began = this.generation;
235
+ const printed = await runSlash(command, "/mcp list");
236
+ const servers = parseMcpList(printed);
237
+ if (servers.length === 0 && printed.trim() !== "" && !EMPTY_LIST.test(printed.trim())) {
238
+ throw new OmpAccountsError("omp's MCP list is not in a format this plugin can read");
239
+ }
240
+ if (began === this.generation) this.listings.set(key, { servers, at: Date.now() });
241
+ return { installed: true, servers, auths, error: null };
242
+ } catch (error) {
243
+ return { installed: true, servers: [], auths, error: publicMessage(error) };
244
+ }
245
+ }
246
+
247
+ /**
248
+ * omp's reauthorization copies the server's config when it starts and may write it back when the
249
+ * browser step ends, which would undo a change made in between. So a server with a sign-in open
250
+ * is left alone until that sign-in ends; another client's change is refused here, not hidden.
251
+ */
252
+ async run(
253
+ store: OmpStore | undefined,
254
+ name: string,
255
+ action: OmpMcpAction,
256
+ ): Promise<{ ok: boolean; message: string }> {
257
+ const command = await resolveCommand();
258
+ // `remove` defaults to the project in omp's working directory; this plugin only manages the
259
+ // user's own file.
260
+ const line =
261
+ action === "remove" ? `/mcp remove ${name} --scope user` : `/mcp ${action} ${name}`;
262
+ const printed = await this.writes.run(async () => {
263
+ // Checked here, in the queue, not before it: a sign-in registered while this change waited
264
+ // for its turn must still stop it.
265
+ if (action !== "test" && this.hasOpenAuth(store, name)) {
266
+ throw new OmpAccountsError(`Finish or cancel the sign-in for ${name} before changing it`);
267
+ }
268
+ return runSlash(command, line);
269
+ });
270
+ this.invalidate();
271
+ return actionResult(printed, action);
272
+ }
273
+
274
+ /** `target` was validated by the contract: one URL token, or a command line after `--`. */
275
+ async add(name: string, target: string): Promise<OmpMcpAddResult> {
276
+ const command = await resolveCommand();
277
+ const remote = /^https?:\/\//iu.test(target);
278
+ const line = remote
279
+ ? `/mcp add ${name} --scope user --url ${target}`
280
+ : `/mcp add ${name} --scope user -- ${target}`;
281
+ const printed = await this.writes.run(() => runSlash(command, line));
282
+ this.invalidate();
283
+ const added = actionResult(printed, "add");
284
+ if (!added.ok) return { ...added, check: null };
285
+ return this.check(command, name, added.message);
286
+ }
287
+
288
+ /** `/mcp add` never connects, so a mistyped address is only found by testing it. */
289
+ private async check(command: OmpCommand, name: string, added: string): Promise<OmpMcpAddResult> {
290
+ let tested: string;
291
+ try {
292
+ tested = (await runSlash(command, `/mcp test ${name}`)).trim();
293
+ } catch (error) {
294
+ const message = `${added} The connection check could not run: ${publicMessage(error)}`;
295
+ return { ok: true, message, check: null };
296
+ }
297
+ const check = readConnectionCheck(tested);
298
+ if (check === "connected") return { ok: true, message: `${added} ${tested}`, check };
299
+ if (check === "needs-authorization") {
300
+ return { ok: true, message: `${added} It needs a sign-in: use Authorize.`, check };
301
+ }
302
+ const reason = tested === "" ? "omp gave no answer" : tested;
303
+ const advice =
304
+ "Its connection check failed, so this may not be a working MCP server. Check the address.";
305
+ return { ok: true, message: `${added} ${advice} omp said: ${reason}`, check };
306
+ }
307
+
308
+ async startAuth(store: OmpStore | undefined, name: string): Promise<OmpMcpAuth> {
309
+ const command = await resolveCommand();
310
+ // Registered in the write queue: a change already running finishes before omp copies the
311
+ // server's config, and every later change finds this sign-in open and is refused.
312
+ const auth = await this.writes.run(async () => this.register(store, name));
313
+ void this.runAuth(auth, command);
314
+ return toAuth(auth);
315
+ }
316
+
317
+ private register(store: OmpStore | undefined, name: string): AuthState {
318
+ // Resolved first: a store that cannot be resolved must not cancel anyone's open sign-in.
319
+ const directory = storeIdentity(store);
320
+ // OAuth callbacks listen on fixed local ports, so only one authorization runs at a time.
321
+ for (const other of this.auths.values()) {
322
+ if (isOpen(other.step)) {
323
+ this.settle(other, "canceled", "A newer authorization replaced this one");
324
+ }
325
+ }
326
+ for (const [id, auth] of this.auths) {
327
+ if (auth.endedAt !== null && Date.now() - auth.endedAt > FINISHED_AUTH_TTL_MS) {
328
+ this.auths.delete(id);
329
+ }
330
+ }
331
+ const auth: AuthState = {
332
+ id: randomUUID(),
333
+ directory,
334
+ name,
335
+ step: "starting",
336
+ url: null,
337
+ instructions: null,
338
+ codePrompt: null,
339
+ message: null,
340
+ process: null,
341
+ timer: undefined,
342
+ endedAt: null,
343
+ };
344
+ this.auths.set(auth.id, auth);
345
+ return auth;
346
+ }
347
+
348
+ /**
349
+ * Finishes an authorization whose browser could not reach this host: omp's callback server is
350
+ * local, so the pasted redirect URL or code is handed to it from here.
351
+ */
352
+ async submitCode(authId: string, code: string): Promise<OmpMcpAuth> {
353
+ const auth = this.auths.get(authId);
354
+ if (!auth?.process || !isOpen(auth.step)) {
355
+ throw new OmpAccountsError("This authorization is no longer running. Start it again");
356
+ }
357
+ const target = auth.url ? callbackUrl(auth.url, code) : null;
358
+ if (!target) {
359
+ throw new OmpAccountsError(
360
+ "That is not the address omp is waiting for. Paste the full address from the browser's address bar, or the code",
361
+ );
362
+ }
363
+ auth.step = "verifying";
364
+ auth.message = null;
365
+ let accepted: boolean;
366
+ try {
367
+ // A redirect would leave omp's loopback address, which the pasted text may not name.
368
+ const response = await fetch(target, {
369
+ redirect: "error",
370
+ signal: AbortSignal.timeout(CALLBACK_TIMEOUT_MS),
371
+ });
372
+ accepted = response.ok;
373
+ } catch {
374
+ if (auth.step === "verifying") auth.step = "waiting";
375
+ throw new OmpAccountsError("omp is no longer listening for the sign-in. Start it again");
376
+ }
377
+ // omp prints the result once its callback server has the code; that moves the step on.
378
+ if (!accepted && auth.step === "verifying") {
379
+ auth.step = "waiting";
380
+ auth.message = "omp did not accept that. Paste the full address or the code again";
381
+ }
382
+ return toAuth(auth);
383
+ }
384
+
385
+ cancelAuth(authId: string): OmpMcpAuth | null {
386
+ const auth = this.auths.get(authId);
387
+ if (!auth) return null;
388
+ if (isOpen(auth.step)) this.settle(auth, "canceled", "Authorization was canceled");
389
+ return toAuth(auth);
390
+ }
391
+
392
+ private hasOpenAuth(store: OmpStore | undefined, name: string): boolean {
393
+ const key = storeIdentity(store);
394
+ return [...this.auths.values()].some(
395
+ (auth) => auth.directory === key && auth.name === name && isOpen(auth.step),
396
+ );
397
+ }
398
+
399
+ private invalidate(): void {
400
+ this.generation += 1;
401
+ this.listings.clear();
402
+ }
403
+
404
+ stop(): void {
405
+ for (const auth of this.auths.values()) {
406
+ if (isOpen(auth.step)) this.settle(auth, "canceled", null);
407
+ }
408
+ }
409
+
410
+ private async runAuth(auth: AuthState, command: OmpCommand): Promise<void> {
411
+ try {
412
+ const rpc = new OmpRpcProcess(command, {
413
+ onOutput: (text) => this.onOutput(auth, text),
414
+ onExit: () => this.settle(auth, "failed", "omp stopped before the authorization finished"),
415
+ });
416
+ if (!isOpen(auth.step)) {
417
+ rpc.close();
418
+ return;
419
+ }
420
+ auth.process = rpc;
421
+ auth.timer = setTimeout(
422
+ () => this.settle(auth, "failed", "Authorization timed out"),
423
+ AUTH_TIMEOUT_MS,
424
+ );
425
+ // omp acknowledges at once; how the authorization ended arrives later as printed text.
426
+ await rpc.request({ type: "prompt", message: `/mcp reauth ${auth.name}` });
427
+ } catch (error) {
428
+ if (isOpen(auth.step)) this.settle(auth, "failed", publicMessage(error));
429
+ }
430
+ }
431
+
432
+ /**
433
+ * A saved login does not make the address right: a server at the wrong path still fails its
434
+ * test. Say so here, where "You're signed in" would otherwise be followed by a failing Test.
435
+ */
436
+ private async confirmSignIn(auth: AuthState, signedIn: string): Promise<void> {
437
+ auth.step = "verifying";
438
+ auth.codePrompt = null;
439
+ let tested: string;
440
+ try {
441
+ tested = (await runSlash(await resolveCommand(), `/mcp test ${auth.name}`)).trim();
442
+ } catch (error) {
443
+ const reason = publicMessage(error);
444
+ const message = `${signedIn} The login is saved, but the connection check could not run: ${reason}`;
445
+ this.settle(auth, "failed", message);
446
+ return;
447
+ }
448
+ if (readConnectionCheck(tested) === "connected") {
449
+ this.settle(auth, "done", `${signedIn} ${tested}`);
450
+ return;
451
+ }
452
+ const reason = tested === "" ? "omp gave no answer" : tested;
453
+ this.settle(
454
+ auth,
455
+ "failed",
456
+ `Signed in and the login is saved, but ${auth.name} still fails its connection check, so the server address may be wrong. omp said: ${reason}`,
457
+ );
458
+ }
459
+
460
+ private onOutput(auth: AuthState, text: string): void {
461
+ if (!isOpen(auth.step)) return;
462
+ const output = readAuthOutput(text);
463
+ if (output.kind === "url") {
464
+ auth.url = output.url;
465
+ auth.instructions = output.instructions;
466
+ auth.codePrompt = "Paste the address from the browser, or the code";
467
+ auth.step = "waiting";
468
+ } else if (output.kind === "done") {
469
+ this.invalidate();
470
+ void this.confirmSignIn(auth, output.message);
471
+ return;
472
+ } else if (output.kind === "failed") {
473
+ this.settle(auth, "failed", output.message);
474
+ }
475
+ }
476
+
477
+ private settle(auth: AuthState, step: OmpLoginStep, message: string | null): void {
478
+ if (!isOpen(auth.step)) return;
479
+ clearTimeout(auth.timer);
480
+ auth.step = step;
481
+ auth.message = message;
482
+ auth.codePrompt = null;
483
+ auth.endedAt = Date.now();
484
+ auth.process?.close();
485
+ auth.process = null;
486
+ }
487
+ }
@@ -1,2 +1,2 @@
1
1
  /** Release Please keeps this bundle-safe constant aligned with package.json. */
2
- export const PASEO_OMP_PACKAGE_VERSION = "5.3.0"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "5.4.0"; // x-release-please-version
@@ -0,0 +1,128 @@
1
+ import { defineRpc } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { OmpLoginSchema } from "./omp-accounts";
4
+ import { OmpStoreSchema } from "./omp-store";
5
+
6
+ /** A server name as `omp` lists it. OMP allows spaces and other characters in names. */
7
+ export const OmpMcpListedNameSchema = z.string().min(1).max(200);
8
+
9
+ /**
10
+ * A name the plugin may put in a slash command: it never starts with `-` and has no spaces, so it
11
+ * is one argument. A listed server whose name does not fit can be shown but not acted on here.
12
+ */
13
+ export const OmpMcpNameSchema = z.string().regex(/^[a-zA-Z0-9_.:][a-zA-Z0-9_.:-]{0,99}$/u);
14
+
15
+ /** One line of `/mcp list`: `name | transport | state | target [source]`. */
16
+ export const OmpMcpServerSchema = z.object({
17
+ name: OmpMcpListedNameSchema,
18
+ transport: z.string(),
19
+ /** `enabled` or `disabled`, as OMP words it. */
20
+ state: z.string(),
21
+ /** The URL of a remote server, or the command line of a local one. */
22
+ target: z.string(),
23
+ /** Where the definition lives, such as `user` or a tool OMP imported it from. */
24
+ source: z.string(),
25
+ });
26
+ export type OmpMcpServer = z.infer<typeof OmpMcpServerSchema>;
27
+
28
+ /** An OAuth authorization in flight; the same steps as an account sign-in. */
29
+ export const OmpMcpAuthSchema = OmpLoginSchema.omit({ provider: true }).extend({
30
+ name: OmpMcpNameSchema,
31
+ });
32
+ export type OmpMcpAuth = z.infer<typeof OmpMcpAuthSchema>;
33
+
34
+ export const OmpMcpsViewSchema = z.object({
35
+ installed: z.boolean(),
36
+ servers: z.array(OmpMcpServerSchema),
37
+ auths: z.array(OmpMcpAuthSchema),
38
+ error: z.string().nullable(),
39
+ });
40
+ export type OmpMcpsView = z.infer<typeof OmpMcpsViewSchema>;
41
+
42
+ export const OMP_MCP_ACTIONS = ["test", "enable", "disable", "remove"] as const;
43
+ export const OmpMcpActionSchema = z.enum(OMP_MCP_ACTIONS);
44
+ export type OmpMcpAction = z.infer<typeof OmpMcpActionSchema>;
45
+
46
+ /**
47
+ * A remote server's URL, or the command line OMP starts for a local one. A URL goes after `--url`,
48
+ * so it is a single token; anything after `--` is the command.
49
+ */
50
+ export const OmpMcpTargetSchema = z
51
+ .string()
52
+ .trim()
53
+ .min(1)
54
+ .max(4096)
55
+ .regex(/^[^\r\n]+$/u, "Use a single line")
56
+ .refine(
57
+ (target) => !/^https?:\/\//iu.test(target) || /^\S+$/u.test(target),
58
+ "A server URL can't contain spaces",
59
+ )
60
+ // omp reads the command line as shell-like words and drops quote characters, which would store a
61
+ // different URL than the one typed.
62
+ .refine(
63
+ (target) => !/^https?:\/\//iu.test(target) || !/['"]/u.test(target),
64
+ "A server URL can't contain quotes; write them as %27 and %22",
65
+ );
66
+
67
+ export const listOmpMcps = defineRpc({
68
+ name: "paseo-omp.list-mcps",
69
+ /** `refresh` asks omp again instead of answering from the last listing. */
70
+ input: z.object({ store: OmpStoreSchema.optional(), refresh: z.boolean().optional() }),
71
+ output: OmpMcpsViewSchema,
72
+ });
73
+
74
+ /** What a connection check found: a server that answers, one that wants a sign-in (HTTP 401), or neither. */
75
+ export const OmpMcpCheckSchema = z.enum(["connected", "needs-authorization", "failed"]);
76
+ export type OmpMcpCheck = z.infer<typeof OmpMcpCheckSchema>;
77
+
78
+ export const OmpMcpAddResultSchema = z.object({
79
+ ok: z.boolean(),
80
+ message: z.string(),
81
+ /** omp's `/mcp add` only writes the file, so the server is tested right after. Null when the add failed or the test could not run. */
82
+ check: OmpMcpCheckSchema.nullable(),
83
+ });
84
+ export type OmpMcpAddResult = z.infer<typeof OmpMcpAddResultSchema>;
85
+
86
+ /** Adds the server to omp's user MCP file with `/mcp add`, then tests it. A server that fails the test stays added. */
87
+ export const addOmpMcp = defineRpc({
88
+ name: "paseo-omp.add-mcp",
89
+ input: z.object({
90
+ store: OmpStoreSchema.optional(),
91
+ name: OmpMcpNameSchema,
92
+ target: OmpMcpTargetSchema,
93
+ }),
94
+ output: OmpMcpAddResultSchema,
95
+ });
96
+
97
+ /** Runs the matching `/mcp` command through omp. `ok` is false when omp reports the command failed. */
98
+ export const runOmpMcpAction = defineRpc({
99
+ name: "paseo-omp.run-mcp-action",
100
+ input: z.object({
101
+ store: OmpStoreSchema.optional(),
102
+ name: OmpMcpNameSchema,
103
+ action: OmpMcpActionSchema,
104
+ }),
105
+ output: z.object({ ok: z.boolean(), message: z.string() }),
106
+ });
107
+
108
+ export const startOmpMcpAuth = defineRpc({
109
+ name: "paseo-omp.start-mcp-auth",
110
+ input: z.object({ store: OmpStoreSchema.optional(), name: OmpMcpNameSchema }),
111
+ output: OmpMcpAuthSchema,
112
+ });
113
+
114
+ export const submitOmpMcpAuthCode = defineRpc({
115
+ name: "paseo-omp.submit-mcp-auth-code",
116
+ input: z.object({
117
+ store: OmpStoreSchema.optional(),
118
+ authId: z.string(),
119
+ code: z.string().trim().min(1).max(4096),
120
+ }),
121
+ output: OmpMcpAuthSchema,
122
+ });
123
+
124
+ export const cancelOmpMcpAuth = defineRpc({
125
+ name: "paseo-omp.cancel-mcp-auth",
126
+ input: z.object({ store: OmpStoreSchema.optional(), authId: z.string() }),
127
+ output: OmpMcpAuthSchema.nullable(),
128
+ });