@oxy-hq/cli 0.5.0 → 0.6.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,902 @@
1
+ #!/usr/bin/env node
2
+ import { A as parseJson, B as usageError, C as comparablePath, D as runChecksCore, E as searchRoutes, F as paramsToQuery, I as parseFields, L as CliError, M as isExternalSurface, N as normalizePath, O as requireSandboxName, P as substitutePlaceholders, R as ExitCode, S as envShow, T as loadOpenApi, _ as invocationsList, a as previewRunsList, b as envDelete, c as runFailed, d as previewDelete, f as previewFailed, g as invocationsHeld, h as fetchLogs, i as previewRunGet, j as request, k as runJq, l as previewChecks, m as previewShow, n as publish, o as previewSubmitRun, p as previewList, r as parseVariables, s as requireRunKind, t as createContext, u as previewCreate, v as fnCall, w as loadCatalog, x as envList, y as envCreate, z as exitCodeName } from "./main.mjs";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
+
10
+ //#region src/commands/mcp.ts
11
+ /**
12
+ * `oxyc mcp` — the Oxy API as MCP tools, over stdio.
13
+ *
14
+ * NOT THE SAME THING AS `oxy mcp`. That one is workspace tooling: it takes a
15
+ * local checkout and exposes the semantic model, automations and `.sql` files
16
+ * in it. This one takes a TOKEN and exposes the deployment's HTTP API — the
17
+ * same surface `oxyc api` reaches, for an agent that would rather call a tool
18
+ * than shell out. Different input, different audience, no overlap.
19
+ *
20
+ * FOUR GENERIC TOOLS FOR THE WHOLE API — the design decision that makes most
21
+ * of it affordable.
22
+ *
23
+ * The obvious shape is one tool per endpoint, and it is the wrong one: the API
24
+ * has ~670 routes, an agent runtime ships every tool's JSON schema in every
25
+ * request, and that is tens of kilobytes of context spent on each turn before
26
+ * a single question is asked. It would also go stale on every deploy, since
27
+ * the tool list would be baked into this package rather than read from the
28
+ * deployment.
29
+ *
30
+ * So discovery stays a QUESTION the agent asks (`oxy_routes`, `oxy_schema`)
31
+ * rather than a payload it carries, exactly as the CLI does it, for
32
+ * everything a generic request can do safely.
33
+ *
34
+ * TWO NAMED EXCEPTIONS: `SANDBOX_TOOLS` and `PREVIEW_TOOLS` below. The sandbox
35
+ * loop and the workspace-previews loop are meant to run UNSUPERVISED — create
36
+ * a sandbox, publish into it, call a function, tear it down — and that needs
37
+ * per-operation validation (the `dev-<handle>` grammar, a confirm gate before
38
+ * a delete, a hard refusal of `--app-env` outside `dev-<handle>` on the
39
+ * publish tool) that `oxy_request` has no way to carry. Each of those tools
40
+ * calls its CLI verb's own request-building function (`env.ts`, `fn.ts`,
41
+ * `checks.ts`, `preview.ts`, `preview-runs.ts`, …), so there is exactly one
42
+ * implementation of each request, and a tool's result is the same JSON
43
+ * document that verb's `--json` prints. `mcp.test.ts` pins the full tool list
44
+ * and a raised (and justified) per-turn schema budget.
45
+ *
46
+ * Auth, target resolution and placeholder substitution are the CLI's — the
47
+ * same `Context`, so a token cached by `oxyc login` works
48
+ * here with no separate setup, and `{org}` / `{workspace}` resolve the same
49
+ * way.
50
+ */
51
+ /**
52
+ * Package version, reported in the MCP handshake.
53
+ *
54
+ * Read from `package.json` rather than restated, so a release bump cannot
55
+ * leave the server announcing a version nobody shipped.
56
+ */
57
+ const VERSION = (() => {
58
+ try {
59
+ const here = dirname(fileURLToPath(import.meta.url));
60
+ for (const candidate of [resolve(here, "..", "package.json"), resolve(here, "..", "..", "package.json")]) if (existsSync(candidate)) return JSON.parse(readFileSync(candidate, "utf8")).version ?? "0.0.0";
61
+ } catch {}
62
+ return "0.0.0";
63
+ })();
64
+ /**
65
+ * A tool result. MCP wants content blocks; everything here is text, because
66
+ * the caller is a language model and the payloads are JSON or markdown.
67
+ */
68
+ function text(body, isError = false) {
69
+ return {
70
+ content: [{
71
+ type: "text",
72
+ text: body
73
+ }],
74
+ isError
75
+ };
76
+ }
77
+ /**
78
+ * A tool result carrying one JSON document — the same shape the matching
79
+ * verb's `--json` prints, so a tool's result and the CLI's output never
80
+ * drift apart. On failure the exit-code class is appended, same spelling as
81
+ * the generic catch-all below (`[exit N NAME]`), so an agent branches on it
82
+ * the way it would on `oxyc`'s own exit code.
83
+ */
84
+ function jsonResult(data, opts = {}) {
85
+ const body = JSON.stringify(data);
86
+ if (!opts.isError) return text(body);
87
+ const code = opts.code ?? ExitCode.FAILURE;
88
+ return text(`${body}\n\n[exit ${code} ${exitCodeName(code)}]`, true);
89
+ }
90
+ const TOOLS = [
91
+ {
92
+ name: "oxy_routes",
93
+ description: "List the API endpoints this Oxy deployment mounts, with what each one does. ALWAYS call this before oxy_request rather than guessing a path. Pass a filter (matched against method, path, surface and description) to narrow it — unfiltered is ~670 routes. Above 60 matches the descriptions are dropped and only method, path and credential come back, so narrow enough to stay under that when you need to know what an endpoint does; past ~400 it is refused outright.",
94
+ inputSchema: {
95
+ type: "object",
96
+ properties: {
97
+ filter: {
98
+ type: "string",
99
+ description: "Substring to narrow by, e.g. 'threads', 'sql', 'admin', 'semantic'."
100
+ },
101
+ all: {
102
+ type: "boolean",
103
+ description: "Include ide-only and worker-only routes. Off by default: those are mounted on one instance of the fleet, so a caller hitting the load balancer cannot reach them directly."
104
+ }
105
+ }
106
+ }
107
+ },
108
+ {
109
+ name: "oxy_schema",
110
+ description: "The request and response schema for ONE endpoint, so a body can be built correctly. Covers the data plane (SQL, semantic query, and the org/workspace lookups); a blank result means undocumented, not nonexistent — use oxy_routes to confirm the endpoint exists.",
111
+ inputSchema: {
112
+ type: "object",
113
+ properties: {
114
+ path: {
115
+ type: "string",
116
+ description: "Endpoint path, e.g. '{workspace}/sql/query'."
117
+ },
118
+ method: {
119
+ type: "string",
120
+ description: "Narrow to one HTTP method."
121
+ }
122
+ },
123
+ required: ["path"]
124
+ }
125
+ },
126
+ {
127
+ name: "oxy_request",
128
+ description: "Make an authenticated request to the Oxy API. The credential is picked from the path (/api/** takes a bearer, /external/api/** an API key). Placeholders {org}, {workspace}, {project}, {customer} and {me} are substituted from context. Read freely; ask the human before any mutating request against production.",
129
+ inputSchema: {
130
+ type: "object",
131
+ properties: {
132
+ path: {
133
+ type: "string",
134
+ description: "Path relative to /api, e.g. '{org}/workspaces'."
135
+ },
136
+ method: {
137
+ type: "string",
138
+ description: "HTTP method. Defaults to GET, or POST with fields."
139
+ },
140
+ fields: {
141
+ type: "object",
142
+ description: "Request parameters. Sent as a JSON body on POST/PUT/PATCH, or as query parameters on GET/HEAD/DELETE. Values keep their JSON type."
143
+ },
144
+ jq: {
145
+ type: "string",
146
+ description: "A jq program to reduce the response before it is returned. Use it — a full list response is far more context than the two fields you need."
147
+ }
148
+ },
149
+ required: ["path"]
150
+ }
151
+ },
152
+ {
153
+ name: "oxy_whoami",
154
+ description: "Which deployment this is pointed at and who the token belongs to. Use it when a call returns 401/403, or a 200 with a null body — on this API an expired session answers 200 null rather than 401, and this tells the two apart.",
155
+ inputSchema: {
156
+ type: "object",
157
+ properties: {}
158
+ }
159
+ }
160
+ ];
161
+ /**
162
+ * THE SANDBOX LOOP, AS TOOLS — the deliberate exception to "four, not one per
163
+ * endpoint" above. A generic `oxy_request` can call these same routes, but it
164
+ * cannot carry the per-operation validation that makes the loop safe for an
165
+ * agent to drive unsupervised: the dev-<handle> grammar, the confirm-before-
166
+ * delete gate, and the hard refusal of a sandbox publish outside dev-<handle>.
167
+ * Every one of these reuses its CLI verb's own request-building function —
168
+ * see `env.ts` / `fn.ts` / `checks.ts` / `invocations.ts` / `logs.ts` /
169
+ * `publish.ts` — so there is exactly one implementation of each request, and
170
+ * the tool result is the same JSON document that verb's `--json` prints.
171
+ *
172
+ * Each description says what it returns AND what to call next, so the loop
173
+ * reads off the tool list alone: env_create → publish_sandbox → fn_call /
174
+ * checks_run → invocations_list / invocations_held / logs → iterate from
175
+ * publish_sandbox → env_delete.
176
+ */
177
+ const SANDBOX_TOOLS = [
178
+ {
179
+ name: "oxy_env_create",
180
+ description: "Create a dev-<handle> SANDBOX of a custom app — its own build pointer, storage silo, secrets and Airhouse sibling, isolated from production and from every other sandbox. Starts with no build. Returns the Environment (status, build, url). Call oxy_publish_sandbox next to give it one.",
181
+ inputSchema: {
182
+ type: "object",
183
+ properties: {
184
+ app: {
185
+ type: "string",
186
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
187
+ },
188
+ name: {
189
+ type: "string",
190
+ description: "dev-<handle> — 1-12 lowercase letters, digits and single hyphens."
191
+ }
192
+ },
193
+ required: ["app", "name"]
194
+ }
195
+ },
196
+ {
197
+ name: "oxy_env_list",
198
+ description: "List a custom app's environments — production, staging and every dev-<handle> sandbox — each with its status and build. Use it to find a sandbox's name before oxy_env_show, oxy_publish_sandbox or oxy_env_delete.",
199
+ inputSchema: {
200
+ type: "object",
201
+ properties: { app: {
202
+ type: "string",
203
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
204
+ } },
205
+ required: ["app"]
206
+ }
207
+ },
208
+ {
209
+ name: "oxy_env_show",
210
+ description: "One environment's detail — status, build, url. Call it after oxy_publish_sandbox to confirm a build landed, or before oxy_fn_call to confirm one exists.",
211
+ inputSchema: {
212
+ type: "object",
213
+ properties: {
214
+ app: {
215
+ type: "string",
216
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
217
+ },
218
+ name: {
219
+ type: "string",
220
+ description: "production, staging, or dev-<handle>."
221
+ }
222
+ },
223
+ required: ["app", "name"]
224
+ }
225
+ },
226
+ {
227
+ name: "oxy_env_delete",
228
+ description: "DESTRUCTIVE — tears down a sandbox's storage silo, secrets and Airhouse sibling for good. Requires confirm=true: there is no terminal to ask on here, so the delete refuses without it, the same way `oxyc env delete` refuses without --yes off a TTY. Set waitSeconds to avoid polling oxy_env_show yourself.",
229
+ inputSchema: {
230
+ type: "object",
231
+ properties: {
232
+ app: {
233
+ type: "string",
234
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
235
+ },
236
+ name: {
237
+ type: "string",
238
+ description: "dev-<handle> — production and staging can never be deleted."
239
+ },
240
+ confirm: {
241
+ type: "boolean",
242
+ description: "Must be true, or the call is refused."
243
+ },
244
+ waitSeconds: {
245
+ type: "number",
246
+ description: "Block until torn down, or this many seconds pass (no wait by default)."
247
+ }
248
+ },
249
+ required: [
250
+ "app",
251
+ "name",
252
+ "confirm"
253
+ ]
254
+ }
255
+ },
256
+ {
257
+ name: "oxy_publish_sandbox",
258
+ description: "DESTRUCTIVE (to the sandbox's build, not production) — build the app in `dir` (default: the current directory) and publish it to a dev-<handle> sandbox's build pointer. REQUIRES a dev-<handle> appEnv and refuses production, staging, or any attempt to promote — a sandbox build is never promoted; publish the same tree to staging and promote that instead, outside this tool. Runs the app's own build command, so it executes whatever package scripts oxy-app.json declares. Returns the publish result (build id, url). Call oxy_fn_call or oxy_checks_run with the same appEnv next.",
259
+ inputSchema: {
260
+ type: "object",
261
+ properties: {
262
+ appEnv: {
263
+ type: "string",
264
+ description: "dev-<handle> — anything else (production, staging) is refused."
265
+ },
266
+ dir: {
267
+ type: "string",
268
+ description: "App directory to publish (default: cwd)."
269
+ },
270
+ app: {
271
+ type: "string",
272
+ description: "App slug (default: oxy-app.json's slug, or OXY_APP)."
273
+ },
274
+ org: {
275
+ type: "string",
276
+ description: "Org slug (default: oxy-app.json's orgSlug, or OXY_ORG)."
277
+ }
278
+ },
279
+ required: ["appEnv"]
280
+ }
281
+ },
282
+ {
283
+ name: "oxy_fn_call",
284
+ description: "Call a custom app's Oxy Function directly (POST .../fn/<function>) and return its result: {ok, status, body, logs, invocationId, error}. isError is set when the FUNCTION failed (distinct from a transport failure, which throws). Needs a build in that environment — oxy_publish_sandbox or oxy_env_show confirms one exists. Call oxy_logs or oxy_invocations_held with the returned invocationId to see why it failed.",
285
+ inputSchema: {
286
+ type: "object",
287
+ properties: {
288
+ app: {
289
+ type: "string",
290
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
291
+ },
292
+ function: {
293
+ type: "string",
294
+ description: "The Oxy Function's name."
295
+ },
296
+ appEnv: {
297
+ type: "string",
298
+ description: "production (default), staging, or dev-<handle>."
299
+ },
300
+ data: {
301
+ type: "string",
302
+ description: "JSON request body (default \"{}\")."
303
+ },
304
+ timeoutSeconds: {
305
+ type: "number",
306
+ description: "Client-side timeout (default 60)."
307
+ }
308
+ },
309
+ required: ["app", "function"]
310
+ }
311
+ },
312
+ {
313
+ name: "oxy_checks_run",
314
+ description: "Run every function the app marked \"check\": true in one environment, and wait for each to a terminal status. Returns {app, checks:[{name, status, passed, error, durationMs}]}; isError is set when any check failed or timed out. Run this right after oxy_publish_sandbox to verify a build.",
315
+ inputSchema: {
316
+ type: "object",
317
+ properties: {
318
+ app: {
319
+ type: "string",
320
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
321
+ },
322
+ appEnv: {
323
+ type: "string",
324
+ description: "production (default), staging, or dev-<handle>."
325
+ },
326
+ timeoutSeconds: {
327
+ type: "number",
328
+ description: "Per-check timeout (default 300)."
329
+ }
330
+ },
331
+ required: ["app"]
332
+ }
333
+ },
334
+ {
335
+ name: "oxy_invocations_list",
336
+ description: "List what ran in an app's environment — every function invocation, newest first, with its status. Use it to confirm oxy_fn_call or oxy_checks_run reached the sandbox, or to find an invocation id for oxy_invocations_held.",
337
+ inputSchema: {
338
+ type: "object",
339
+ properties: {
340
+ app: {
341
+ type: "string",
342
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
343
+ },
344
+ appEnv: {
345
+ type: "string",
346
+ description: "Narrow to one environment."
347
+ },
348
+ build: {
349
+ type: "string",
350
+ description: "Narrow to one build (its id, or the build UUID)."
351
+ },
352
+ function: {
353
+ type: "string",
354
+ description: "Narrow to one function."
355
+ },
356
+ limit: {
357
+ type: "number",
358
+ description: "Max rows (default 50)."
359
+ }
360
+ },
361
+ required: ["app"]
362
+ }
363
+ },
364
+ {
365
+ name: "oxy_invocations_held",
366
+ description: "What a non-production invocation's write policy HELD instead of performing — production's would-be effect, recorded rather than run. Empty for a production invocation, since nothing is held there. Call with an id from oxy_invocations_list or oxy_fn_call's invocationId.",
367
+ inputSchema: {
368
+ type: "object",
369
+ properties: {
370
+ app: {
371
+ type: "string",
372
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
373
+ },
374
+ invocationId: {
375
+ type: "string",
376
+ description: "From oxy_invocations_list or oxy_fn_call."
377
+ }
378
+ },
379
+ required: ["app", "invocationId"]
380
+ }
381
+ },
382
+ {
383
+ name: "oxy_logs",
384
+ description: "An app's persisted ctx.log() / console.* output, newest-relevant window first. Use it to debug a function that oxy_fn_call or oxy_checks_run reported as failed.",
385
+ inputSchema: {
386
+ type: "object",
387
+ properties: {
388
+ app: {
389
+ type: "string",
390
+ description: "\"<org-slug>/<app-slug>\" or the app UUID."
391
+ },
392
+ appEnv: {
393
+ type: "string",
394
+ description: "Narrow to one environment (default: production only)."
395
+ },
396
+ invocation: {
397
+ type: "string",
398
+ description: "Narrow to one invocation id."
399
+ },
400
+ request: {
401
+ type: "string",
402
+ description: "Narrow to one request id."
403
+ },
404
+ hours: {
405
+ type: "number",
406
+ description: "Window size in hours (default 24, max 168)."
407
+ },
408
+ limit: {
409
+ type: "number",
410
+ description: "Max rows (default 100, max 500)."
411
+ }
412
+ },
413
+ required: ["app"]
414
+ }
415
+ }
416
+ ];
417
+ /**
418
+ * WORKSPACE PREVIEWS, AS TOOLS — the same exception as `SANDBOX_TOOLS` above,
419
+ * for the same reason: the run-kind grammar and the create/wait/timeout
420
+ * contract are per-operation validation a generic `oxy_request` cannot carry.
421
+ * Each reuses its `oxyc preview` verb's own request-building function (see
422
+ * `preview.ts` / `preview-runs.ts`), so there is one implementation of each
423
+ * request and the tool result matches that verb's `--json` output.
424
+ *
425
+ * The loop: preview_create (waits for the compile) → preview_checks → " +
426
+ * preview_run (procedure or airway_sample) → preview_run_show (waits for the " +
427
+ * run) → preview_runs_list to see transform_build/compare runs the server " +
428
+ * queued on its own → preview_delete when done.
429
+ */
430
+ const PREVIEW_TOOLS = [
431
+ {
432
+ name: "oxy_preview_create",
433
+ description: "Preview a workspace branch: compile its head into a staging revision (or reuse the ready one for that commit) and start serving it under x-oxy-preview-revision. Returns the PreviewItem ({branch, status, revision_id, checks, ...}) — idempotent, so calling it again on the same commit is free. Set waitSeconds to avoid polling oxy_preview_show yourself; isError is then set on a compile that failed. Call oxy_preview_checks next.",
434
+ inputSchema: {
435
+ type: "object",
436
+ properties: {
437
+ branch: {
438
+ type: "string",
439
+ description: "The branch to preview. Not the default branch."
440
+ },
441
+ waitSeconds: {
442
+ type: "number",
443
+ description: "Block until the compile is ready or failed, up to this many seconds (no wait by default)."
444
+ }
445
+ },
446
+ required: ["branch"]
447
+ }
448
+ },
449
+ {
450
+ name: "oxy_preview_list",
451
+ description: "List every branch staff are previewing in this workspace, most recently touched first, each with its compile status and checks summary. Use it to find a branch name before the other preview tools.",
452
+ inputSchema: {
453
+ type: "object",
454
+ properties: {}
455
+ }
456
+ },
457
+ {
458
+ name: "oxy_preview_show",
459
+ description: "One branch's preview — status and checks summary (PreviewItem). Not a server route: filters oxy_preview_list's result by branch, and fails NOT_FOUND when the branch has no preview.",
460
+ inputSchema: {
461
+ type: "object",
462
+ properties: { branch: {
463
+ type: "string",
464
+ description: "The previewed branch."
465
+ } },
466
+ required: ["branch"]
467
+ }
468
+ },
469
+ {
470
+ name: "oxy_preview_delete",
471
+ description: "DESTRUCTIVE — stop previewing a branch: cancels its queued runs and releases its staging revision. Requires confirm=true (there is no terminal to ask on here).",
472
+ inputSchema: {
473
+ type: "object",
474
+ properties: {
475
+ branch: {
476
+ type: "string",
477
+ description: "The previewed branch to stop previewing."
478
+ },
479
+ confirm: {
480
+ type: "boolean",
481
+ description: "Must be true, or the call is refused."
482
+ }
483
+ },
484
+ required: ["branch", "confirm"]
485
+ }
486
+ },
487
+ {
488
+ name: "oxy_preview_checks",
489
+ description: "The Airway change check of a preview's current revision: each changed .airway.yml pipeline and whether merging it needs a Reset schema, and each changed automation (\"auto\" transforms are built in the preview and compared with live; \"manual\" ones say why not). \"pending\" with no pipelines until the check has run — call oxy_preview_show or retry shortly.",
490
+ inputSchema: {
491
+ type: "object",
492
+ properties: { branch: {
493
+ type: "string",
494
+ description: "The previewed branch."
495
+ } },
496
+ required: ["branch"]
497
+ }
498
+ },
499
+ {
500
+ name: "oxy_preview_run",
501
+ description: "Start a held dry run of a previewed branch: a procedure (every write held or, on the managed Airhouse, redirected into the preview's own schemas) or an airway_sample (a bounded window of a pipeline into the preview's schemas). transform_build and compare runs are queued by the server's own change check and cannot be started here — read them back with oxy_preview_runs_list / oxy_preview_run_show instead. Returns {run_id, state}. Set waitSeconds to avoid polling oxy_preview_run_show yourself; isError is then set if the run failed or was cancelled. Needs OXY_PREVIEW_RUNS enabled on the deployment.",
502
+ inputSchema: {
503
+ type: "object",
504
+ properties: {
505
+ branch: {
506
+ type: "string",
507
+ description: "The previewed branch to run against."
508
+ },
509
+ kind: {
510
+ type: "string",
511
+ description: "\"procedure\" or \"airway_sample\"."
512
+ },
513
+ ref: {
514
+ type: "string",
515
+ description: "The automation path (procedure) or .airway.yml path (airway_sample)."
516
+ },
517
+ variables: {
518
+ type: "string",
519
+ description: "procedure: JSON object of the automation's variables."
520
+ },
521
+ readLiveOnly: {
522
+ type: "boolean",
523
+ description: "procedure: read live tables even where the preview holds a copy."
524
+ },
525
+ windowFrom: {
526
+ type: "string",
527
+ description: "airway_sample: window start, RFC 3339."
528
+ },
529
+ windowTo: {
530
+ type: "string",
531
+ description: "airway_sample: window end, RFC 3339."
532
+ },
533
+ resources: {
534
+ type: "array",
535
+ items: { type: "string" },
536
+ description: "airway_sample: the resources to read, for a multi-resource source."
537
+ },
538
+ waitSeconds: {
539
+ type: "number",
540
+ description: "Block until the run finishes, up to this many seconds (no wait by default)."
541
+ }
542
+ },
543
+ required: [
544
+ "branch",
545
+ "kind",
546
+ "ref"
547
+ ]
548
+ }
549
+ },
550
+ {
551
+ name: "oxy_preview_runs_list",
552
+ description: "A branch's held runs, newest first — procedure, transform_build, compare and airway_sample alike, with each one's state and outcome. Use it to find a run_id for oxy_preview_run_show, including the transform_build/compare runs the server queues on its own that oxy_preview_run cannot start.",
553
+ inputSchema: {
554
+ type: "object",
555
+ properties: { branch: {
556
+ type: "string",
557
+ description: "The previewed branch."
558
+ } },
559
+ required: ["branch"]
560
+ }
561
+ },
562
+ {
563
+ name: "oxy_preview_run_show",
564
+ description: "One run's detail: its steps (with what each held or redirected), and — for transform_build/compare — the compare-with-live outcome, or — for airway_sample — the sample's ask and result. Set waitSeconds to avoid polling yourself; isError is then set if the run failed or was cancelled.",
565
+ inputSchema: {
566
+ type: "object",
567
+ properties: {
568
+ runId: {
569
+ type: "string",
570
+ description: "From oxy_preview_run or oxy_preview_runs_list."
571
+ },
572
+ waitSeconds: {
573
+ type: "number",
574
+ description: "Block until the run finishes, up to this many seconds (no wait by default)."
575
+ }
576
+ },
577
+ required: ["runId"]
578
+ }
579
+ }
580
+ ];
581
+ const ALL_TOOLS = [
582
+ ...TOOLS,
583
+ ...SANDBOX_TOOLS,
584
+ ...PREVIEW_TOOLS
585
+ ];
586
+ /**
587
+ * Above this many matches, `oxy_routes` drops the descriptions.
588
+ *
589
+ * DEGRADES, IT DOES NOT REFUSE — the same shape as `oxyc routes`, which picks
590
+ * `renderDetailed` under 40 matches and the compact method+path table above it
591
+ * (`discover.ts`). The expensive field is `description`, not the row: a trimmed
592
+ * row is a few tens of bytes, so several hundred still fit in a result an agent
593
+ * can read, while the descriptions are what turn a broad match into hundreds of
594
+ * KB of context spent before a question is asked.
595
+ *
596
+ * The threshold is on the COUNT, not on whether a `filter` was supplied — a
597
+ * filter is not evidence of narrowing. `searchRoutes` matches a substring of
598
+ * method, path, surface or description, so `"admin"`, `"workspace"` and
599
+ * `"query"` are all filters a model reaches for in good faith that clear this.
600
+ */
601
+ const MAX_DESCRIBED_ROUTES = 60;
602
+ /**
603
+ * And above THIS many, there is nothing useful to return at all.
604
+ *
605
+ * Deliberately far above the threshold that drops descriptions: refusing is the
606
+ * answer only when even the trimmed listing would be a context dump, which for
607
+ * a deployment of ~670 routes means "you asked for effectively all of them".
608
+ */
609
+ const MAX_ROUTES_PER_RESULT = 400;
610
+ /** `{ a: 1 }` → the `-f`/`-F` pairs `parseFields` understands. */
611
+ function fieldPairs(fields) {
612
+ if (!fields) return [];
613
+ return Object.entries(fields).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
614
+ }
615
+ /**
616
+ * Check the arguments the schema says are required.
617
+ *
618
+ * `inputSchema.required` is ADVISORY on the low-level `Server` — it is handed
619
+ * to the model, not enforced by the transport. Without this, `oxy_schema` with
620
+ * no `path` matched every path and returned the whole OpenAPI document, and
621
+ * `oxy_request` with none built a request to `/api/`.
622
+ */
623
+ function requireArgs(name, args, required) {
624
+ const missing = required.filter((k) => {
625
+ const v = args[k];
626
+ return v === void 0 || v === null || typeof v === "string" && v.trim() === "";
627
+ });
628
+ if (missing.length > 0) throw new CliError(`${name} needs ${missing.join(", ")}`, { code: ExitCode.USAGE });
629
+ }
630
+ async function callTool(ctx, name, args) {
631
+ switch (name) {
632
+ case "oxy_routes": {
633
+ const catalog = await loadCatalog({
634
+ target: ctx.target(),
635
+ bearer: ctx.maybeBearer()
636
+ });
637
+ const filter = args.filter?.trim();
638
+ let matches = searchRoutes(catalog, filter || void 0);
639
+ if (!args.all) matches = matches.filter((r) => r.role === "fleet-ok");
640
+ const staleNote = catalog.stale ? "NOTE: this route table came from a stale local cache; the deployment was unreachable.\n\n" : "";
641
+ const asked = filter ? ` ${JSON.stringify(filter)}` : "";
642
+ if (matches.length > MAX_ROUTES_PER_RESULT) return text(`${staleNote}${matches.length} routes match${asked}, which is effectively the whole deployment. Call oxy_routes again with a narrower \`filter\` (matched against method, path, surface and description), e.g. "threads", "sql", "semantic", "admin".`, true);
643
+ if (matches.length === 0) return text(`${staleNote}No route matches ${JSON.stringify(filter ?? "")}. Try a broader filter, or pass all=true to include ide-only and worker-only mounts.`, true);
644
+ const described = matches.length <= MAX_DESCRIBED_ROUTES;
645
+ const trimmed = matches.map((r) => described ? {
646
+ method: r.method,
647
+ path: r.path,
648
+ credential: r.credential,
649
+ description: r.description
650
+ } : {
651
+ method: r.method,
652
+ path: r.path,
653
+ credential: r.credential
654
+ });
655
+ return text(`${staleNote}${described ? "" : `NOTE: ${matches.length} routes match${asked} — too many to describe, so each row is method, path and credential WITHOUT its description. Narrow the \`filter\` to ${MAX_DESCRIBED_ROUTES} or fewer matches to get the descriptions back.\n\n`}${JSON.stringify(trimmed)}`);
656
+ }
657
+ case "oxy_schema": {
658
+ requireArgs("oxy_schema", args, ["path"]);
659
+ const doc = await loadOpenApi({
660
+ target: ctx.target(),
661
+ bearer: ctx.maybeBearer()
662
+ });
663
+ const wanted = typeof args.path === "string" ? args.path : "";
664
+ const method = args.method;
665
+ const paths = Object.entries(doc.paths ?? {});
666
+ const exact = paths.filter(([p]) => comparablePath(p) === comparablePath(wanted));
667
+ const hit = exact.length > 0 ? exact : paths.filter(([p]) => comparablePath(p).includes(comparablePath(wanted)));
668
+ if (hit.length === 0) return text(`No documented schema for ${wanted}. The OpenAPI document covers the data plane only — call oxy_routes with a filter to confirm the endpoint exists.`, true);
669
+ const selected = Object.fromEntries(hit.map(([p, ops]) => [p, method ? Object.fromEntries(Object.entries(ops).filter(([verb]) => verb.toLowerCase() === method.toLowerCase())) : ops]));
670
+ return text(JSON.stringify({
671
+ paths: selected,
672
+ components: doc.components
673
+ }, null, 2));
674
+ }
675
+ case "oxy_request": {
676
+ requireArgs("oxy_request", args, ["path"]);
677
+ const raw = typeof args.path === "string" ? args.path : "";
678
+ const method = (typeof args.method === "string" ? args.method.toUpperCase() : "") || void 0;
679
+ const fields = parseFields([], fieldPairs(args.fields));
680
+ const verb = method ?? (fields.present ? "POST" : "GET");
681
+ const carriesBody = ![
682
+ "GET",
683
+ "HEAD",
684
+ "DELETE"
685
+ ].includes(verb);
686
+ let path = substitutePlaceholders(normalizePath(raw), ctx.placeholders());
687
+ let body;
688
+ if (fields.present) {
689
+ if (carriesBody) body = JSON.stringify(fields.params);
690
+ else {
691
+ const query = paramsToQuery(fields.params);
692
+ if (query) path += (path.includes("?") ? "&" : "?") + query;
693
+ }
694
+ }
695
+ const apiKey = ctx.apiKey();
696
+ const external = isExternalSurface(path);
697
+ const response = await request({
698
+ target: ctx.target(),
699
+ path,
700
+ method: verb,
701
+ body,
702
+ bearer: external && apiKey ? ctx.maybeBearer() : ctx.bearer(),
703
+ apiKey
704
+ });
705
+ if (response.status < 200 || response.status >= 300) return text(`HTTP ${response.status} ${response.statusText}\n${response.body}`, true);
706
+ if (response.body.trim() === "null") return text("null\n\n(NOTE: a 200 with a null body can mean an expired session on this API, not 'no such thing'. Call oxy_whoami to tell them apart.)");
707
+ const jq = args.jq;
708
+ if (jq) return text(runJq(response.body, jq));
709
+ return text(response.body);
710
+ }
711
+ case "oxy_whoami": {
712
+ const target = ctx.target();
713
+ const response = await request({
714
+ target,
715
+ path: "/api/user",
716
+ method: "GET",
717
+ bearer: ctx.bearer()
718
+ });
719
+ const payload = parseJson(response.body);
720
+ if (payload === null || payload === void 0) return text(`target: ${target}\nThe token no longer resolves to a user — the session has expired. Ask the human to run \`oxyc login\`.`, true);
721
+ return text(JSON.stringify({
722
+ target,
723
+ user: payload
724
+ }, null, 2));
725
+ }
726
+ case "oxy_env_create":
727
+ requireArgs("oxy_env_create", args, ["app", "name"]);
728
+ return jsonResult(await envCreate(ctx, String(args.app), String(args.name)));
729
+ case "oxy_env_list":
730
+ requireArgs("oxy_env_list", args, ["app"]);
731
+ return jsonResult({ environments: await envList(ctx, String(args.app)) });
732
+ case "oxy_env_show":
733
+ requireArgs("oxy_env_show", args, ["app", "name"]);
734
+ return jsonResult(await envShow(ctx, String(args.app), String(args.name)));
735
+ case "oxy_env_delete":
736
+ requireArgs("oxy_env_delete", args, ["app", "name"]);
737
+ if (args.confirm !== true) throw usageError("oxy_env_delete needs confirm=true", "there is no terminal to ask on here — pass confirm=true once you mean it");
738
+ return jsonResult(await envDelete(ctx, String(args.app), String(args.name), {
739
+ yes: true,
740
+ waitSeconds: args.waitSeconds === void 0 ? void 0 : Number(args.waitSeconds)
741
+ }));
742
+ case "oxy_publish_sandbox": {
743
+ requireArgs("oxy_publish_sandbox", args, ["appEnv"]);
744
+ const appEnv = requireSandboxName(String(args.appEnv));
745
+ const org = args.org;
746
+ const publishCtx = org === void 0 ? ctx : createContext({
747
+ ...ctx.flags,
748
+ org
749
+ }, ctx.cwd);
750
+ const outcome = await publish(publishCtx, {
751
+ appEnv,
752
+ dir: args.dir,
753
+ app: args.app
754
+ });
755
+ return jsonResult(outcome.result ?? { bundle_dir: outcome.bundleDir });
756
+ }
757
+ case "oxy_fn_call": {
758
+ requireArgs("oxy_fn_call", args, ["app", "function"]);
759
+ const result = await fnCall(ctx, String(args.app), String(args.function), {
760
+ appEnv: args.appEnv,
761
+ data: args.data,
762
+ timeoutSeconds: args.timeoutSeconds === void 0 ? 60 : Number(args.timeoutSeconds)
763
+ });
764
+ return jsonResult(result, {
765
+ isError: !result.ok,
766
+ code: ExitCode.FAILURE
767
+ });
768
+ }
769
+ case "oxy_checks_run": {
770
+ requireArgs("oxy_checks_run", args, ["app"]);
771
+ const report = await runChecksCore(ctx, String(args.app), {
772
+ timeoutSeconds: args.timeoutSeconds === void 0 ? 300 : Number(args.timeoutSeconds),
773
+ appEnv: args.appEnv
774
+ });
775
+ return jsonResult(report, {
776
+ isError: report.checks.some((c) => !c.passed),
777
+ code: ExitCode.CHECK_FAILED
778
+ });
779
+ }
780
+ case "oxy_invocations_list":
781
+ requireArgs("oxy_invocations_list", args, ["app"]);
782
+ return jsonResult({ invocations: await invocationsList(ctx, String(args.app), {
783
+ appEnv: args.appEnv,
784
+ build: args.build,
785
+ fn: args.function,
786
+ limit: args.limit === void 0 ? void 0 : Number(args.limit)
787
+ }) });
788
+ case "oxy_invocations_held":
789
+ requireArgs("oxy_invocations_held", args, ["app", "invocationId"]);
790
+ return jsonResult(await invocationsHeld(ctx, String(args.app), String(args.invocationId)));
791
+ case "oxy_logs":
792
+ requireArgs("oxy_logs", args, ["app"]);
793
+ return jsonResult({ logs: await fetchLogs(ctx, String(args.app), {
794
+ appEnv: args.appEnv,
795
+ invocation: args.invocation,
796
+ request: args.request,
797
+ hours: args.hours === void 0 ? void 0 : Number(args.hours),
798
+ limit: args.limit === void 0 ? void 0 : Number(args.limit)
799
+ }) });
800
+ case "oxy_preview_create": {
801
+ requireArgs("oxy_preview_create", args, ["branch"]);
802
+ const item = await previewCreate(ctx, String(args.branch), { waitSeconds: args.waitSeconds === void 0 ? void 0 : Number(args.waitSeconds) });
803
+ return jsonResult(item, {
804
+ isError: previewFailed(item),
805
+ code: ExitCode.FAILURE
806
+ });
807
+ }
808
+ case "oxy_preview_list": return jsonResult({ items: await previewList(ctx) });
809
+ case "oxy_preview_show":
810
+ requireArgs("oxy_preview_show", args, ["branch"]);
811
+ return jsonResult(await previewShow(ctx, String(args.branch)));
812
+ case "oxy_preview_delete":
813
+ requireArgs("oxy_preview_delete", args, ["branch"]);
814
+ if (args.confirm !== true) throw usageError("oxy_preview_delete needs confirm=true", "there is no terminal to ask on here — pass confirm=true once you mean it");
815
+ return jsonResult(await previewDelete(ctx, String(args.branch), { yes: true }));
816
+ case "oxy_preview_checks":
817
+ requireArgs("oxy_preview_checks", args, ["branch"]);
818
+ return jsonResult(await previewChecks(ctx, String(args.branch)));
819
+ case "oxy_preview_run": {
820
+ requireArgs("oxy_preview_run", args, [
821
+ "branch",
822
+ "kind",
823
+ "ref"
824
+ ]);
825
+ const kind = requireRunKind(String(args.kind));
826
+ const windowFrom = args.windowFrom;
827
+ const windowTo = args.windowTo;
828
+ const submitted = await previewSubmitRun(ctx, {
829
+ branch: String(args.branch),
830
+ kind,
831
+ ref: String(args.ref),
832
+ variables: parseVariables(args.variables),
833
+ readLiveOnly: args.readLiveOnly,
834
+ window: windowFrom === void 0 && windowTo === void 0 ? void 0 : {
835
+ from: windowFrom,
836
+ to: windowTo
837
+ },
838
+ resources: args.resources ?? []
839
+ });
840
+ const waitSeconds = args.waitSeconds === void 0 ? void 0 : Number(args.waitSeconds);
841
+ if (waitSeconds === void 0) return jsonResult(submitted);
842
+ const detail = await previewRunGet(ctx, submitted.run_id, { waitSeconds });
843
+ return jsonResult(detail, {
844
+ isError: runFailed(detail),
845
+ code: ExitCode.FAILURE
846
+ });
847
+ }
848
+ case "oxy_preview_runs_list":
849
+ requireArgs("oxy_preview_runs_list", args, ["branch"]);
850
+ return jsonResult({ runs: await previewRunsList(ctx, String(args.branch)) });
851
+ case "oxy_preview_run_show": {
852
+ requireArgs("oxy_preview_run_show", args, ["runId"]);
853
+ const detail = await previewRunGet(ctx, String(args.runId), { waitSeconds: args.waitSeconds === void 0 ? void 0 : Number(args.waitSeconds) });
854
+ return jsonResult(detail, {
855
+ isError: runFailed(detail),
856
+ code: ExitCode.FAILURE
857
+ });
858
+ }
859
+ default: return text(`unknown tool: ${name}`, true);
860
+ }
861
+ }
862
+ /**
863
+ * Serve MCP on stdio until the client disconnects.
864
+ *
865
+ * STDIO IS THE WHOLE TRANSPORT, deliberately. An HTTP/SSE server would need a
866
+ * port, a lifetime and an auth story of its own; stdio is what every agent
867
+ * runtime already launches, and the process inherits the caller's environment
868
+ * — which is where the token and the target come from.
869
+ *
870
+ * NOTHING MAY BE WRITTEN TO STDOUT except protocol frames. `log.info` and
871
+ * friends already go to stderr, which is why this can share the CLI's own
872
+ * plumbing without corrupting the stream.
873
+ */
874
+ async function runMcp(ctx) {
875
+ const server = new Server({
876
+ name: "oxyc",
877
+ version: VERSION
878
+ }, { capabilities: { tools: {} } });
879
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: ALL_TOOLS }));
880
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
881
+ try {
882
+ return await callTool(ctx, req.params.name, req.params.arguments ?? {});
883
+ } catch (cause) {
884
+ const message = cause.message ?? String(cause);
885
+ const { hint, remedy } = cause;
886
+ return text([
887
+ message,
888
+ [hint, remedy].filter((line) => line !== void 0 && line !== "").join("\n\n"),
889
+ cause instanceof CliError ? `[exit ${cause.code} ${exitCodeName(cause.code)}]` + (cause.serverCode ? ` server code: ${cause.serverCode}` : "") : void 0
890
+ ].filter((s) => s !== void 0 && s !== "").join("\n\n"), true);
891
+ }
892
+ });
893
+ await server.connect(new StdioServerTransport());
894
+ await new Promise((resolve) => {
895
+ process.stdin.on("close", resolve);
896
+ server.onclose = resolve;
897
+ });
898
+ }
899
+
900
+ //#endregion
901
+ export { runMcp };
902
+ //# sourceMappingURL=mcp-D5FFpqAw.mjs.map