@oxy-hq/cli 0.2.0 → 0.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.
@@ -17,7 +17,7 @@ Start a session scoped to this customer with:
17
17
  | `semantics/topics/` | `*.topic.yml` — question areas: a base view plus the views it may join to. Not one per table. |
18
18
  | `pipelines/` | `*.airway.yml` — Airway ELT pipelines. Credentials live in the secret manager, never in the YAML. |
19
19
  | `workflows/` | `*.automation.yml` — automations. `.automation.yml` is the canonical extension; `.procedure.yml` is legacy and still accepted, so do not start new files with it. |
20
- | `apps/` | Custom app bundles (React + Vite, shipped with `oxy publish`). |
20
+ | `apps/` | Custom app bundles (React + Vite, shipped with `oxyc publish`). |
21
21
  | `config.yml` | Workspace root config — models, databases, defaults. |
22
22
  | `.github/workflows/` | GitHub Actions CI for this repo. Not the same thing as `workflows/` above, which holds oxy automations — the two are one letter of context apart and easy to confuse. |
23
23
  | `.github/scripts/` | Shell the workflows call. Kept out of the YAML because a `run:` block can only ever be executed on a runner, while a script can be run — and tested — anywhere. |
@@ -86,7 +86,7 @@ running it against **a real oxy in the cloud** — there is no local warehouse,
86
86
  no fixture data, and no local `oxy serve` to point at. From the repo root:
87
87
 
88
88
  ```bash
89
- oxy login --env dev # once per env; opens a browser, caches a token
89
+ oxyc login --env dev # once per env; opens a browser, caches a token
90
90
  pnpm dev --env dev # starts everything
91
91
  ```
92
92
 
@@ -97,7 +97,7 @@ stops both together when you press Ctrl-C.
97
97
  **`--env` is required, and that is deliberate.** It says which oxy the app
98
98
  reads from — `dev`, `staging`, `production`, a full URL
99
99
  (`--env https://acme.oxygen-hq.com`), or any name the app's own `oxy-app.json`
100
- declares under `environments`. The underlying `oxy proxy` defaults to
100
+ declares under `environments`. The underlying `oxyc proxy` defaults to
101
101
  **production** if nothing says otherwise, and a `pnpm dev` that quietly serves
102
102
  a customer's live data is not something this repo will do. `--env production`
103
103
  additionally needs `--yes`.
@@ -113,7 +113,7 @@ pnpm dev --env dev sales-dashboard
113
113
 
114
114
  | Process | Port | What it is |
115
115
  | --- | --- | --- |
116
- | `oxy proxy --env <env>` | `3000` | Background. Every `/api` call the app makes goes through here, signed with the token `oxy login` cached, and out to the cloud. It stands in for a local `oxy serve`, which is why the port is not configurable — the Vite plugin already proxies `/api` to `3000`. |
116
+ | `oxyc proxy --env <env>` | `3000` | Background. Every `/api` call the app makes goes through here, signed with the token `oxyc login` cached, and out to the cloud. It stands in for a local `oxy serve`, which is why the port is not configurable — the Vite plugin already proxies `/api` to `3000`. Each Oxy Function call prints a `↳ <status> fn <name> request_id=… trace_id=…` line — the ids to look up when one fails. |
117
117
  | `pnpm dev` in the app | `5173` | Foreground. Vite, with hot reload. **This is the URL you open**: <http://localhost:5173>. |
118
118
 
119
119
  Ctrl-C stops both, and it always returns: a proxy that ignores the polite
@@ -139,9 +139,11 @@ that an afternoon of local clicking cannot change what the customer sees:
139
139
  ### If something is wrong
140
140
 
141
141
  - **Requests come back 401** — the cached token for that env has expired.
142
- `oxy login --env <env>` again.
143
- - **`the 'oxy' CLI is not on your PATH`** — install it with
144
- `curl -sSfL https://get.oxy.tech | bash`; it lands in `~/.local/bin`.
142
+ `oxyc login --env <env>` again.
143
+ - **`the 'oxyc' CLI is not on your PATH`** — install it with
144
+ `npm install -g @oxy-hq/cli`. A global install, not `npx`: Ctrl-C stops the
145
+ proxy by pid, and a wrapper process in between keeps the signal from reaching
146
+ it.
145
147
  - **`this repo has no custom apps yet`** — expected on a fresh repo, and it is
146
148
  not an error. The message says how to add one.
147
149
  - **A change to `apps/` does not show up** — Vite serves the app, but the data
@@ -160,8 +162,8 @@ a long-lived credential sitting in it.
160
162
  From the app's own directory under `apps/`:
161
163
 
162
164
  ```bash
163
- oxy login --env dev # once per env; opens a browser, caches a token
164
- oxy publish --env dev # a draft, to the dev environment
165
+ oxyc login --env dev # once per env; opens a browser, caches a token
166
+ oxyc publish --env dev # a draft, to the dev environment
165
167
  ```
166
168
 
167
169
  `--env` is not optional in practice. The CLI defaults it to **production**, so
@@ -212,14 +214,14 @@ opted in.
212
214
  ### Where an opted-in CI publishes
213
215
 
214
216
  `.github/workflows/publish.yaml` builds every bundle under `apps/` and ships
215
- it with `oxy publish`. It runs on a push to `main` that touches `apps/`, the
217
+ it with `oxyc publish`. It runs on a push to `main` that touches `apps/`, the
216
218
  lockfile, or the workflow itself, and it can be run by hand from the Actions
217
219
  tab.
218
220
 
219
221
  **Where it publishes is decided by how it was triggered, and it is always
220
222
  said out loud:**
221
223
 
222
- | Trigger | Event | `oxy publish --env` | Channel | Reviewers |
224
+ | Trigger | Event | `oxyc publish --env` | Channel | Reviewers |
223
225
  | --- | --- | --- | --- | --- |
224
226
  | push to `main` | `push` | `dev` | draft | none |
225
227
  | Actions tab (**Run workflow**) | `workflow_dispatch` | `production` | draft, or live with **Promote** | whatever `production` requires |
@@ -231,7 +233,7 @@ by `customer-tooling`'s own suite.
231
233
 
232
234
  That mapping lives in `.github/scripts/publish-env.sh`, and a trigger it has
233
235
  no entry for **fails the run** rather than picking one. The reason is worth
234
- knowing, because it was a live bug in this workflow: `oxy publish` defaults
236
+ knowing, because it was a live bug in this workflow: `oxyc publish` defaults
235
237
  `--env` to **production**, so an invocation that leaves the flag off does not
236
238
  publish "nowhere in particular" — it publishes at the customer's live
237
239
  environment. Every publish here names its environment explicitly, and there
@@ -250,7 +252,7 @@ tidiness one. `build` runs `pnpm install` and `pnpm -r build` — which is to
250
252
  say it executes the postinstall and build scripts of every dependency your
251
253
  apps pull in — and holds no publish credential at all. It hands the built
252
254
  output to `publish` as a workflow artifact. `publish` holds `OXY_TOKEN`, and
253
- runs no package script: `oxy publish --dir` uploads a pre-built directory
255
+ runs no package script: `oxyc publish --dir` uploads a pre-built directory
254
256
  as-is instead of building anything. So a compromised dependency in an app's
255
257
  tree never runs on a runner where the token exists.
256
258
 
@@ -325,8 +327,8 @@ worth knowing exactly what the two ways of doing it are:
325
327
  reviewed a draft and want that exact bundle live, this is the one you want.
326
328
  - **The Actions tab**, running this workflow with a **Ref** and **Promote**
327
329
  ticked, **rebuilds that ref and publishes the result live**. It does not
328
- promote an existing draft — no command in the `oxy` CLI can, so the
329
- workflow cannot either. If `main` has moved since the draft you reviewed,
330
+ promote an existing draft — `oxyc publish` cannot, so the workflow cannot
331
+ either. If `main` has moved since the draft you reviewed,
330
332
  this ships the newer commit, under a new build id.
331
333
 
332
334
  That is why the ref is an explicit, required input rather than something the
@@ -15,7 +15,7 @@
15
15
  # committed.
16
16
  node_modules/
17
17
 
18
- # Build output. `out/` is oxy publish's default outDir; `dist/` and `build/`
18
+ # Build output. `out/` is oxyc publish's default outDir; `dist/` and `build/`
19
19
  # are what a Vite or Next app writes when its oxy-app.json names one instead.
20
20
  out/
21
21
  dist/
@@ -6,9 +6,9 @@
6
6
  # why this file exists at all. Before it, running an app locally needed three
7
7
  # commands in two terminals and knowledge that was written down nowhere:
8
8
  #
9
- # oxy proxy --env <env> background, listens on :3000. Forwards the app's
9
+ # oxyc proxy --env <env> background, listens on :3000. Forwards the app's
10
10
  # /api calls to the cloud, signed with the token
11
- # `oxy login --env <env>` cached.
11
+ # `oxyc login --env <env>` cached.
12
12
  # pnpm dev (in the app) foreground, Vite on :5173, which proxies /api to
13
13
  # :3000. That target is the Vite plugin's default,
14
14
  # so the proxy's port is not really negotiable —
@@ -36,7 +36,7 @@ root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
36
36
  # that also uses it looks for it.
37
37
  DISCOVER="$root/.github/scripts/discover-apps.sh"
38
38
 
39
- # `oxy proxy`'s own default, and what @oxy-hq/vite-plugin proxies /api to.
39
+ # `oxyc proxy`'s own default, and what @oxy-hq/vite-plugin proxies /api to.
40
40
  PROXY_PORT=3000
41
41
  # Vite's default. Printed, never bound by this script.
42
42
  DEV_PORT=5173
@@ -60,7 +60,7 @@ Run one of this repo's custom apps locally, against a cloud oxy's real data.
60
60
  pnpm dev --env <env> [app] [--allow-writes] [--allow-events] [--yes]
61
61
 
62
62
  --env <env> REQUIRED. Which oxy to proxy to. There is deliberately no
63
- default: \`oxy proxy\`'s own default is production, and a
63
+ default: \`oxyc proxy\`'s own default is production, and a
64
64
  \`pnpm dev\` that silently reads production is not something
65
65
  this repo will do. One of:
66
66
  dev staging production
@@ -73,7 +73,7 @@ Run one of this repo's custom apps locally, against a cloud oxy's real data.
73
73
  --yes Confirm that --env production is really what you meant.
74
74
  -h, --help This text.
75
75
 
76
- First run, once per env: oxy login --env <env>
76
+ First run, once per env: oxyc login --env <env>
77
77
  EOF
78
78
  }
79
79
 
@@ -315,13 +315,13 @@ if [ -z "$env_name" ]; then
315
315
  "a full URL (--env https://acme.oxygen-hq.com), or a name the app's" \
316
316
  "oxy-app.json declares under \"environments\"." \
317
317
  "" \
318
- "There is no default on purpose. 'oxy proxy' defaults to PRODUCTION, and" \
318
+ "There is no default on purpose. 'oxyc proxy' defaults to PRODUCTION, and" \
319
319
  "a 'pnpm dev' that silently serves production data is not a thing this" \
320
320
  "repo will do quietly."
321
321
  fi
322
322
 
323
323
  if [ "$env_name" = "production" ] && [ "$confirm_yes" -ne 1 ]; then
324
- # `oxy proxy` refuses a production target without --yes on its own. Catching
324
+ # `oxyc proxy` refuses a production target without --yes on its own. Catching
325
325
  # it here matters because the proxy runs in the BACKGROUND: its refusal (or
326
326
  # its prompt) would scroll past under Vite's banner, and the app would just
327
327
  # fail every request with nothing on screen explaining why.
@@ -335,12 +335,13 @@ fi
335
335
 
336
336
  # --- preconditions ----------------------------------------------------------
337
337
 
338
- if ! command -v oxy >/dev/null 2>&1; then
339
- die "the 'oxy' CLI is not on your PATH, and the proxy is oxy." \
338
+ if ! command -v oxyc >/dev/null 2>&1; then
339
+ die "the 'oxyc' CLI is not on your PATH, and the proxy is oxyc." \
340
340
  "" \
341
- " curl -sSfL https://get.oxy.tech | bash" \
341
+ " npm install -g @oxy-hq/cli" \
342
342
  "" \
343
- "It installs to ~/.local/bin; add that to PATH if it is not already there."
343
+ "A global install, not npx: the proxy is killed by pid on Ctrl-C, and a" \
344
+ "wrapper process in between would keep the signal from reaching it."
344
345
  fi
345
346
 
346
347
  if ! command -v pnpm >/dev/null 2>&1; then
@@ -371,7 +372,7 @@ read_port_holder "$PROXY_PORT"
371
372
  if [ -n "$port_holder" ]; then
372
373
  die "port $PROXY_PORT is already taken by: $port_holder" \
373
374
  "" \
374
- "'oxy proxy' has to listen there — the app's dev server proxies /api to" \
375
+ "'oxyc proxy' has to listen there — the app's dev server proxies /api to" \
375
376
  "that exact port — so this cannot just move out of the way. Usually it is" \
376
377
  "a proxy from an earlier run that outlived its terminal, or a local" \
377
378
  "'oxy serve'. Stop it and try again:" \
@@ -389,7 +390,7 @@ if [ "$confirm_yes" -eq 1 ]; then proxy_args+=(--yes); fi
389
390
  say "" \
390
391
  " app $app_dir" \
391
392
  " env $env_name" \
392
- " proxy oxy ${proxy_args[*]} -> http://localhost:$PROXY_PORT" \
393
+ " proxy oxyc ${proxy_args[*]} -> http://localhost:$PROXY_PORT" \
393
394
  " dev pnpm dev in $app_dir -> http://localhost:$DEV_PORT" \
394
395
  ""
395
396
 
@@ -410,23 +411,26 @@ else
410
411
  say " Tracking events are DROPPED, so local clicking never shows up in the" \
411
412
  " customer's analytics. Pass --allow-events to forward them."
412
413
  fi
413
- say "" " Ctrl-C stops both. If requests come back 401, run: oxy login --env $env_name" ""
414
+ say "" " Ctrl-C stops both. If requests come back 401, run: oxyc login --env $env_name" ""
414
415
 
415
- oxy "${proxy_args[@]}" &
416
+ oxyc "${proxy_args[@]}" &
416
417
  proxy_pid=$!
417
418
 
418
- # A proxy that dies on the first second — no cached token, a bad --env — would
419
+ # A proxy that dies on the first second — a bad --env, a production host
420
+ # without --yes — would
419
421
  # otherwise leave Vite up and every request failing, with the reason scrolled
420
422
  # off the top. One second is enough to catch the immediate exits and cannot
421
423
  # produce a false alarm: a proxy still running after it is simply left alone.
422
424
  sleep 1
423
425
  if process_finished "$proxy_pid"; then
424
426
  proxy_pid=""
425
- die "'oxy proxy --env $env_name' exited immediately — see its output above." \
427
+ die "'oxyc proxy --env $env_name' exited immediately — see its output above." \
426
428
  "" \
427
- "Most often there is no cached token for that env yet:" \
429
+ "Most often --env did not resolve to a deployment, or it names a" \
430
+ "production host (an org URL under oxygen-hq.com) and needs --yes." \
431
+ "If it did start but every request is a 401, cache a token for it:" \
428
432
  "" \
429
- " oxy login --env $env_name"
433
+ " oxyc login --env $env_name"
430
434
  fi
431
435
 
432
436
  # The dev server, in the foreground, and the LAST statement in this file.
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-VdontkUr.mjs","names":[],"sources":["../src/commands/mcp.ts"],"sourcesContent":["/**\n * `oxyc mcp` — the Oxy API as MCP tools, over stdio.\n *\n * NOT THE SAME THING AS `oxy mcp`. That one is workspace tooling: it takes a\n * local checkout and exposes the semantic model, automations and `.sql` files\n * in it. This one takes a TOKEN and exposes the deployment's HTTP API — the\n * same surface `oxyc api` reaches, for an agent that would rather call a tool\n * than shell out. Different input, different audience, no overlap.\n *\n * FOUR TOOLS, NOT SIX HUNDRED — the design decision that makes this affordable.\n *\n * The obvious shape is one tool per endpoint, and it is the wrong one: the API\n * has ~670 routes, an agent runtime ships every tool's JSON schema in every\n * request, and that is tens of kilobytes of context spent on each turn before\n * a single question is asked. It would also go stale on every deploy, since\n * the tool list would be baked into this package rather than read from the\n * deployment.\n *\n * So discovery stays a QUESTION the agent asks (`routes`, `schema`) rather\n * than a payload it carries, exactly as the CLI does it. Four tools cost a few\n * hundred bytes per turn and reach every endpoint, including ones added after\n * this package was published.\n *\n * Auth, target resolution and placeholder substitution are the CLI's — the\n * same `Context`, so a token cached by `oxyc login` (or `oxy login`) works\n * here with no separate setup, and `{org}` / `{workspace}` resolve the same\n * way.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { CallToolRequestSchema, ListToolsRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport { loadCatalog, loadOpenApi, searchRoutes } from \"../api/catalog.js\";\nimport { paramsToQuery, parseFields } from \"../api/fields.js\";\nimport { runJq } from \"../api/output.js\";\nimport { isExternalSurface, normalizePath, substitutePlaceholders } from \"../api/paths.js\";\nimport { parseJson, request } from \"../api/request.js\";\nimport type { Context } from \"../context/resolve.js\";\nimport { CliError, ExitCode } from \"../util/errors.js\";\nimport { comparablePath } from \"./discover.js\";\n\n/**\n * Package version, reported in the MCP handshake.\n *\n * Read from `package.json` rather than restated, so a release bump cannot\n * leave the server announcing a version nobody shipped.\n */\nconst VERSION: string = (() => {\n try {\n const here = dirname(fileURLToPath(import.meta.url));\n for (const candidate of [\n resolve(here, \"..\", \"package.json\"),\n resolve(here, \"..\", \"..\", \"package.json\")\n ]) {\n if (existsSync(candidate)) {\n return (\n (JSON.parse(readFileSync(candidate, \"utf8\")) as { version?: string }).version ?? \"0.0.0\"\n );\n }\n }\n } catch {\n // A packaging shape we did not anticipate. The handshake needs a string,\n // not an accurate one.\n }\n return \"0.0.0\";\n})();\n\n/**\n * A tool result. MCP wants content blocks; everything here is text, because\n * the caller is a language model and the payloads are JSON or markdown.\n */\nfunction text(body: string, isError = false) {\n return { content: [{ type: \"text\" as const, text: body }], isError };\n}\n\nconst TOOLS = [\n {\n name: \"oxy_routes\",\n description:\n \"List the API endpoints this Oxy deployment mounts, with what each one does. \" +\n \"ALWAYS call this before oxy_request rather than guessing a path. \" +\n \"Pass a filter (matched against method, path, surface and description) to narrow it — \" +\n \"unfiltered is ~670 routes. Above 60 matches the descriptions are dropped and only \" +\n \"method, path and credential come back, so narrow enough to stay under that when you \" +\n \"need to know what an endpoint does; past ~400 it is refused outright.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filter: {\n type: \"string\",\n description: \"Substring to narrow by, e.g. 'threads', 'sql', 'admin', 'semantic'.\"\n },\n all: {\n type: \"boolean\",\n description:\n \"Include ide-only and worker-only routes. Off by default: those are mounted on one \" +\n \"instance of the fleet, so a caller hitting the load balancer cannot reach them directly.\"\n }\n }\n }\n },\n {\n name: \"oxy_schema\",\n description:\n \"The request and response schema for ONE endpoint, so a body can be built correctly. \" +\n \"Covers the data plane (SQL, semantic query, and the org/workspace lookups); a blank \" +\n \"result means undocumented, not nonexistent — use oxy_routes to confirm the endpoint exists.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Endpoint path, e.g. '{workspace}/sql/query'.\" },\n method: { type: \"string\", description: \"Narrow to one HTTP method.\" }\n },\n required: [\"path\"]\n }\n },\n {\n name: \"oxy_request\",\n description:\n \"Make an authenticated request to the Oxy API. The credential is picked from the path \" +\n \"(/api/** takes a bearer, /external/api/** an API key). Placeholders {org}, {workspace}, \" +\n \"{project}, {customer} and {me} are substituted from context. \" +\n \"Read freely; ask the human before any mutating request against production.\",\n inputSchema: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Path relative to /api, e.g. '{org}/workspaces'.\" },\n method: {\n type: \"string\",\n description: \"HTTP method. Defaults to GET, or POST with fields.\"\n },\n fields: {\n type: \"object\",\n description:\n \"Request parameters. Sent as a JSON body on POST/PUT/PATCH, or as query parameters \" +\n \"on GET/HEAD/DELETE. Values keep their JSON type.\"\n },\n jq: {\n type: \"string\",\n description:\n \"A jq program to reduce the response before it is returned. Use it — a full list \" +\n \"response is far more context than the two fields you need.\"\n }\n },\n required: [\"path\"]\n }\n },\n {\n name: \"oxy_whoami\",\n description:\n \"Which deployment this is pointed at and who the token belongs to. \" +\n \"Use it when a call returns 401/403, or a 200 with a null body — on this API an expired \" +\n \"session answers 200 null rather than 401, and this tells the two apart.\",\n inputSchema: { type: \"object\", properties: {} }\n }\n];\n\n/**\n * Above this many matches, `oxy_routes` drops the descriptions.\n *\n * DEGRADES, IT DOES NOT REFUSE — the same shape as `oxyc routes`, which picks\n * `renderDetailed` under 40 matches and the compact method+path table above it\n * (`discover.ts`). The expensive field is `description`, not the row: a trimmed\n * row is a few tens of bytes, so several hundred still fit in a result an agent\n * can read, while the descriptions are what turn a broad match into hundreds of\n * KB of context spent before a question is asked.\n *\n * The threshold is on the COUNT, not on whether a `filter` was supplied — a\n * filter is not evidence of narrowing. `searchRoutes` matches a substring of\n * method, path, surface or description, so `\"admin\"`, `\"workspace\"` and\n * `\"query\"` are all filters a model reaches for in good faith that clear this.\n */\nconst MAX_DESCRIBED_ROUTES = 60;\n\n/**\n * And above THIS many, there is nothing useful to return at all.\n *\n * Deliberately far above the threshold that drops descriptions: refusing is the\n * answer only when even the trimmed listing would be a context dump, which for\n * a deployment of ~670 routes means \"you asked for effectively all of them\".\n */\nconst MAX_ROUTES_PER_RESULT = 400;\n\n/** `{ a: 1 }` → the `-f`/`-F` pairs `parseFields` understands. */\nfunction fieldPairs(fields: Record<string, unknown> | undefined): string[] {\n if (!fields) return [];\n return Object.entries(fields).map(([k, v]) => `${k}=${JSON.stringify(v)}`);\n}\n\n/**\n * Check the arguments the schema says are required.\n *\n * `inputSchema.required` is ADVISORY on the low-level `Server` — it is handed\n * to the model, not enforced by the transport. Without this, `oxy_schema` with\n * no `path` matched every path and returned the whole OpenAPI document, and\n * `oxy_request` with none built a request to `/api/`.\n */\nfunction requireArgs(name: string, args: Record<string, unknown>, required: string[]): void {\n const missing = required.filter((k) => {\n const v = args[k];\n return v === undefined || v === null || (typeof v === \"string\" && v.trim() === \"\");\n });\n if (missing.length > 0) {\n throw new CliError(`${name} needs ${missing.join(\", \")}`, { code: ExitCode.USAGE });\n }\n}\n\nasync function callTool(ctx: Context, name: string, args: Record<string, unknown>) {\n switch (name) {\n case \"oxy_routes\": {\n const catalog = await loadCatalog({ target: ctx.target(), bearer: ctx.maybeBearer() });\n const filter = (args.filter as string | undefined)?.trim();\n let matches = searchRoutes(catalog, filter || undefined);\n if (!args.all) matches = matches.filter((r) => r.role === \"fleet-ok\");\n\n // A cache stale enough to be wrong is worth saying INSIDE the result:\n // `loadCatalog` warns on stderr, which an MCP client never shows anyone.\n const staleNote = catalog.stale\n ? \"NOTE: this route table came from a stale local cache; the deployment was unreachable.\\n\\n\"\n : \"\";\n\n const asked = filter ? ` ${JSON.stringify(filter)}` : \"\";\n\n // Only a match set too large even to LIST is refused. Below that the\n // result degrades instead, because a filter like \"admin\" or \"query\" can\n // clear the description threshold in good faith and \"guess something\n // narrower\" is a dead end for a model with no way to see what it hit.\n if (matches.length > MAX_ROUTES_PER_RESULT) {\n return text(\n `${staleNote}${matches.length} routes match${asked}, which is effectively the whole ` +\n `deployment. Call oxy_routes again with a narrower \\`filter\\` (matched against ` +\n `method, path, surface and description), e.g. \"threads\", \"sql\", \"semantic\", \"admin\".`,\n true\n );\n }\n\n if (matches.length === 0) {\n // An empty array reads as \"this deployment has no such endpoint\",\n // which is usually false — the filter was wrong, or the route is\n // ide-only and hidden by default.\n return text(\n `${staleNote}No route matches ${JSON.stringify(filter ?? \"\")}. Try a broader filter, ` +\n `or pass all=true to include ide-only and worker-only mounts.`,\n true\n );\n }\n // Trimmed to the fields that help a caller build a request. The full\n // record carries the handler path and mount notes, which are for a\n // maintainer reading source, not for an agent composing a call.\n const described = matches.length <= MAX_DESCRIBED_ROUTES;\n // `credential` SURVIVES THE TRIM. It is what separates the bearer mount\n // from the `/external/api` API-key one, so a caller composing a request\n // needs it in either form — and `renderCompact`, the CLI shape this\n // mirrors, keeps it as a per-surface heading. It is also not the\n // expensive field: ~25 bytes a row, ~10 KB across the whole ceiling,\n // against descriptions that run to hundreds of KB.\n const trimmed = matches.map((r) =>\n described\n ? { method: r.method, path: r.path, credential: r.credential, description: r.description }\n : { method: r.method, path: r.path, credential: r.credential }\n );\n // The note says the listing is trimmed AND how to get the descriptions\n // back. Without it a model reads a description-less row as an endpoint\n // that has no documentation, rather than one it did not ask narrowly\n // enough to see.\n const trimNote = described\n ? \"\"\n : `NOTE: ${matches.length} routes match${asked} — too many to describe, so each row is ` +\n `method, path and credential WITHOUT its description. Narrow the \\`filter\\` to ` +\n `${MAX_DESCRIBED_ROUTES} or fewer matches to get the descriptions back.\\n\\n`;\n return text(`${staleNote}${trimNote}${JSON.stringify(trimmed)}`);\n }\n\n case \"oxy_schema\": {\n requireArgs(\"oxy_schema\", args, [\"path\"]);\n const doc = (await loadOpenApi({ target: ctx.target(), bearer: ctx.maybeBearer() })) as {\n paths?: Record<string, Record<string, unknown>>;\n components?: unknown;\n };\n const wanted = String(args.path ?? \"\");\n const method = args.method as string | undefined;\n // `comparablePath` is imported from `discover.ts` rather than copied:\n // a second reduction of the same two spellings is a second thing to keep\n // in step, and the copy here was untested. Exact first, then substring —\n // the order `runSchema` uses, so the two commands answer alike.\n const paths = Object.entries(doc.paths ?? {});\n const exact = paths.filter(([p]) => comparablePath(p) === comparablePath(wanted));\n const hit =\n exact.length > 0\n ? exact\n : paths.filter(([p]) => comparablePath(p).includes(comparablePath(wanted)));\n if (hit.length === 0) {\n return text(\n `No documented schema for ${wanted}. The OpenAPI document covers the data plane only — ` +\n `call oxy_routes with a filter to confirm the endpoint exists.`,\n true\n );\n }\n const selected = Object.fromEntries(\n hit.map(([p, ops]) => [\n p,\n method\n ? Object.fromEntries(\n Object.entries(ops).filter(([verb]) => verb.toLowerCase() === method.toLowerCase())\n )\n : ops\n ])\n );\n return text(JSON.stringify({ paths: selected, components: doc.components }, null, 2));\n }\n\n case \"oxy_request\": {\n requireArgs(\"oxy_request\", args, [\"path\"]);\n const raw = String(args.path ?? \"\");\n const method = String(args.method ?? \"\").toUpperCase() || undefined;\n const fields = parseFields([], fieldPairs(args.fields as Record<string, unknown>));\n const verb = method ?? (fields.present ? \"POST\" : \"GET\");\n const carriesBody = ![\"GET\", \"HEAD\", \"DELETE\"].includes(verb);\n\n let path = substitutePlaceholders(normalizePath(raw), ctx.placeholders());\n let body: string | undefined;\n if (fields.present) {\n if (carriesBody) body = JSON.stringify(fields.params);\n else {\n const query = paramsToQuery(fields.params);\n if (query) path += (path.includes(\"?\") ? \"&\" : \"?\") + query;\n }\n }\n\n const apiKey = ctx.apiKey();\n const external = isExternalSurface(path);\n const response = await request({\n target: ctx.target(),\n path,\n method: verb,\n body,\n bearer: external && apiKey ? ctx.maybeBearer() : ctx.bearer(),\n apiKey\n });\n\n if (response.status < 200 || response.status >= 300) {\n // The STATUS and the body, not a thrown error: the model can act on\n // \"403, here is what the server said\" and cannot act on a transport\n // exception. It is marked `isError` so the runtime shows it as one.\n return text(`HTTP ${response.status} ${response.statusText}\\n${response.body}`, true);\n }\n\n if (response.body.trim() === \"null\") {\n return text(\n \"null\\n\\n(NOTE: a 200 with a null body can mean an expired session on this API, \" +\n \"not 'no such thing'. Call oxy_whoami to tell them apart.)\"\n );\n }\n\n const jq = args.jq as string | undefined;\n if (jq) return text(runJq(response.body, jq));\n return text(response.body);\n }\n\n case \"oxy_whoami\": {\n const target = ctx.target();\n const response = await request({\n target,\n path: \"/api/user\",\n method: \"GET\",\n bearer: ctx.bearer()\n });\n const payload = parseJson(response.body);\n if (payload === null || payload === undefined) {\n return text(\n `target: ${target}\\nThe token no longer resolves to a user — the session has expired. ` +\n `Ask the human to run \\`oxyc login\\`.`,\n true\n );\n }\n return text(JSON.stringify({ target, user: payload }, null, 2));\n }\n\n default:\n return text(`unknown tool: ${name}`, true);\n }\n}\n\n/**\n * Serve MCP on stdio until the client disconnects.\n *\n * STDIO IS THE WHOLE TRANSPORT, deliberately. An HTTP/SSE server would need a\n * port, a lifetime and an auth story of its own; stdio is what every agent\n * runtime already launches, and the process inherits the caller's environment\n * — which is where the token and the target come from.\n *\n * NOTHING MAY BE WRITTEN TO STDOUT except protocol frames. `log.info` and\n * friends already go to stderr, which is why this can share the CLI's own\n * plumbing without corrupting the stream.\n */\nexport async function runMcp(ctx: Context): Promise<void> {\n const server = new Server({ name: \"oxyc\", version: VERSION }, { capabilities: { tools: {} } });\n\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n try {\n return await callTool(\n ctx,\n req.params.name,\n (req.params.arguments ?? {}) as Record<string, unknown>\n );\n } catch (cause) {\n // A throw here would kill the session. The model can act on a message;\n // it cannot act on a dead transport.\n const message = (cause as Error).message ?? String(cause);\n // BOTH CHANNELS. A model gets one string, so there is no marker to\n // distinguish them — but reading `hint` alone drops the one line that\n // says what to DO, which is the half a model can act on.\n const { hint, remedy } = cause as { hint?: string; remedy?: string };\n // Blank line between them, the way every other renderer of these two\n // separates them — a model given two consecutive imperatives with no\n // boundary loses the distinction the second field exists to make.\n // `!== undefined` for the narrowing TS gives it, and a length check\n // because an empty string would open the block with a blank line —\n // `filter(Boolean)` covered that and cost the narrowing, so both.\n const extra = [hint, remedy].filter((line) => line !== undefined && line !== \"\").join(\"\\n\\n\");\n return text(extra ? `${message}\\n\\n${extra}` : message, true);\n }\n });\n\n await server.connect(new StdioServerTransport());\n\n // `connect` returns once the transport is wired; the process must stay up\n // until the client closes stdin.\n await new Promise<void>((resolve) => {\n process.stdin.on(\"close\", resolve);\n server.onclose = resolve;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,iBAAyB;CAC7B,IAAI;EACF,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;EACnD,KAAK,MAAM,aAAa,CACtB,QAAQ,MAAM,MAAM,cAAc,GAClC,QAAQ,MAAM,MAAM,MAAM,cAAc,CAC1C,GACE,IAAI,WAAW,SAAS,GACtB,OACG,KAAK,MAAM,aAAa,WAAW,MAAM,CAAC,CAAC,CAA0B,WAAW;CAIzF,QAAQ,CAGR;CACA,OAAO;AACT,EAAC,CAAE;;;;;AAMH,SAAS,KAAK,MAAc,UAAU,OAAO;CAC3C,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAiB,MAAM;EAAK,CAAC;EAAG;CAAQ;AACrE;AAEA,MAAM,QAAQ;CACZ;EACE,MAAM;EACN,aACE;EAMF,aAAa;GACX,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