From 6b4c509ac8aadb94b815d503ea31571149d5b5a0 Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Mon, 9 Nov 2026 17:18:29 -0300 Subject: [PATCH 1/7] feat: add deel app search, describe and run for web-app actions Adds `deel app`, which finds and runs the Deel web-app actions published for agents, as the signed-in user, through Deel's MCP endpoint (/mcp): a small JSON-RPC client (no MCP SDK) and three commands on top of it. - search / describe / run map to the search_actions, get_action and run_read_action / run_write_action tools; run picks the tool from get_action's run_with, and --input is one {path_params, query, body} object. - The login is checked before any call (an OAuth login, no sensitive-data claims); a 401 refreshes the login once; reads retry, writes never do; errors map to the CLI envelope with a next step; a body the server cut at 100 KB is returned as text with meta.truncated and a warning. - DEEL_MCP_URL points the commands at another /mcp for test environments. Also fixes two problems the end-to-end run found, for every command: output piped into another process was cut at 64 KB because the CLI exited before stdout drained (now it sets the exit code and ends on its own, safe under Node and Bun), and --jq parsed a text payload as JSON instead of taking it as a string. PA-8226 --- README.md | 24 ++- scripts/doctor-hashes.json | 31 ++-- src/commands/app.ts | 146 ++++++++++++++++++ src/commands/index.ts | 4 +- src/core/app-actions.ts | 299 +++++++++++++++++++++++++++++++++++++ src/core/auth.ts | 19 ++- src/core/config.ts | 9 ++ src/core/constants.ts | 2 +- src/core/io.ts | 27 ++++ src/core/mcp.ts | 131 ++++++++++++++++ src/core/oauth.ts | 12 +- src/core/output.ts | 3 +- src/main.ts | 9 +- test/app-actions.test.ts | 274 +++++++++++++++++++++++++++++++++ test/app.test.ts | 232 ++++++++++++++++++++++++++++ test/auth.test.ts | 9 +- test/io.test.ts | 49 ++++++ test/mcp.test.ts | 118 +++++++++++++++ test/oauth.test.ts | 34 ++++- test/output.test.ts | 6 + 20 files changed, 1408 insertions(+), 30 deletions(-) create mode 100644 src/commands/app.ts create mode 100644 src/core/app-actions.ts create mode 100644 src/core/mcp.ts create mode 100644 test/app-actions.test.ts create mode 100644 test/app.test.ts create mode 100644 test/io.test.ts create mode 100644 test/mcp.test.ts diff --git a/README.md b/README.md index 3b4dfa9..89aed82 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ deel logs requests list --status_class 4xx --beta # your organization's failed - [Output (`--json`, `--fields`, `--jq`, `--quiet`)](#output) - [Idempotency](#idempotency) - [Webhooks](#webhooks) +- [Web-app actions](#web-app-actions) - [Environments](#environments) - [Corporate proxies & custom CAs](#corporate-proxies--custom-cas) - [Exit codes](#exit-codes) @@ -268,6 +269,26 @@ A webhook id can start with `-`, which the argument parser reads as a flag. Pass `simulate` runs the delivery from Deel's servers, so the receiver URL must be publicly reachable; it is limited to 10 simulations per hour per event type, is never retried and gets no auto-derived `Idempotency-Key`, and exits 1 when the receiver does not answer 2xx. +## Web-app actions + +`deel app` runs actions of the Deel web app that Deel has published for agents, as the signed-in user and with that user's permissions. It calls Deel's MCP endpoint (`/mcp`), which is the only way in: web-app endpoints accept an OAuth login only through it. Web-app actions carry no stability promise: they change with the web app and can change or disappear without notice, so scripts that use them should expect to break. Which actions an organization can use is decided by Deel. + +```bash +deel auth login # once; a PAT can't run web-app actions +deel app search "time off" # actions this login can run (--limit 1-20) +deel app describe # input schema, scopes, and whether it reads or writes +deel app describe --generate-input > input.json +deel app run --input file://input.json # or --input 'path_params={id=123},query={status=open}' +deel app run --input ... --dry-run # print the call, run nothing +``` + +- `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. +- `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. Writes are never retried; when a write gets no answer, the error says so and asks you to check with a read before running it again. +- Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much, and stderr has a warning. +- A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). + +**For agents:** let the agent run `deel app search` and `deel app describe` freely, and keep `deel app run` on "ask" in your agent's permission settings, since the CLI itself never asks before a write. + ## Environments | `--env` | Base URL | @@ -334,6 +355,7 @@ Location: `~/Library/Logs/deel/deel.log` (macOS), | ------------------- | ----------------------------------------------------------- | | `DEEL_TOKEN` | PAT value | | `DEEL_ENV` | Default environment (`prod` / `demo`) | +| `DEEL_MCP_URL` | MCP endpoint for `deel app` (https; default `/mcp` on the API host) | | `DEEL_LOG` | `off` to disable local logging | | `DEEL_LOG_BODIES` | `1` to include response bodies in the local log (off by default) | | `DEEL_LOG_DIR` | Override the log directory | @@ -384,7 +406,7 @@ src/ types.ts # shared descriptor/manifest types manifest.generated.ts # command descriptors (generated by the deel-cli-extractor skill — never hand-edited) commands.map.ts # command ↔ API endpoint mapping - commands/ # static commands (auth, job, webhooks) + commands/ # static commands (app, auth, job, webhooks) core/ # http, auth, keychain, config, tls, input, output, logging, … test/ # automated tests (node --test), one file per module ``` diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index b8be9e9..451aef1 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -17,7 +17,7 @@ ".nvmrc": "f14b4987904bcb5814e4459a057ed4d20f58a633152288a761214dcd28780b56", "CONTRIBUTING.md": "c3d910ec4cf50a54b483fff388f1e9b226272e28fff44d047fd3293fb3a49794", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "0caf72fc9aa21b190db7f34a235f6b573b370eb85ff47ca283396a78f88c48ab", + "README.md": "a7d788adbe72c94a2515ee8995164511bed84781419e6737a76bbcb56dd8ccde", "SECURITY.md": "5759dae591c598f64383beb8570e8b7c1302e91b82d4baca019f301d31a01565", "package-lock.json": "d1712a62a91a8de27ed484df07ed2fe23fb9c0b4ffb242f7d7b6a753a8c519f5", "package.json": "82ea75b867ea139e0cb32bde07ed8ecad6713ce557fff8876ac87c7f68fde335", @@ -35,36 +35,41 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "8d0ef6ddccb68f68233b609ff4159583b30f4c15d88dbd3b7a7ec912120c18aa", "src/commands.map.ts": "f8437737b33ba7597e1dde683929fafba48ee912226895c303c5df54cc866a5e", + "src/commands/app.ts": "af8dea8471d35434537d71191102a04d41a1f45377696d25a299d3fafb082b56", "src/commands/auth.ts": "9fca7b582ab961b1a492d24e31b13492eb14e8eab65eb4cf486dd7290a155dcd", - "src/commands/index.ts": "46b686860fa205cbae3baf3320a5cea5262e525f42b4b2cf3454cab0e67ac7a8", + "src/commands/index.ts": "56bd18a7c74e8dfc7133830a4b379a25b46c5a97ac92b747350ef5e38f394db2", "src/commands/job.ts": "0a3ac3245f3d52867a64c414e8ea87a137030d55952f4121b8199e9660bdf935", "src/commands/shared.ts": "18709976927d1d4f524a78f62ea8133cfc976c542a77a88486c68581312ad9ad", "src/commands/webhooks.ts": "77ba46b73e6e064bc33234bf0071a5bedd5b6f5a2d49e60a7e92da0c5678aa4d", - "src/core/auth.ts": "394b0477d525c4fda3a1ee5403f33a7dd76c569d37b2f78efb1611b9cb6ffda9", - "src/core/config.ts": "2295a4dd876a5bfda658a3ccdf6f305893cd277b5a83dffe647cef3149482301", - "src/core/constants.ts": "ef6ef49800798446f447bfd49df446d2a2eb4d57183e735710094c7052da0f78", + "src/core/app-actions.ts": "51ed6d1b0eed3c06dcd1790e8d855bea24abdfcaa33a817320793701cc41e3bd", + "src/core/auth.ts": "ca9f32e3c7167f572b39eb363925760f3e7d87241f978e2068c7e527940ef920", + "src/core/config.ts": "3a9ae869e0c2710a33441a5c67054d88203a0f403448a17327cd55716f6fd6ac", + "src/core/constants.ts": "4a7fdb50bf7d203cae1c51fd0ca840fe440c2821f25ed5e82c4274fd0675648b", "src/core/context.ts": "cd446ae728060675f03db31cc767f469df1a01b4bba7843f3d6255b9bd5d996d", "src/core/errors.ts": "26d099836c3d67bbde90d28143485acc7f679129e3905e5bed996e9720dea333", "src/core/executor.ts": "bedd559f9e8f069e93722f97cd8c4bd201717ddc80784575af9f007629461900", "src/core/http.ts": "4926b0be50c59ca0995c160b790ed5243b360926bbd163d3d04352475ce9a262", "src/core/idempotency.ts": "ec9f2af6d12cb739aa53ee17bdbc932fc07e6c5087011718cf8d81a4d08fa04b", "src/core/input.ts": "34ad1c10a3fde878624258fb0d5c41a901857ed534ff75d48848683790b73187", - "src/core/io.ts": "973ca57aa11ef358b753060334768ffe6b5b581720ca810bf2c63136e79a77ca", + "src/core/io.ts": "62bb99bce19c926533d41dd66a08f4735d578d17ddcce4a55f6dcf8507444fc4", "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "d660e82ee1700b8a9926c83174268b1b4fc650a6ae6848dbf83f63f9bc15d9bc", + "src/core/mcp.ts": "29d95f990bf20a3ae17522a9d4c1115d05732e5a0e7f50feaee9680d845459ad", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", - "src/core/oauth.ts": "1a4938658335b1a2ee6490e2f6c19ecb571c7a9228c5a0d6db087a2ec4bcc0d5", - "src/core/output.ts": "4a6adf3bc3043bdcc89331271cf2bcd83782a37b09b73b047c4d4f674afbb1a5", + "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", + "src/core/output.ts": "d1fce35d4d75563ddb7544eca9752d82dc6d2b08c07ecdf60f6a8268083cae82", "src/core/tls.ts": "c06f0d810e91f0a7e959f2363750871d6e5e67edcf00ac3a9a05c2ba7fce9f65", "src/core/webhooks.ts": "63e98217b287327236769abb40358631176e68ee6ec698bd3becef2528cdf187", "src/help.ts": "39d96d86569a73686f8bd133369646420e5de32497b6d8d2d557d707918b0e2a", - "src/main.ts": "825c3581a935b3c83e104e905b2dbb99b17ab208659847ae5f9c6f0572364e47", + "src/main.ts": "d126d9fc96e1050a93956d5a134705eec2923ea57787aa0a8544edcbcaf7a01b", "src/manifest.generated.ts": "884b86be368ceef6be7f8010464abc42b8d0375d710c7004adb5158f264a82b1", "src/types.ts": "f18f56cdb821c39469e21d59208e1e3948761ba609090f23fd3f5e4bd9f4d567", "src/version.ts": "4428bcfed17f7d5e084e9b3faf40d85ae44fe71cc3a81770ab348774c3dc0d68", + "test/app-actions.test.ts": "26f40964c7be506348f812027cb60cb59fc735d34a19c33dbad9e475d2ef54a5", + "test/app.test.ts": "eb23b2a6edf1bef92af664508d37d36eea6306da8097bf0b4be3c35285558b99", "test/auth-command.test.ts": "6efb94a0c3754bc0057ee62249df6c57b558ad82a0a6919d2f5ed695c4769839", - "test/auth.test.ts": "0c3eff32fd95cbe086510467f59e16de486178413bc190da7df3a994edffdedc", + "test/auth.test.ts": "f309ecfbdeaa8bcb6ec179410f29efe4923e663485bb1b35d0cec4096313aed4", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", "test/check-doctor.test.ts": "4ae966ba51e61ab2d1a11655b344a1ecab0e57a4ea3f8d038c024d63405af145", "test/check-macho-signature.test.ts": "4ef01ed87b052c85aee27270a5738f992d51a80a4c36891f218a491d28e9c0dc", @@ -79,13 +84,15 @@ "test/idempotency.test.ts": "82ff10c19c9979ce27839c1fd25a503c6695e622cf630bacc5783c15951d1de3", "test/input.test.ts": "6b17dc862cb789e6f3274510b9f209388510a65f4dc61ddee28499678ea304f2", "test/install.test.ts": "f68a3ee5f08eb2172e9c12823ed46e120ea156fc2695abc77626e32dd57b826e", + "test/io.test.ts": "8214a9ec3dee20c5d9b75e9b5b3b46b2ea18b5c284d05aa8e91b0b4fcba3ab82", "test/jobs.test.ts": "0a37b7204e5c5f9c2ffef3efa062256f6d1e061885189b2809698c3baf36bc13", "test/keychain.test.ts": "0f1fad8ae0d351ffecc051e551f0c5ad6e9be263e6ff1246589eae2dbf2f8856", "test/logging.test.ts": "9ed74d04fef5727186b7aa40e06d30e5eeb31210f1ae6a072c7cf1330be6a69b", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", + "test/mcp.test.ts": "f6c28cb28444ca3764f4209ba8f52b3fef1f86f66c7074234c40a34676451e50", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", - "test/oauth.test.ts": "58837bf6de40f33b643fa988a6be1197cd2346d0415db448099e75042371eb03", - "test/output.test.ts": "87df3f927f89496b6e2d8af48b0eb384885ce592f36edfd13408b590f1b79ee2", + "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", + "test/output.test.ts": "3b898699a31c7da7e5cac5dc973d9eff186bdcff9f0f8f10355d9e02ffebfe65", "test/shared.test.ts": "916d7b2440f5748b1b641e622b71086a12639114d8eb53cc69b11a720b718f7b", "test/sign-darwin.test.ts": "ac2f43cfbb4ba9337a62bdd2b3e52ff0b76f7ac08b1c98b9ee9a7f43c974e345", "test/stubs.ts": "dcbf3fd49a134bebf2282a5f43f56954ce3bf4f6b3806fb126ed7e288da15121", diff --git a/src/commands/app.ts b/src/commands/app.ts new file mode 100644 index 0000000..30ea41d --- /dev/null +++ b/src/commands/app.ts @@ -0,0 +1,146 @@ +// `deel app search | describe | run` — Deel web-app actions through Deel's /mcp, as the signed-in user. +// Web-app actions carry no stability promise: they change with the web app. Nothing here is +// interactive, and a write runs without a confirmation step: the agent host's permission settings decide. + +import { defineCommand } from "citty"; +import { createContext } from "../core/context.ts"; +import type { Ctx } from "../core/context.ts"; +import { envelope, render } from "../core/output.ts"; +import { setLoggingEnabled, setLogBodiesEnabled } from "../core/logging.ts"; +import { resolveMcpUrl } from "../core/config.ts"; +import { authFor, resolveToken } from "../core/auth.ts"; +import type { ResolvedToken } from "../core/auth.ts"; +import { parseInput } from "../core/input.ts"; +import { CliError } from "../core/errors.ts"; +import type { IOStreams } from "../core/io.ts"; +import type { Transport } from "../core/http.ts"; +import type { CredentialStore } from "../core/keychain.ts"; +import { + SEARCH_MAX_LIMIT, + actionInput, + assertEligible, + createAppClient, + getAction, + inputSkeleton, + runAction, + runCall, + searchActions, +} from "../core/app-actions.ts"; +import type { AppClient } from "../core/app-actions.ts"; +import { commonArgs, configFrom, outputOpts } from "./shared.ts"; +import type { Args } from "./shared.ts"; + +// Test seams: a fake transport, keychain or IO; the real ones otherwise. +export type AppDeps = { baseTransport?: Transport; store?: CredentialStore; io?: IOStreams; sleep?: (ms: number) => Promise }; + +type Session = { ctx: Ctx; client: AppClient }; + +function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { + setLoggingEnabled(args.log !== false); + setLogBodiesEnabled(args["log-bodies"] === true); + const config = configFrom(args, rawArgs); + const resolved: ResolvedToken = resolveToken({ tokenStdin: Boolean(args["token-stdin"]), config, store: deps.store, transport: deps.baseTransport }); + assertEligible(resolved); + const url = resolveMcpUrl(config); + const ctx = createContext({ config, token: authFor(resolved), io: deps.io, baseTransport: deps.baseTransport }); + const oauth = resolved.oauth; + const client = createAppClient({ + http: ctx.http, + url, + newRequestId: ctx.newRequestId, + sleep: deps.sleep, + renew: oauth + ? async () => { + await oauth.renew(oauth.current().access_token); + return true; + } + : undefined, + }); + return { ctx, client }; +} + +// Hidden flags citty doesn't declare, so `--flag value` would leave the value among the positionals. +const HIDDEN_VALUE_FLAGS = ["base-url"]; + +// Every positional word (citty's positional arg keeps only the first), without the values of hidden flags. +export function positionals(args: Args, rawArgs: string[]): string[] { + const words = Array.isArray(args._) ? args._.map(String) : []; + for (const flag of HIDDEN_VALUE_FLAGS) { + const at = rawArgs.indexOf(`--${flag}`); + if (at === -1 || at + 1 >= rawArgs.length) continue; + const index = words.indexOf(rawArgs[at + 1]); + if (index !== -1) words.splice(index, 1); + } + return words; +} + +export async function runSearch(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + const query = positionals(args, rawArgs).join(" "); + const limit = args.limit === undefined ? undefined : Number(args.limit); + if (!query.trim()) throw new CliError("usage.app", "Usage: deel app search [--limit 1-20]"); + const { ctx, client } = prepare(args, rawArgs, deps); + const { actions, requestId } = await searchActions(client, query, limit); + await render(ctx.io, envelope({ actions }, { request_id: requestId }), outputOpts(args)); +} + +export async function runDescribe(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + const names = positionals(args, rawArgs); + if (names.length === 0) throw new CliError("usage.app", "Usage: deel app describe ... [--generate-input]"); + if (args["generate-input"] && names.length > 1) throw new CliError("usage.app", "--generate-input takes one action name."); + const { ctx, client } = prepare(args, rawArgs, deps); + const found = []; + for (const name of names) found.push(await getAction(client, name)); + if (args["generate-input"]) { + ctx.io.out(JSON.stringify(inputSkeleton(found[0].action), null, 2) + "\n"); + return; + } + const actions = found.map((item) => item.action); + await render(ctx.io, envelope({ actions }, { request_id: found[found.length - 1].requestId }), outputOpts(args)); +} + +export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + const [name, ...extra] = positionals(args, rawArgs); + if (!name || extra.length > 0) throw new CliError("usage.app", "Usage: deel app run [--input ...] [--dry-run]"); + const input = actionInput(args.input === undefined ? undefined : parseInput(String(args.input), [])); + const { ctx, client } = prepare(args, rawArgs, deps); + const { action, requestId } = await getAction(client, name); + if (args["dry-run"]) { + const call = runCall(action, input); + await render(ctx.io, envelope({ method: "tools/call", params: { name: call.tool, arguments: call.arguments } }, { request_id: requestId, dry_run: true }), outputOpts(args)); + return; + } + const outcome = await runAction(client, action, input); + const meta: Record = { request_id: outcome.requestId }; + if (outcome.truncated) { + meta.truncated = outcome.truncated; + ctx.io.err(`warning: the response was cut at ${outcome.truncated.shown_bytes} of ${outcome.truncated.total_bytes} bytes, so it is returned as text. Narrow the query to get all of it.\n`); + } + await render(ctx.io, envelope(outcome.data, meta), outputOpts(args)); +} + +const appArgs = { ...commonArgs }; + +export const appCommand = defineCommand({ + meta: { name: "app", description: "Deel web-app actions through /mcp, as the signed-in user" }, + subCommands: { + search: defineCommand({ + meta: { name: "search", description: "Find actions the signed-in user can run: deel app search " }, + args: { query: { type: "positional", required: false, description: "What the action does" }, limit: { type: "string", description: `Maximum results, 1-${SEARCH_MAX_LIMIT} (default 10)` }, ...appArgs }, + run: (cittyCtx) => runSearch(cittyCtx.args as Args, cittyCtx.rawArgs), + }), + describe: defineCommand({ + meta: { name: "describe", description: "Show an action's input schema, scopes and run tool: deel app describe ..." }, + args: { name: { type: "positional", required: false, description: "Action name(s), as search returns them" }, ...appArgs }, + run: (cittyCtx) => runDescribe(cittyCtx.args as Args, cittyCtx.rawArgs), + }), + run: defineCommand({ + meta: { name: "run", description: "Run an action: deel app run --input '{path_params, query, body}'" }, + args: { + name: { type: "positional", required: false, description: "Action name, as search returns it" }, + "dry-run": { type: "boolean", description: "Print the tools/call that would be sent, without running it" }, + ...appArgs, + }, + run: (cittyCtx) => runRun(cittyCtx.args as Args, cittyCtx.rawArgs), + }), + }, +}); diff --git a/src/commands/index.ts b/src/commands/index.ts index fb61d1b..706e276 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -2,16 +2,18 @@ // don't map 1:1 to a single API operation the way generated commands do. import type { CommandDef } from "citty"; +import { appCommand } from "./app.ts"; import { authCommand } from "./auth.ts"; import { jobCommand } from "./job.ts"; import { webhooksCommand } from "./webhooks.ts"; -export { authCommand, jobCommand, webhooksCommand }; +export { appCommand, authCommand, jobCommand, webhooksCommand }; // Keyed by the top-level command name; merged into the root command tree. // The keys MUST stay in sync with RESERVED_COMMANDS (src/core/constants.ts), // which prevents a derived API command from colliding with one of these. export const staticCommands: Record = { + app: appCommand, auth: authCommand, job: jobCommand, webhooks: webhooksCommand, diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts new file mode 100644 index 0000000..a657012 --- /dev/null +++ b/src/core/app-actions.ts @@ -0,0 +1,299 @@ +// Deel web-app actions over Deel's /mcp: `search_actions`, `get_action`, `run_read_action` and +// `run_write_action`. The CLI only consumes them: the server decides who may use them, checks scopes and +// validates input. This module adds what a CLI needs on top: a check before any call that the login can +// work at all, the read or write choice from `run_with`, retries for reads only, and errors mapped to +// the CLI's envelope with a next step. + +import { CliError } from "./errors.ts"; +import { accessTokenClaims } from "./auth.ts"; +import type { ResolvedToken } from "./auth.ts"; +import { RETRY_BASE_DELAY_MS, RETRY_MAX_ATTEMPTS } from "./constants.ts"; +import { callTool, toolFailure } from "./mcp.ts"; +import type { ToolFailure, ToolResult } from "./mcp.ts"; +import type { Transport } from "./http.ts"; + +export const APP_TOOL = { + search: "search_actions", + get: "get_action", + runRead: "run_read_action", + runWrite: "run_write_action", +} as const; + +export const SEARCH_MAX_LIMIT = 20; +const INPUT_KEYS = ["path_params", "query", "body"] as const; +const TRUNCATION_NOTICE = /^\[Response truncated: the action returned (\d+) bytes; only the first (\d+) bytes are shown\.\]$/; +// Failures that happen before an action runs, or on a read, so another attempt is safe. +const TRANSIENT_CODES = new Set(["UPSTREAM_UNAVAILABLE", "UPSTREAM_TIMEOUT", "UPSTREAM_SERVER_ERROR"]); +const NO_RESPONSE_CODES = new Set(["UPSTREAM_TIMEOUT", "UPSTREAM_UNAVAILABLE"]); + +export type JsonSchema = { type?: string; properties?: Record; required?: string[]; enum?: unknown[]; [key: string]: unknown }; + +export type ActionSummary = { name: string; title?: string; description?: string; method?: string; scopes?: string[] }; +export type ActionDetail = ActionSummary & { run_with?: string; input_schema?: JsonSchema }; +export type ActionInput = { path_params?: Record; query?: Record; body?: unknown }; + +export type AppClient = { + call: (tool: string, args: Record, opts: { retryable: boolean }) => Promise; +}; + +export type AppClientOpts = { + http: Transport; + url: string; + newRequestId: () => string; + renew?: () => Promise; // refresh the OAuth login after a 401; false when there is nothing to renew + sleep?: (ms: number) => Promise; +}; + +function oauthRequired(message: string): CliError { + return new CliError("auth.oauth_required", message, "Run 'deel auth login' (a PAT can't run web-app actions)."); +} + +function sensitiveDataHidden(): CliError { + return new CliError( + "app.sensitive_data_hidden", + "This login hides sensitive data, and web-app actions aren't available to such a login.", + "Run 'deel auth login' again without hiding sensitive data.", + ); +} + +// Fails before any call when the login can't run web-app actions: no login, a PAT, or a token that hides PII +// or employment data. Claims are read unverified, only to pick the error; the server decides for real. +export function assertEligible(resolved: ResolvedToken): void { + if (resolved.source === "none" || !resolved.token) throw oauthRequired("'deel app' needs a Deel OAuth login."); + if (resolved.source === "keychain") throw oauthRequired("'deel app' needs a Deel OAuth login, and the saved login is a PAT."); + const token = resolved.oauth?.current().access_token ?? resolved.token; + const claims = accessTokenClaims(token); + if (!claims) { + if (resolved.source === "oauth") return; + throw oauthRequired("'deel app' needs a Deel OAuth access token, and this token isn't one."); + } + if (typeof claims.client_id !== "string" || !claims.client_id) throw oauthRequired("'deel app' needs a Deel OAuth login, and this token is a PAT."); + if (claims.hide_pii_data === true || claims.hide_employment_data === true) throw sensitiveDataHidden(); +} + +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export function createAppClient(opts: AppClientOpts): AppClient { + const sleep = opts.sleep ?? defaultSleep; + return { + async call(tool, args, { retryable }) { + const attempts = retryable ? RETRY_MAX_ATTEMPTS : 1; + let renewed = false; + for (let attempt = 1; ; attempt++) { + const result = await callTool({ + http: opts.http, + url: opts.url, + requestId: opts.newRequestId(), + name: tool, + args, + retryable, + command: `app ${tool}`, + onUnauthorized: async () => { + if (renewed || !opts.renew) return false; + renewed = true; + return opts.renew(); + }, + }); + if (!result.isError) return result; + const failure = toolFailure(result); + // A token introspection rejected: answered before anything runs, so a renewed login may retry once. + if (failure.code === "AUTHENTICATION_REQUIRED" && !renewed && opts.renew) { + renewed = true; + if (await opts.renew()) { + attempt--; + continue; + } + } + const transient = failure.statusCode === 429 || (failure.code !== undefined && TRANSIENT_CODES.has(failure.code)); + if (!transient || attempt >= attempts) return result; + await sleep(RETRY_BASE_DELAY_MS * 2 ** (attempt - 1)); + } + }, + }; +} + +// ---------------- errors ---------------- + +export type FailureContext = { action?: string; scopes?: string[]; write?: boolean }; + +export function appError(failure: ToolFailure, requestId: string, context: FailureContext = {}): CliError { + const error = mapFailure(failure, context); + error.requestId = requestId; + return error; +} + +function mapFailure(failure: ToolFailure, context: FailureContext): CliError { + const { code, message } = failure; + if (failure.statusCode === 429) { + return new CliError("app.rate_limited", message, context.write ? "Wait a moment, then check whether the action ran before running it again." : "Wait a moment and try again."); + } + switch (code) { + case "AUTHENTICATION_REQUIRED": + return new CliError("auth.expired", message, "deel auth login"); + case "TOKEN_TYPE_NOT_ALLOWED": + return /pii|employment|sensitive/i.test(message) ? sensitiveDataHidden() : oauthRequired(message); + case "APP_ACTIONS_NOT_ALLOWED": + case "APP_ACTIONS_NOT_CONFIGURED": + return new CliError("app.unavailable", message, "Web-app actions are rolled out per organization."); + case "ACTION_NOT_FOUND": + return new CliError( + "app.action_not_found", + context.action ? `No action named "${context.action}" is available to this login.` : message, + "Find one with 'deel app search '.", + ); + case "INSUFFICIENT_SCOPES": { + // Without get_action's scopes (describe of an action the login can't use), take the ones the server names. + const named = /needs one of these scopes: ([\w:.,\s-]+)$/.exec(message)?.[1].split(",").map((scope) => scope.trim()).filter(Boolean); + const scopes = context.scopes?.length ? context.scopes.join(",") : (named ?? []).join(","); + return new CliError("auth.insufficient_scope", message, scopes ? `Run 'deel auth login --scopes ${scopes}' to add a scope it needs.` : "Run 'deel auth login --scopes ' with the scope it needs."); + } + case "INVALID_ARGUMENTS": + return new CliError("app.invalid_input", message, context.action ? `See the input with 'deel app describe ${context.action}'.` : undefined); + case "WRONG_ACTION_KIND": + return new CliError("app.wrong_kind", message); + } + if (context.write && (code === undefined || NO_RESPONSE_CODES.has(code) || failure.statusCode >= 500)) { + const sentence = /[.!?]$/.test(message) ? message : `${message}.`; + return new CliError("app.outcome_unknown", `${sentence} The action may or may not have run.`, "Check the result with a read action before running it again."); + } + const suffix = code ? code.toLowerCase().replace(/[^a-z0-9_]/g, "_") : `http_${failure.statusCode}`; + return new CliError(`app.${suffix}`, message); +} + +function failed(result: ToolResult, context: FailureContext): never { + throw appError(toolFailure(result), result.requestId, context); +} + +function jsonText(result: ToolResult): unknown { + try { + return JSON.parse(result.texts[0] ?? ""); + } catch { + const error = new CliError("mcp.response", "The MCP endpoint sent a tool result that is not JSON."); + error.requestId = result.requestId; + throw error; + } +} + +// ---------------- operations ---------------- + +export async function searchActions(client: AppClient, query: string, limit?: number): Promise<{ actions: ActionSummary[]; requestId: string }> { + if (!query.trim()) throw new CliError("usage.app", "Usage: deel app search "); + if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > SEARCH_MAX_LIMIT)) { + throw new CliError("usage.app", `--limit must be a whole number from 1 to ${SEARCH_MAX_LIMIT}.`); + } + const result = await client.call(APP_TOOL.search, { query, ...(limit !== undefined ? { limit } : {}) }, { retryable: true }); + if (result.isError) failed(result, {}); + const payload = jsonText(result) as { actions?: unknown }; + return { actions: Array.isArray(payload.actions) ? (payload.actions as ActionSummary[]) : [], requestId: result.requestId }; +} + +export async function getAction(client: AppClient, name: string): Promise<{ action: ActionDetail; requestId: string }> { + const result = await client.call(APP_TOOL.get, { name }, { retryable: true }); + if (result.isError) failed(result, { action: name }); + return { action: jsonText(result) as ActionDetail, requestId: result.requestId }; +} + +// --input for `run`: the whole {path_params, query, body} object. +export function actionInput(value: unknown): ActionInput { + if (value === undefined) return {}; + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new CliError("usage.app_input", "--input must be an object with path_params, query and/or body.", "Try: --input 'path_params={id=123}'"); + } + const extra = Object.keys(value).filter((key) => !(INPUT_KEYS as readonly string[]).includes(key)); + if (extra.length > 0) { + throw new CliError("usage.app_input", `Unknown --input key(s): ${extra.join(", ")}. Use path_params, query and body.`, "See the input with 'deel app describe '."); + } + return value as ActionInput; +} + +// The CLI parses `id=123` as a number; path and query values the schema declares as strings are sent as strings, +// and numeric strings the schema declares as numbers are sent as numbers. Everything else is left to the server. +function coerceSection(values: Record | undefined, schema: JsonSchema | undefined): Record | undefined { + if (!values || typeof values !== "object" || Array.isArray(values)) return values; + const coerced: Record = {}; + for (const [key, value] of Object.entries(values)) { + const type = schema?.properties?.[key]?.type; + if (type === "string" && (typeof value === "number" || typeof value === "boolean")) coerced[key] = String(value); + else if ((type === "integer" || type === "number") && typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) coerced[key] = Number(value); + else coerced[key] = value; + } + return coerced; +} + +export function coerceInput(input: ActionInput, schema: JsonSchema | undefined): ActionInput { + const path = coerceSection(input.path_params, schema?.properties?.path_params); + const query = coerceSection(input.query, schema?.properties?.query); + return { + ...(path !== undefined ? { path_params: path } : {}), + ...(query !== undefined ? { query } : {}), + ...(input.body !== undefined ? { body: input.body } : {}), + }; +} + +export type RunCall = { tool: string; arguments: Record }; + +export function runCall(action: ActionDetail, input: ActionInput): RunCall { + const tool = action.run_with === APP_TOOL.runRead || action.run_with === APP_TOOL.runWrite ? action.run_with : APP_TOOL.runWrite; + return { tool, arguments: { name: action.name, ...coerceInput(input, action.input_schema) } }; +} + +export type RunOutcome = { data: unknown; requestId: string; truncated?: { total_bytes: number; shown_bytes: number } }; + +// The backend body as it came: JSON when it parses, otherwise the text. A body over the server's cap is cut and +// followed by a notice item; cut JSON doesn't parse, so it stays text. +export function runOutcome(result: ToolResult): RunOutcome { + const body = result.texts[0] ?? ""; + const notice = result.texts.slice(1).map((text) => TRUNCATION_NOTICE.exec(text)).find(Boolean); + if (notice) return { data: body, requestId: result.requestId, truncated: { total_bytes: Number(notice[1]), shown_bytes: Number(notice[2]) } }; + let data: unknown = body; + try { + data = JSON.parse(body); + } catch { + /* not JSON: keep the text */ + } + return { data, requestId: result.requestId }; +} + +export async function runAction(client: AppClient, action: ActionDetail, input: ActionInput): Promise { + let call = runCall(action, input); + const context = (tool: string): FailureContext => ({ action: action.name, scopes: action.scopes, write: tool === APP_TOOL.runWrite }); + let result = await client.call(call.tool, call.arguments, { retryable: call.tool === APP_TOOL.runRead }); + if (result.isError && toolFailure(result).code === "WRONG_ACTION_KIND") { + // The catalog changed between get_action and the run; the check runs before anything is called, so the + // other tool is safe to try once. + call = { ...call, tool: call.tool === APP_TOOL.runRead ? APP_TOOL.runWrite : APP_TOOL.runRead }; + result = await client.call(call.tool, call.arguments, { retryable: call.tool === APP_TOOL.runRead }); + } + if (result.isError) failed(result, context(call.tool)); + return runOutcome(result); +} + +// ---------------- describe --generate-input ---------------- + +function skeletonOf(schema: JsonSchema | undefined): unknown { + if (!schema || typeof schema !== "object") return ""; + if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0]; + if (Array.isArray(schema.allOf)) return skeletonOf({ ...(schema.allOf as JsonSchema[]).reduce((merged, part) => ({ ...merged, ...part }), {}) }); + switch (schema.type) { + case "object": { + const skeleton: Record = {}; + for (const [key, property] of Object.entries(schema.properties ?? {})) skeleton[key] = skeletonOf(property); + return skeleton; + } + case "array": + return []; + case "integer": + case "number": + return 0; + case "boolean": + return false; + default: + return ""; + } +} + +// An --input skeleton for `deel app run`, from the action's input schema. +export function inputSkeleton(action: ActionDetail): Record { + const skeleton = skeletonOf(action.input_schema); + return skeleton && typeof skeleton === "object" && !Array.isArray(skeleton) ? (skeleton as Record) : {}; +} diff --git a/src/core/auth.ts b/src/core/auth.ts index 22b0351..0e620e9 100644 --- a/src/core/auth.ts +++ b/src/core/auth.ts @@ -128,15 +128,22 @@ export function redactHeaders(headers: Record): Record | null { try { - const claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")) as { scope?: unknown }; - if (typeof claims.scope === "string") return claims.scope; - if (Array.isArray(claims.scope) && claims.scope.every((item) => typeof item === "string")) return claims.scope.join(" "); + const claims: unknown = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")); + if (claims && typeof claims === "object" && !Array.isArray(claims)) return claims as Record; } catch { /* not a JWT */ } return null; } + +// The scope claim of an access token, for display only (`deel auth status`). +export function accessTokenScope(token: string): string | null { + const scope = accessTokenClaims(token)?.scope; + if (typeof scope === "string") return scope; + if (Array.isArray(scope) && scope.every((item) => typeof item === "string")) return scope.join(" "); + return null; +} diff --git a/src/core/config.ts b/src/core/config.ts index 118267b..dadc2f5 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -100,6 +100,15 @@ export function resolveConfig(opts: { env?: string; baseUrl?: string; beta?: boo return config; } +// The MCP endpoint the `deel app` commands call: `/mcp` on the API host, or DEEL_MCP_URL (https) for a test +// environment that serves it on its own host. The override is the user's explicit choice of server, like +// --base-url, so the login is sent there too. +export function resolveMcpUrl(config: Config): string { + const override = httpsOverride("DEEL_MCP_URL"); + if (override.error) throw new CliError("config.mcp", override.error); + return override.value ?? `${new URL(config.baseUrl).origin}/mcp`; +} + // The legacy PAT stored under the bare env name belongs to the environment's own server. Talking to another // server (an issuer override or a different API host) must never read or touch it. export function ownsLegacyPat(config: Config): boolean { diff --git a/src/core/constants.ts b/src/core/constants.ts index 7a0f684..00f352e 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -29,7 +29,7 @@ export const IDEMPOTENCY_NAMESPACE = "8f4b6c1e-3d2a-4f9c-9a1b-7e5d0c2a1f00"; export const AGENT_ENV_SIGNALS = ["CI", "CLAUDE_CODE", "CURSOR", "CODEX"] as const; // --- Command resolver vocabulary --- -export const RESERVED_COMMANDS = new Set(["job", "auth", "webhooks"]); +export const RESERVED_COMMANDS = new Set(["job", "auth", "webhooks", "app"]); export const COMMAND_SUFFIX_MODIFIERS = ["-bulk", "-async"]; // --- Header names (lowercase; fetch normalizes) --- diff --git a/src/core/io.ts b/src/core/io.ts index 71b0300..2b535f7 100644 --- a/src/core/io.ts +++ b/src/core/io.ts @@ -30,6 +30,33 @@ export function realIO(): IOStreams { }; } +// How long a process with nothing left to write may stay up before it is forced to exit. +export const FORCED_EXIT_MS = 5_000; + +export type ExitOpts = { + streams?: Array>; + setExitCode?: (code: number) => void; + exit?: (code: number) => void; + schedule?: (run: () => void, ms: number) => void; +}; + +// End the process without dropping output. process.exit() right after a write drops what is still queued for a +// pipe (it stops at 64 KB on macOS), so a large output piped into jq or a file would be cut. Under Node an +// empty write's callback runs once earlier writes are flushed; under Bun it can run before, so the process +// isn't exited directly: it sets the exit code and ends by itself once its writes are done. An unref'd timer +// still forces the exit if something else keeps the event loop alive. +export function exitAfterFlush(code: number, opts: ExitOpts = {}): void { + const streams = opts.streams ?? [process.stdout, process.stderr]; + const setExitCode = opts.setExitCode ?? ((value: number) => void (process.exitCode = value)); + const exit = opts.exit ?? process.exit; + const schedule = opts.schedule ?? ((run: () => void, ms: number) => void setTimeout(run, ms).unref()); + setExitCode(code); + let pending = streams.length; + const flushed = () => schedule(() => exit(code), FORCED_EXIT_MS); + if (pending === 0) return flushed(); + for (const stream of streams) stream.write("", () => --pending === 0 && flushed()); +} + // Test double: captures writes into buffers; feed stdin via `stdin`. export function captureIO(opts: { stdin?: string; isTTY?: boolean } = {}): IOStreams & { stdout: string[]; stderr: string[] } { const stdout: string[] = []; diff --git a/src/core/mcp.ts b/src/core/mcp.ts new file mode 100644 index 0000000..9801324 --- /dev/null +++ b/src/core/mcp.ts @@ -0,0 +1,131 @@ +// A minimal MCP client: one JSON-RPC `tools/call` per HTTP POST, no session and no SDK. The server is +// stateless, so no `initialize` handshake is needed. A tool failure comes back as HTTP 200 with `isError` +// and a JSON text payload; this module returns it as data and leaves its meaning to the caller. + +import { CliError } from "./errors.ts"; +import { HEADER } from "./constants.ts"; +import type { Transport } from "./http.ts"; + +export const MCP_ACCEPT = "application/json, text/event-stream"; + +export type ToolResult = { + isError: boolean; + texts: string[]; // the text items of `content`, in order + requestId: string; +}; + +// The error payload the server puts in an `isError` result's first text item. +export type ToolFailure = { + statusCode: number; + code?: string; + message: string; + details?: unknown; +}; + +export type CallToolOpts = { + http: Transport; + url: string; + requestId: string; + name: string; + args: Record; + retryable: boolean; + // Called once when the server answers HTTP 401; returns true when a retry may help (a refreshed login). + onUnauthorized?: () => Promise; + command?: string; +}; + +type RpcMessage = { jsonrpc?: string; id?: unknown; result?: unknown; error?: { code?: unknown; message?: unknown } }; + +// A Streamable HTTP response is either one JSON body or an SSE stream whose `data:` lines carry the messages. +export function parseRpcBody(text: string, contentType: string | undefined, id: number): RpcMessage | null { + if (contentType?.includes("text/event-stream")) { + const messages = text + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => { + try { + return JSON.parse(line.slice("data:".length).trim()) as RpcMessage; + } catch { + return null; + } + }) + .filter((message): message is RpcMessage => message !== null); + return messages.find((message) => message.id === id) ?? null; + } + try { + const message = JSON.parse(text) as RpcMessage; + return message && typeof message === "object" ? message : null; + } catch { + return null; + } +} + +function printable(value: unknown, fallback: string): string { + return typeof value === "string" && value ? value.replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 500) : fallback; +} + +export async function callTool(opts: CallToolOpts): Promise { + const id = 1; + const send = () => + opts.http({ + method: "POST", + url: opts.url, + headers: { + [HEADER.accept]: MCP_ACCEPT, + [HEADER.contentType]: "application/json", + [HEADER.requestId]: opts.requestId, + }, + body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name: opts.name, arguments: opts.args } }), + retryable: opts.retryable, + meta: { command: opts.command ?? "mcp", tool: opts.name }, + }); + + let response = await send(); + // A 401 is answered before the tool runs, so one retry with a renewed login is safe even for a write. + if (response.status === 401 && opts.onUnauthorized && (await opts.onUnauthorized())) response = await send(); + if (response.status === 401) { + throw withRequestId(new CliError("auth.expired", "The Deel login was rejected.", "deel auth login"), opts.requestId); + } + if (response.status < 200 || response.status >= 300) { + throw withRequestId(new CliError(`http.${response.status}`, `The MCP endpoint answered HTTP ${response.status}.`), opts.requestId); + } + + const message = parseRpcBody(response.text, response.headers[HEADER.contentType], id); + if (!message) throw withRequestId(new CliError("mcp.response", "The MCP endpoint sent a response that is not JSON-RPC."), opts.requestId); + if (message.error) { + const text = printable(message.error.message, "JSON-RPC error"); + // An unregistered tool: the server has app actions switched off. + if (/not found|unknown tool/i.test(text)) { + throw withRequestId(new CliError("app.unavailable", "Web-app actions are not available on this server.", "They are rolled out per organization."), opts.requestId); + } + throw withRequestId(new CliError("mcp.rpc", `${text} (JSON-RPC ${String(message.error.code ?? "error")})`), opts.requestId); + } + + const result = (message.result ?? {}) as { isError?: unknown; content?: unknown }; + const content = Array.isArray(result.content) ? result.content : []; + const texts = content + .filter((item): item is { type: string; text: string } => Boolean(item) && (item as { type?: unknown }).type === "text" && typeof (item as { text?: unknown }).text === "string") + .map((item) => item.text); + return { isError: result.isError === true, texts, requestId: opts.requestId }; +} + +// Reads `{statusCode, message, errors: [{code}], details}` from an `isError` result. +export function toolFailure(result: ToolResult): ToolFailure { + let payload: Record = {}; + try { + const parsed: unknown = JSON.parse(result.texts[0] ?? ""); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) payload = parsed as Record; + } catch { + /* plain-text error */ + } + const errors = Array.isArray(payload.errors) ? (payload.errors as Array>) : []; + const code = errors.find((error) => typeof error?.code === "string" && error.code)?.code as string | undefined; + const statusCode = typeof payload.statusCode === "number" ? payload.statusCode : 500; + const message = printable(payload.message ?? result.texts[0], "The tool call failed."); + return { statusCode, ...(code ? { code } : {}), message, ...(payload.details !== undefined ? { details: payload.details } : {}) }; +} + +function withRequestId(error: CliError, requestId: string): CliError { + error.requestId = requestId; + return error; +} diff --git a/src/core/oauth.ts b/src/core/oauth.ts index 3f77763..778b315 100644 --- a/src/core/oauth.ts +++ b/src/core/oauth.ts @@ -350,6 +350,9 @@ export type OAuthSourceOpts = { export type OAuthSource = { // A valid access token, refreshed first when it is close to expiry. token: () => Promise; + // A new access token after the server rejected `rejected` before its expiry: refreshed now, unless another + // process already stored a different one. + renew: (rejected: string) => Promise; current: () => OAuthEntry; }; @@ -362,7 +365,7 @@ export function createOAuthSource(opts: OAuthSourceOpts): OAuthSource { let entry = opts.entry; let inflight: Promise | null = null; - async function refresh(): Promise { + async function refresh(rejected?: string): Promise { return withLock( lockPath(opts.issuer), async () => { @@ -370,7 +373,8 @@ export function createOAuthSource(opts: OAuthSourceOpts): OAuthSource { // would make the server revoke the whole login, so always re-read before refreshing. const latest = readOAuthEntry(opts.store, opts.issuer); if (!latest) throw expired(); - if (isFresh(latest, now())) return latest; + const usable = rejected === undefined ? isFresh(latest, now()) : latest.access_token !== rejected; + if (usable) return latest; const metadata = await discover(opts.issuer, opts.transport); const response = await postForm(opts.transport, metadata.token_endpoint, { grant_type: "refresh_token", @@ -408,5 +412,9 @@ export function createOAuthSource(opts: OAuthSourceOpts): OAuthSource { entry = await inflight; return entry.access_token; }, + async renew(rejected) { + entry = await refresh(rejected); + return entry.access_token; + }, }; } diff --git a/src/core/output.ts b/src/core/output.ts index 7358f2e..5359a18 100644 --- a/src/core/output.ts +++ b/src/core/output.ts @@ -18,7 +18,8 @@ export type OutputOpts = { async function runJq(data: unknown, filter: string): Promise { try { const { json } = await import("jq-wasm"); - return await json(data as any, filter); + // jq-wasm parses a string input as JSON text; quote it so a text payload reaches the filter as a string. + return await json((typeof data === "string" ? JSON.stringify(data) : data) as any, filter); } catch (error) { throw new CliError("jq.error", `--jq filter failed: ${(error as Error).message}`); } diff --git a/src/main.ts b/src/main.ts index 34f9b2b..2ba35a3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,23 +4,24 @@ import { run } from "./cli.ts"; import { CliError, EXIT, toEnvelope } from "./core/errors.ts"; import { reexecWithSystemCa } from "./core/tls.ts"; +import { exitAfterFlush } from "./core/io.ts"; // CA trust (OS store by default) is installed lazily in the HTTP transport, so // offline commands (--help, --generate-input) stay fast. run(process.argv.slice(2)) - .then((code) => process.exit(code)) + .then((code) => exitAfterFlush(code)) .catch((err) => { if (err instanceof CliError) { // Bun's binary ignores setDefaultCACertificates; retry once trusting the OS store. if (err.code === "network.tls") reexecWithSystemCa(); // exits on retry; returns if already retried process.stderr.write(JSON.stringify({ error: toEnvelope(err) }, null, 2) + "\n"); - process.exit(EXIT.ERROR); + return exitAfterFlush(EXIT.ERROR); } const anyErr = err as { name?: string; code?: string; message?: string }; if (anyErr?.name === "CLIError" || anyErr?.code === "EARG") { process.stderr.write(JSON.stringify({ error: { code: "usage", message: anyErr.message } }, null, 2) + "\n"); - process.exit(EXIT.ERROR); + return exitAfterFlush(EXIT.ERROR); } process.stderr.write(JSON.stringify({ error: { code: "unexpected", message: (err as Error).message } }, null, 2) + "\n"); - process.exit(EXIT.ERROR); + exitAfterFlush(EXIT.ERROR); }); diff --git a/test/app-actions.test.ts b/test/app-actions.test.ts new file mode 100644 index 0000000..64eaca6 --- /dev/null +++ b/test/app-actions.test.ts @@ -0,0 +1,274 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + APP_TOOL, + actionInput, + appError, + assertEligible, + coerceInput, + createAppClient, + getAction, + inputSkeleton, + runAction, + runCall, + runOutcome, + searchActions, +} from "../src/core/app-actions.ts"; +import type { ActionDetail, AppClient } from "../src/core/app-actions.ts"; +import type { ResolvedToken } from "../src/core/auth.ts"; +import type { CliError } from "../src/core/errors.ts"; +import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; +import type { ToolResult } from "../src/core/mcp.ts"; +import type { OAuthSource } from "../src/core/oauth.ts"; + +// Made-up actions only: deel-cli is public. +const APPROVE: ActionDetail = { + name: "approve_widget", + title: "Approve a widget", + method: "POST", + scopes: ["widgets:write"], + run_with: APP_TOOL.runWrite, + input_schema: { + type: "object", + properties: { + path_params: { type: "object", properties: { widget_id: { type: "string" } }, required: ["widget_id"] }, + query: { type: "object", properties: { limit: { type: "integer" }, note: { type: "string" } } }, + body: { type: "object", properties: { reason: { type: "string" }, urgent: { type: "boolean" }, level: { enum: ["low", "high"] } } }, + }, + }, +}; +const LIST: ActionDetail = { name: "list_widgets", method: "GET", scopes: ["widgets:read"], run_with: APP_TOOL.runRead, input_schema: { type: "object", properties: {} } }; + +const jwt = (claims: object) => `h.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.s`; +const failure = (statusCode: number, code?: string, message = "failed") => + JSON.stringify({ status: "error", statusCode, message, errors: [{ message, ...(code ? { code } : {}) }] }); + +const ok = (...texts: string[]): ToolResult => ({ isError: false, texts, requestId: "req" }); +const err = (statusCode: number, code?: string, message?: string): ToolResult => ({ isError: true, texts: [failure(statusCode, code, message)], requestId: "req" }); + +// A fake AppClient answering each call from a queue, recording the tool, arguments and retry flag. +function scripted(...results: ToolResult[]) { + const calls: Array<{ tool: string; args: Record; retryable: boolean }> = []; + const client: AppClient = { call: async (tool, args, { retryable }) => (calls.push({ tool, args, retryable }), results.shift() ?? assert.fail(`unexpected ${tool}`)) }; + return { client, calls }; +} + +// ---------------- eligibility ---------------- + +const oauthSource = (accessToken: string) => ({ current: () => ({ access_token: accessToken }) }) as unknown as OAuthSource; + +test("no login, or a PAT saved by an earlier release, is auth.oauth_required before any call", () => { + const cases: ResolvedToken[] = [{ token: null, source: "none" }, { token: "pat", source: "keychain" }]; + for (const resolved of cases) assert.throws(() => assertEligible(resolved), (error: CliError) => error.code === "auth.oauth_required" && /deel auth login/.test(error.next ?? "")); +}); + +test("a token without a client_id claim is a PAT", () => { + assert.throws(() => assertEligible({ token: jwt({ sub: "1" }), source: "env" }), (error: CliError) => error.code === "auth.oauth_required"); +}); + +test("a DEEL_TOKEN that is not a JWT is refused, a stored OAuth login that isn't decodable is left to the server", () => { + assert.throws(() => assertEligible({ token: "opaque", source: "env" }), (error: CliError) => error.code === "auth.oauth_required"); + assert.doesNotThrow(() => assertEligible({ token: "opaque", source: "oauth", oauth: oauthSource("opaque") })); +}); + +test("a token that hides PII or employment data is app.sensitive_data_hidden", () => { + for (const claim of ["hide_pii_data", "hide_employment_data"]) { + assert.throws(() => assertEligible({ token: jwt({ client_id: "c", [claim]: true }), source: "stdin" }), (error: CliError) => error.code === "app.sensitive_data_hidden"); + } +}); + +test("an OAuth login is checked on its current access token", () => { + const good = jwt({ client_id: "c" }); + assert.doesNotThrow(() => assertEligible({ token: "stale", source: "oauth", oauth: oauthSource(good) })); + assert.throws(() => assertEligible({ token: good, source: "oauth", oauth: oauthSource(jwt({ client_id: "c", hide_pii_data: true })) }), (error: CliError) => error.code === "app.sensitive_data_hidden"); +}); + +// ---------------- client: retries and renewal ---------------- + +const rpc = (result: unknown): HttpResponse => ({ status: 200, headers: { "content-type": "application/json" }, text: JSON.stringify({ jsonrpc: "2.0", id: 1, result }), json: undefined }); +const content = (texts: string[], isError = false) => rpc({ content: texts.map((text) => ({ type: "text", text })), ...(isError ? { isError } : {}) }); + +function client(responses: HttpResponse[], opts: { renew?: () => Promise } = {}) { + const requests: HttpRequest[] = []; + const sleeps: number[] = []; + let id = 0; + const http: Transport = async (request) => (requests.push(request), responses.shift() ?? assert.fail("unexpected request")); + const appClient = createAppClient({ http, url: "https://mcp.example.test/mcp", newRequestId: () => `r${++id}`, renew: opts.renew, sleep: async (ms) => void sleeps.push(ms) }); + return { appClient, requests, sleeps }; +} + +test("a transient failure on a retryable call is retried with backoff, and each attempt has its own request id", async () => { + const { appClient, requests, sleeps } = client([content([failure(503, "UPSTREAM_UNAVAILABLE")], true), content([failure(429)], true), content(["ok"])]); + const result = await appClient.call(APP_TOOL.search, { query: "x" }, { retryable: true }); + assert.deepEqual(result.texts, ["ok"]); + assert.deepEqual(sleeps, [200, 400]); + assert.deepEqual(requests.map((request) => request.headers["x-request-id"]), ["r1", "r2", "r3"]); +}); + +test("a write is never retried", async () => { + const { appClient, requests } = client([content([failure(504, "UPSTREAM_TIMEOUT")], true)]); + const result = await appClient.call(APP_TOOL.runWrite, { name: "x" }, { retryable: false }); + assert.equal(result.isError, true); + assert.equal(requests.length, 1); +}); + +test("a permanent failure is returned at once", async () => { + const { appClient, requests } = client([content([failure(404, "ACTION_NOT_FOUND")], true)]); + assert.equal((await appClient.call(APP_TOOL.get, { name: "x" }, { retryable: true })).isError, true); + assert.equal(requests.length, 1); +}); + +test("AUTHENTICATION_REQUIRED renews the login once and retries, also on a write", async () => { + let renewals = 0; + const { appClient, requests } = client([content([failure(401, "AUTHENTICATION_REQUIRED")], true), content(["done"])], { renew: async () => (renewals++, true) }); + assert.deepEqual((await appClient.call(APP_TOOL.runWrite, { name: "x" }, { retryable: false })).texts, ["done"]); + assert.equal(renewals, 1); + assert.equal(requests.length, 2); +}); + +test("a login is renewed at most once per call, across an HTTP 401 and an isError 401", async () => { + let renewals = 0; + const unauthorized: HttpResponse = { status: 401, headers: {}, text: "", json: undefined }; + const { appClient } = client([unauthorized, content([failure(401, "AUTHENTICATION_REQUIRED")], true)], { renew: async () => (renewals++, true) }); + const result = await appClient.call(APP_TOOL.search, { query: "x" }, { retryable: false }); + assert.equal(result.isError, true); + assert.equal(renewals, 1); +}); + +// ---------------- errors ---------------- + +test("the server's error codes map to CLI errors with a next step", () => { + const mapped = (statusCode: number, code: string | undefined, context = {}, message = "server said no") => appError({ statusCode, code, message }, "req", context); + assert.equal(mapped(401, "AUTHENTICATION_REQUIRED").code, "auth.expired"); + assert.equal(mapped(403, "TOKEN_TYPE_NOT_ALLOWED", {}, "App actions need an OAuth token").code, "auth.oauth_required"); + assert.equal(mapped(403, "TOKEN_TYPE_NOT_ALLOWED", {}, "not available to a token that hides PII or employment data").code, "app.sensitive_data_hidden"); + assert.equal(mapped(403, "APP_ACTIONS_NOT_ALLOWED").code, "app.unavailable"); + assert.equal(mapped(503, "APP_ACTIONS_NOT_CONFIGURED").code, "app.unavailable"); + const notFound = mapped(404, "ACTION_NOT_FOUND", { action: "nope" }); + assert.equal(notFound.code, "app.action_not_found"); + assert.match(notFound.message, /"nope"/); + assert.match(notFound.next ?? "", /deel app search/); + assert.match(mapped(403, "INSUFFICIENT_SCOPES", { scopes: ["a:write", "b:write"] }).next ?? "", /--scopes a:write,b:write/); + assert.match(mapped(403, "INSUFFICIENT_SCOPES").next ?? "", /--scopes /); + assert.match(mapped(403, "INSUFFICIENT_SCOPES", {}, "x needs one of these scopes: a:read, b:read").next ?? "", /--scopes a:read,b:read/); + assert.match(mapped(400, "INVALID_ARGUMENTS", { action: "x" }).next ?? "", /deel app describe x/); + assert.equal(mapped(400, "INVALID_ARGUMENTS").next, undefined); + assert.equal(mapped(400, "WRONG_ACTION_KIND").code, "app.wrong_kind"); + assert.equal(mapped(403, "PERMISSION_DENIED").code, "app.permission_denied"); + assert.equal(mapped(401, "INVALID_MCP_ASSERTION").code, "app.invalid_mcp_assertion"); + assert.equal(mapped(418, undefined).code, "app.http_418"); + assert.equal(mapped(500, "UPSTREAM_SERVER_ERROR").code, "app.upstream_server_error"); + assert.equal(mapped(403, "INSUFFICIENT_SCOPES").requestId, "req"); +}); + +test("a rate limit says to check before re-running a write", () => { + assert.equal(appError({ statusCode: 429, message: "slow down" }, "r").next, "Wait a moment and try again."); + assert.match(appError({ statusCode: 429, message: "slow down" }, "r", { write: true }).next ?? "", /check whether the action ran/); +}); + +test("a write that got no answer has an unknown outcome", () => { + for (const code of ["UPSTREAM_TIMEOUT", "UPSTREAM_UNAVAILABLE", "UPSTREAM_SERVER_ERROR", undefined]) { + const error = appError({ statusCode: code === "UPSTREAM_TIMEOUT" ? 504 : 503, code, message: "no answer." }, "r", { write: true }); + assert.equal(error.code, "app.outcome_unknown"); + assert.match(error.next ?? "", /read action/); + } + assert.equal(appError({ statusCode: 400, code: "UPSTREAM_CLIENT_ERROR", message: "bad" }, "r", { write: true }).code, "app.upstream_client_error"); + assert.equal(appError({ statusCode: 504, code: "UPSTREAM_TIMEOUT", message: "The action timed out" }, "r", { write: true }).message, "The action timed out. The action may or may not have run."); + assert.equal(appError({ statusCode: 504, code: "UPSTREAM_TIMEOUT", message: "No answer." }, "r", { write: true }).message, "No answer. The action may or may not have run."); +}); + +// ---------------- search and describe ---------------- + +test("search sends the query and limit and returns the actions", async () => { + const { client: fake, calls } = scripted(ok(JSON.stringify({ actions: [{ name: "list_widgets" }] }))); + const found = await searchActions(fake, "widgets", 5); + assert.deepEqual(found, { actions: [{ name: "list_widgets" }], requestId: "req" }); + assert.deepEqual(calls, [{ tool: APP_TOOL.search, args: { query: "widgets", limit: 5 }, retryable: true }]); +}); + +test("search checks its arguments before calling", async () => { + const { client: fake, calls } = scripted(); + await assert.rejects(() => searchActions(fake, " "), (error: CliError) => error.code === "usage.app"); + for (const limit of [0, 21, 1.5]) await assert.rejects(() => searchActions(fake, "x", limit), (error: CliError) => error.code === "usage.app"); + assert.equal(calls.length, 0); +}); + +test("search maps an isError result and rejects a result that isn't JSON", async () => { + await assert.rejects(() => searchActions(scripted(err(403, "APP_ACTIONS_NOT_ALLOWED")).client, "x"), (error: CliError) => error.code === "app.unavailable"); + await assert.rejects(() => searchActions(scripted(ok("not json")).client, "x"), (error: CliError) => error.code === "mcp.response" && error.requestId === "req"); + assert.deepEqual((await searchActions(scripted(ok("{}")).client, "x")).actions, []); +}); + +test("getAction returns the action and names it in errors", async () => { + assert.deepEqual((await getAction(scripted(ok(JSON.stringify(LIST))).client, "list_widgets")).action, LIST); + await assert.rejects(() => getAction(scripted(err(404, "ACTION_NOT_FOUND")).client, "nope"), (error: CliError) => error.code === "app.action_not_found" && /"nope"/.test(error.message)); +}); + +// ---------------- run ---------------- + +test("--input must be an object of path_params, query and body", () => { + assert.deepEqual(actionInput(undefined), {}); + assert.deepEqual(actionInput({ path_params: { a: 1 }, body: [] }), { path_params: { a: 1 }, body: [] }); + for (const bad of ["x", [1], null]) assert.throws(() => actionInput(bad), (error: CliError) => error.code === "usage.app_input"); + assert.throws(() => actionInput({ widget_id: 1 }), (error: CliError) => error.code === "usage.app_input" && /widget_id/.test(error.message)); +}); + +test("path and query values follow the schema's string or number types; the body is left as is", () => { + const input = { path_params: { widget_id: 123 }, query: { limit: "5", note: true, other: 7 }, body: { reason: 1 } }; + assert.deepEqual(coerceInput(input, APPROVE.input_schema), { path_params: { widget_id: "123" }, query: { limit: 5, note: "true", other: 7 }, body: { reason: 1 } }); + assert.deepEqual(coerceInput({ query: { limit: "many" } }, APPROVE.input_schema), { query: { limit: "many" } }); + assert.deepEqual(coerceInput({}, undefined), {}); +}); + +test("run uses the tool get_action names in run_with, and a write when it names none", () => { + assert.equal(runCall(LIST, {}).tool, APP_TOOL.runRead); + assert.equal(runCall(APPROVE, {}).tool, APP_TOOL.runWrite); + assert.equal(runCall({ name: "x" }, {}).tool, APP_TOOL.runWrite); + assert.deepEqual(runCall(APPROVE, { path_params: { widget_id: 9 } }).arguments, { name: "approve_widget", path_params: { widget_id: "9" } }); +}); + +test("a read is retryable and a write is not", async () => { + const read = scripted(ok("[]")); + await runAction(read.client, LIST, {}); + assert.deepEqual(read.calls, [{ tool: APP_TOOL.runRead, args: { name: "list_widgets" }, retryable: true }]); + const write = scripted(ok("{}")); + await runAction(write.client, APPROVE, { path_params: { widget_id: "w1" } }); + assert.deepEqual(write.calls, [{ tool: APP_TOOL.runWrite, args: { name: "approve_widget", path_params: { widget_id: "w1" } }, retryable: false }]); +}); + +test("WRONG_ACTION_KIND retries once with the other tool", async () => { + const { client: fake, calls } = scripted(err(400, "WRONG_ACTION_KIND"), ok('{"status":"ok"}')); + const outcome = await runAction(fake, LIST, {}); + assert.deepEqual(outcome.data, { status: "ok" }); + assert.deepEqual(calls.map((call) => [call.tool, call.retryable]), [[APP_TOOL.runRead, true], [APP_TOOL.runWrite, false]]); +}); + +test("a failed run carries the action's scopes into the next step", async () => { + await assert.rejects(() => runAction(scripted(err(403, "INSUFFICIENT_SCOPES")).client, APPROVE, {}), (error: CliError) => error.code === "auth.insufficient_scope" && /widgets:write/.test(error.next ?? "")); + await assert.rejects(() => runAction(scripted(err(504, "UPSTREAM_TIMEOUT")).client, APPROVE, {}), (error: CliError) => error.code === "app.outcome_unknown"); +}); + +test("a run returns the body as JSON when it parses, as text otherwise", () => { + assert.deepEqual(runOutcome(ok('{"id":"w1"}')), { data: { id: "w1" }, requestId: "req" }); + assert.deepEqual(runOutcome(ok("plain text")), { data: "plain text", requestId: "req" }); + assert.deepEqual(runOutcome(ok()), { data: "", requestId: "req" }); +}); + +test("a cut body stays text and reports how much was shown", () => { + const notice = "[Response truncated: the action returned 162732 bytes; only the first 102400 bytes are shown.]"; + assert.deepEqual(runOutcome(ok('{"items":[1,2', notice)), { data: '{"items":[1,2', requestId: "req", truncated: { total_bytes: 162732, shown_bytes: 102400 } }); +}); + +// ---------------- describe --generate-input ---------------- + +test("the input skeleton follows the schema", () => { + assert.deepEqual(inputSkeleton(APPROVE), { + path_params: { widget_id: "" }, + query: { limit: 0, note: "" }, + body: { reason: "", urgent: false, level: "low" }, + }); + assert.deepEqual(inputSkeleton(LIST), {}); + assert.deepEqual(inputSkeleton({ name: "x" }), {}); + const combined: ActionDetail = { name: "x", input_schema: { type: "object", properties: { path_params: { type: "object", properties: { id: { allOf: [{ type: "string" }, { pattern: "x" }] }, tags: { type: "array" }, n: { type: "number" } } } } } }; + assert.deepEqual(inputSkeleton(combined), { path_params: { id: "", tags: [], n: 0 } }); +}); diff --git a/test/app.test.ts b/test/app.test.ts new file mode 100644 index 0000000..cbf4166 --- /dev/null +++ b/test/app.test.ts @@ -0,0 +1,232 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { TestContext } from "node:test"; +import { positionals, runDescribe, runRun, runSearch } from "../src/commands/app.ts"; +import type { AppDeps } from "../src/commands/app.ts"; +import { staticCommands } from "../src/commands/index.ts"; +import { RESERVED_COMMANDS } from "../src/core/constants.ts"; +import { resolveConfig, resolveMcpUrl } from "../src/core/config.ts"; +import type { CliError } from "../src/core/errors.ts"; +import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; +import type { IOStreams } from "../src/core/io.ts"; +import type { CredentialStore } from "../src/core/keychain.ts"; +import { readOAuthEntry, writeOAuthEntry } from "../src/core/oauth.ts"; +import { tempDir } from "./stubs.ts"; + +// Made-up actions only: deel-cli is public. +const ISSUER = "https://api.letsdeel.com"; +const MCP = `${ISSUER}/mcp`; +const jwt = (claims: object) => `h.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.s`; +const ACCESS = jwt({ client_id: "cli", scope: "widgets:read widgets:write" }); +const RENEWED = jwt({ client_id: "cli", scope: "widgets:read widgets:write", n: 2 }); +const ARGS = { json: true }; +const LIST = { name: "list_widgets", method: "GET", scopes: ["widgets:read"], run_with: "run_read_action", input_schema: { type: "object", properties: { query: { type: "object", properties: { status: { type: "string" } } } } } }; +const APPROVE = { + name: "approve_widget", + method: "POST", + scopes: ["widgets:write"], + run_with: "run_write_action", + input_schema: { type: "object", properties: { path_params: { type: "object", properties: { widget_id: { type: "string" } }, required: ["widget_id"] } }, required: ["path_params"] }, +}; + +function isolated(t: TestContext, env: Record = {}) { + const keys = ["DEEL_LOG_DIR", "DEEL_TOKEN", "DEEL_OAUTH_ISSUER", "DEEL_ENV", "DEEL_MCP_URL"]; + const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]])); + for (const key of keys) delete process.env[key]; + process.env.DEEL_LOG_DIR = tempDir(t); + Object.assign(process.env, env); + t.after(() => { + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + }); +} + +function loggedIn(accessToken = ACCESS) { + const items = new Map(); + const store: CredentialStore = { + available: () => true, + get: (account) => items.get(account) ?? null, + set: (account, value) => (items.set(account, value), true), + remove: (account) => items.delete(account), + }; + writeOAuthEntry(store, ISSUER, { v: 2, access_token: accessToken, refresh_token: "rt", expires_at: new Date(Date.now() + 3600_000).toISOString() }); + return store; +} + +function captureIO() { + const out: string[] = []; + const err: string[] = []; + const io: IOStreams = { out: (text) => out.push(text), err: (text) => err.push(text), readStdin: () => "", isTTY: false, interactive: false }; + return { io, json: () => JSON.parse(out.join("")), out: () => out.join(""), err: () => err.join("") }; +} + +const toolResult = (texts: string[], isError = false) => ({ content: texts.map((text) => ({ type: "text", text })), ...(isError ? { isError } : {}) }); +const failure = (statusCode: number, code: string, message = "failed") => JSON.stringify({ status: "error", statusCode, message, errors: [{ message, code }] }); + +// /mcp answering tools/call from a handler; OAuth discovery and the token endpoint for a refresh. +function server(handle: (tool: string, args: Record, request: HttpRequest) => { texts: string[]; isError?: boolean } | HttpResponse) { + const requests: HttpRequest[] = []; + const transport: Transport = async (request) => { + requests.push(request); + const json = (status: number, body: unknown): HttpResponse => ({ status, headers: { "content-type": "application/json" }, text: JSON.stringify(body), json: body }); + if (request.url.endsWith("/.well-known/oauth-authorization-server")) { + return json(200, { issuer: ISSUER, authorization_endpoint: `${ISSUER}/oauth/authorize`, token_endpoint: `${ISSUER}/oauth/tokens` }); + } + if (request.url === `${ISSUER}/oauth/tokens`) return json(200, { access_token: RENEWED, refresh_token: "rt2", expires_in: 3600 }); + const rpc = JSON.parse(String(request.body)) as { params: { name: string; arguments: Record } }; + const answer = handle(rpc.params.name, rpc.params.arguments, request); + if ("status" in answer) return answer; + return json(200, { jsonrpc: "2.0", id: 1, result: toolResult(answer.texts, answer.isError) }); + }; + return { transport, requests, tools: () => requests.filter((request) => request.url.endsWith("/mcp")).map((request) => JSON.parse(String(request.body)).params) }; +} + +function deps(transport: Transport, store: CredentialStore, io: IOStreams): AppDeps { + return { baseTransport: transport, store, io, sleep: async () => {} }; +} + +test("app is a static command and a reserved name", () => { + assert.ok(staticCommands.app); + assert.ok(RESERVED_COMMANDS.has("app")); +}); + +test("the MCP URL is /mcp on the API host, or DEEL_MCP_URL", (t) => { + isolated(t); + assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), MCP); + assert.equal(resolveMcpUrl(resolveConfig({ env: "demo" })), "https://api-staging.letsdeel.com/mcp"); + process.env.DEEL_MCP_URL = "https://mcp.example.test/mcp/"; + assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), "https://mcp.example.test/mcp"); + process.env.DEEL_MCP_URL = "http://mcp.example.test/mcp"; + assert.throws(() => resolveMcpUrl(resolveConfig({ env: "prod" })), (error: CliError) => error.code === "config.mcp"); +}); + +test("search prints the actions with the request id", async (t) => { + isolated(t); + const io = captureIO(); + const { transport, tools, requests } = server(() => ({ texts: [JSON.stringify({ actions: [{ name: "list_widgets", method: "GET" }] })] })); + await runSearch({ ...ARGS, _: ["pending", "widgets"], limit: "5" }, [], deps(transport, loggedIn(), io.io)); + assert.deepEqual(tools(), [{ name: "search_actions", arguments: { query: "pending widgets", limit: 5 } }]); + const printed = io.json(); + assert.deepEqual(printed.data, { actions: [{ name: "list_widgets", method: "GET" }] }); + assert.equal(printed.meta.request_id, requests[0].headers["x-request-id"]); + assert.equal(requests[0].url, MCP); + assert.equal(requests[0].headers.authorization, `Bearer ${ACCESS}`); +}); + +test("search without words is a usage error, before any call", async (t) => { + isolated(t); + const { transport, requests } = server(() => assert.fail("no call expected")); + await assert.rejects(() => runSearch({ ...ARGS, _: [] }, [], deps(transport, loggedIn(), captureIO().io)), (error: CliError) => error.code === "usage.app"); + assert.equal(requests.length, 0); +}); + +test("a PAT in DEEL_TOKEN is refused before any call", async (t) => { + isolated(t, { DEEL_TOKEN: jwt({ sub: "pat" }) }); + const { transport, requests } = server(() => assert.fail("no call expected")); + await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, loggedIn(), captureIO().io)), (error: CliError) => error.code === "auth.oauth_required"); + assert.equal(requests.length, 0); +}); + +test("describe prints each action, and --generate-input prints a skeleton", async (t) => { + isolated(t); + const actions: Record = { list_widgets: LIST, approve_widget: APPROVE }; + const { transport, tools } = server((_tool, args) => ({ texts: [JSON.stringify(actions[String(args.name)])] })); + const io = captureIO(); + await runDescribe({ ...ARGS, _: ["list_widgets", "approve_widget"] }, [], deps(transport, loggedIn(), io.io)); + assert.deepEqual(io.json().data.actions, [LIST, APPROVE]); + assert.deepEqual(tools().map((call) => call.arguments), [{ name: "list_widgets" }, { name: "approve_widget" }]); + + const skeleton = captureIO(); + await runDescribe({ ...ARGS, _: ["approve_widget"], "generate-input": true }, [], deps(transport, loggedIn(), skeleton.io)); + assert.deepEqual(JSON.parse(skeleton.out()), { path_params: { widget_id: "" } }); + await assert.rejects(() => runDescribe({ ...ARGS, _: ["a", "b"], "generate-input": true }, [], deps(transport, loggedIn(), captureIO().io)), (error: CliError) => error.code === "usage.app"); + await assert.rejects(() => runDescribe({ ...ARGS, _: [] }, [], deps(transport, loggedIn(), captureIO().io)), (error: CliError) => error.code === "usage.app"); +}); + +test("run reads the action, then calls run_read_action with the parsed input", async (t) => { + isolated(t); + const { transport, tools } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(LIST)] } : { texts: ['[{"id":"w1"}]'] })); + const io = captureIO(); + await runRun({ ...ARGS, _: ["list_widgets"], input: "query={status=pending}" }, [], deps(transport, loggedIn(), io.io)); + assert.deepEqual(tools(), [ + { name: "get_action", arguments: { name: "list_widgets" } }, + { name: "run_read_action", arguments: { name: "list_widgets", query: { status: "pending" } } }, + ]); + assert.deepEqual(io.json().data, [{ id: "w1" }]); +}); + +test("run of a write calls run_write_action without asking, and is sent once", async (t) => { + isolated(t); + const { transport, tools, requests } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(APPROVE)] } : { texts: [failure(504, "UPSTREAM_TIMEOUT", "The action timed out")], isError: true })); + await assert.rejects( + () => runRun({ ...ARGS, _: ["approve_widget"], input: "path_params={widget_id=123}" }, [], deps(transport, loggedIn(), captureIO().io)), + (error: CliError) => error.code === "app.outcome_unknown" && Boolean(error.requestId), + ); + assert.deepEqual(tools()[1], { name: "run_write_action", arguments: { name: "approve_widget", path_params: { widget_id: "123" } } }); + assert.equal(requests.filter((request) => request.url === MCP).length, 2); + assert.equal(requests[1].retryable, false); +}); + +test("run --dry-run prints the call and runs nothing", async (t) => { + isolated(t); + const { transport, tools } = server(() => ({ texts: [JSON.stringify(APPROVE)] })); + const io = captureIO(); + await runRun({ ...ARGS, _: ["approve_widget"], input: '{"path_params":{"widget_id":"w1"}}', "dry-run": true }, [], deps(transport, loggedIn(), io.io)); + assert.equal(tools().length, 1); + const printed = io.json(); + assert.deepEqual(printed.data, { method: "tools/call", params: { name: "run_write_action", arguments: { name: "approve_widget", path_params: { widget_id: "w1" } } } }); + assert.equal(printed.meta.dry_run, true); +}); + +test("run checks its arguments and --input before any call", async (t) => { + isolated(t); + const { transport, requests } = server(() => assert.fail("no call expected")); + const run = (args: Record) => runRun({ ...ARGS, ...args }, [], deps(transport, loggedIn(), captureIO().io)); + await assert.rejects(() => run({ _: [] }), (error: CliError) => error.code === "usage.app"); + await assert.rejects(() => run({ _: ["a", "b"] }), (error: CliError) => error.code === "usage.app"); + await assert.rejects(() => run({ _: ["a"], input: "widget_id=1" }), (error: CliError) => error.code === "usage.app_input"); + assert.equal(requests.length, 0); +}); + +test("a truncated response is returned as text with meta.truncated and a warning", async (t) => { + isolated(t); + const notice = "[Response truncated: the action returned 200000 bytes; only the first 102400 bytes are shown.]"; + const { transport } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(LIST)] } : { texts: ['[{"id":', notice] })); + const io = captureIO(); + await runRun({ ...ARGS, _: ["list_widgets"] }, [], deps(transport, loggedIn(), io.io)); + const printed = io.json(); + assert.equal(printed.data, '[{"id":'); + assert.deepEqual(printed.meta.truncated, { total_bytes: 200000, shown_bytes: 102400 }); + assert.match(io.err(), /cut at 102400 of 200000 bytes/); +}); + +test("an HTTP 401 renews the stored login and retries with the new token", async (t) => { + isolated(t); + const store = loggedIn(); + const { transport, requests } = server((_tool, _args, request) => + request.headers.authorization === `Bearer ${ACCESS}` ? { status: 401, headers: {}, text: "", json: undefined } : { texts: ['{"actions":[]}'] }, + ); + const io = captureIO(); + await runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, store, io.io)); + const mcpCalls = requests.filter((request) => request.url === MCP); + assert.deepEqual(mcpCalls.map((request) => request.headers.authorization), [`Bearer ${ACCESS}`, `Bearer ${RENEWED}`]); + assert.equal(readOAuthEntry(store, ISSUER)?.access_token, RENEWED); + assert.deepEqual(io.json().data, { actions: [] }); +}); + +test("DEEL_MCP_URL points the commands at another /mcp", async (t) => { + isolated(t, { DEEL_MCP_URL: "https://mcp.example.test/mcp" }); + const { transport, requests } = server(() => ({ texts: ['{"actions":[]}'] })); + await runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, loggedIn(), captureIO().io)); + assert.equal(requests[0].url, "https://mcp.example.test/mcp"); +}); + +test("the value of the hidden --base-url flag is not a positional word", () => { + const url = "https://api.example.test/rest"; + assert.deepEqual(positionals({ _: ["time", url, "off"] }, ["time", "--base-url", url, "off"]), ["time", "off"]); + assert.deepEqual(positionals({ _: ["a"] }, ["a", `--base-url=${url}`]), ["a"]); + assert.deepEqual(positionals({ _: ["a"] }, ["a", "--base-url"]), ["a"]); + assert.deepEqual(positionals({}, []), []); +}); diff --git a/test/auth.test.ts b/test/auth.test.ts index 536dc83..1fb671a 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import type { TestContext } from "node:test"; -import { resolveToken, requireToken, authFor, accessTokenScope, maskToken, redactHeaders, baseUrlRefused } from "../src/core/auth.ts"; +import { resolveToken, requireToken, authFor, accessTokenClaims, accessTokenScope, maskToken, redactHeaders, baseUrlRefused } from "../src/core/auth.ts"; import { resolveConfig } from "../src/core/config.ts"; import { CliError } from "../src/core/errors.ts"; import type { HttpResponse, Transport } from "../src/core/http.ts"; @@ -253,6 +253,13 @@ test("accessTokenScope reads the scope claim without verifying the token", () => assert.equal(accessTokenScope(jwt({ scope: ["a", "b"] })), "a b"); }); +test("accessTokenClaims decodes a JWT payload object, and gives null otherwise", () => { + assert.deepEqual(accessTokenClaims(jwt({ client_id: "c", hide_pii_data: true })), { client_id: "c", hide_pii_data: true }); + assert.equal(accessTokenClaims("opaque-token"), null); + assert.equal(accessTokenClaims(`h.${Buffer.from("[1]").toString("base64url")}.s`), null); + assert.equal(accessTokenClaims(`h.${Buffer.from("null").toString("base64url")}.s`), null); +}); + test("accessTokenScope gives null when the token cannot be decoded or has no scope", () => { assert.equal(accessTokenScope("opaque-token"), null); assert.equal(accessTokenScope("a.%%%.c"), null); diff --git a/test/io.test.ts b/test/io.test.ts new file mode 100644 index 0000000..eb65877 --- /dev/null +++ b/test/io.test.ts @@ -0,0 +1,49 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { FORCED_EXIT_MS, exitAfterFlush } from "../src/core/io.ts"; + +const IO_MODULE = fileURLToPath(new URL("../src/core/io.ts", import.meta.url)); + +function fakes() { + const callbacks: Array<() => void> = []; + const stream = { write: (_chunk: string, callback?: () => void) => (callbacks.push(callback!), true) }; + const codes: number[] = []; + const exits: number[] = []; + const scheduled: number[] = []; + const opts = { + setExitCode: (code: number) => void codes.push(code), + exit: (code: number) => void exits.push(code), + schedule: (run: () => void, ms: number) => (scheduled.push(ms), run()), + }; + return { callbacks, stream, codes, exits, scheduled, opts }; +} + +test("exitAfterFlush sets the exit code at once and forces the exit only after every stream has flushed", () => { + const { callbacks, stream, codes, exits, scheduled, opts } = fakes(); + exitAfterFlush(3, { ...opts, streams: [stream, stream] as never }); + assert.deepEqual(codes, [3]); + assert.deepEqual(exits, []); + callbacks[0](); + assert.deepEqual(exits, []); + callbacks[1](); + assert.deepEqual(scheduled, [FORCED_EXIT_MS]); + assert.deepEqual(exits, [3]); +}); + +test("exitAfterFlush with no streams schedules the forced exit at once", () => { + const { codes, exits, opts } = fakes(); + exitAfterFlush(0, { ...opts, streams: [] }); + assert.deepEqual(codes, [0]); + assert.deepEqual(exits, [0]); +}); + +test("a large output piped to a slow reader arrives whole", () => { + const size = 300_000; // well past the 64 KB a pipe holds + const script = `import { exitAfterFlush } from ${JSON.stringify(IO_MODULE)}; process.stdout.write("x".repeat(${size})); exitAfterFlush(0);`; + const reader = `import sys, time; time.sleep(0.3); print(len(sys.stdin.read()))`; + const result = spawnSync("sh", ["-c", `"${process.execPath}" --input-type=module -e '${script}' | python3 -c '${reader}'`], { encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), String(size)); +}); diff --git a/test/mcp.test.ts b/test/mcp.test.ts new file mode 100644 index 0000000..7c0c59a --- /dev/null +++ b/test/mcp.test.ts @@ -0,0 +1,118 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { MCP_ACCEPT, callTool, parseRpcBody, toolFailure } from "../src/core/mcp.ts"; +import type { CliError } from "../src/core/errors.ts"; +import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; + +const URL = "https://mcp.example.test/mcp"; + +const reply = (status: number, body: unknown, contentType = "application/json"): HttpResponse => ({ + status, + headers: { "content-type": contentType }, + text: typeof body === "string" ? body : JSON.stringify(body), + json: undefined, +}); + +const result = (texts: string[], isError = false) => ({ jsonrpc: "2.0", id: 1, result: { content: texts.map((text) => ({ type: "text", text })), ...(isError ? { isError } : {}) } }); + +function recording(...responses: HttpResponse[]) { + const requests: HttpRequest[] = []; + const transport: Transport = async (request) => (requests.push(request), responses.shift() ?? reply(500, {})); + return { transport, requests }; +} + +const call = (http: Transport, extra: Partial[0]> = {}) => + callTool({ http, url: URL, requestId: "req-1", name: "search_actions", args: { query: "time off" }, retryable: true, ...extra }); + +test("a tool call is one JSON-RPC tools/call POST with the request id and MCP accept header", async () => { + const { transport, requests } = recording(reply(200, result(['{"actions":[]}']))); + const outcome = await call(transport); + assert.deepEqual(outcome, { isError: false, texts: ['{"actions":[]}'], requestId: "req-1" }); + assert.equal(requests.length, 1); + const [request] = requests; + assert.equal(request.method, "POST"); + assert.equal(request.url, URL); + assert.equal(request.headers.accept, MCP_ACCEPT); + assert.equal(request.headers["x-request-id"], "req-1"); + assert.equal(request.retryable, true); + assert.deepEqual(JSON.parse(String(request.body)), { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "search_actions", arguments: { query: "time off" } } }); +}); + +test("an SSE response is read from its data lines", async () => { + const sse = `event: message\ndata: ${JSON.stringify(result(["ok"]))}\n\n`; + const { transport } = recording(reply(200, sse, "text/event-stream")); + assert.deepEqual((await call(transport)).texts, ["ok"]); +}); + +test("parseRpcBody picks the SSE message with the call's id and skips bad lines", () => { + const text = ["data: not json", `data: ${JSON.stringify({ jsonrpc: "2.0", id: 9, result: {} })}`, `data: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { x: 1 } })}`].join("\n"); + assert.deepEqual(parseRpcBody(text, "text/event-stream", 1)?.result, { x: 1 }); + assert.equal(parseRpcBody("data: {}", "text/event-stream", 1), null); + assert.equal(parseRpcBody("", "application/json", 1), null); +}); + +test("an isError result is returned as data, not thrown", async () => { + const { transport } = recording(reply(200, result(['{"statusCode":404}'], true))); + const outcome = await call(transport); + assert.equal(outcome.isError, true); +}); + +test("an HTTP 401 renews the login once and retries", async () => { + const { transport, requests } = recording(reply(401, {}), reply(200, result(["ok"]))); + let renewals = 0; + const outcome = await call(transport, { onUnauthorized: async () => (renewals++, true) }); + assert.equal(renewals, 1); + assert.equal(requests.length, 2); + assert.deepEqual(outcome.texts, ["ok"]); +}); + +test("a second 401, or one with nothing to renew, is auth.expired with the request id", async () => { + for (const onUnauthorized of [async () => true, async () => false, undefined]) { + const { transport } = recording(reply(401, {}), reply(401, {})); + await assert.rejects( + () => call(transport, { onUnauthorized }), + (error: CliError) => error.code === "auth.expired" && error.next === "deel auth login" && error.requestId === "req-1", + ); + } +}); + +test("another HTTP status is http.", async () => { + const { transport } = recording(reply(502, "bad gateway", "text/plain")); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "http.502" && error.requestId === "req-1"); +}); + +test("a body that is not JSON-RPC is mcp.response", async () => { + const { transport } = recording(reply(200, "", "text/html")); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.response"); +}); + +test("an unknown tool means app actions are off on the server", async () => { + const { transport } = recording(reply(200, { jsonrpc: "2.0", id: 1, error: { code: -32602, message: "Tool search_actions not found" } })); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "app.unavailable"); +}); + +test("another JSON-RPC error is mcp.rpc with a printable message", async () => { + const { transport } = recording(reply(200, { jsonrpc: "2.0", id: 1, error: { code: -32603, message: "boom\u001b[31m" } })); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.rpc" && error.message === "boom [31m (JSON-RPC -32603)"); +}); + +test("non-text content items are ignored", async () => { + const body = { jsonrpc: "2.0", id: 1, result: { content: [{ type: "image", data: "x" }, { type: "text", text: "a" }, null] } }; + const { transport } = recording(reply(200, body)); + assert.deepEqual((await call(transport)).texts, ["a"]); +}); + +test("toolFailure reads the status, code, message and details of the server's error payload", () => { + const payload = { status: "error", statusCode: 403, message: "needs a scope", errors: [{ message: "needs a scope", code: "INSUFFICIENT_SCOPES" }], details: { a: 1 } }; + assert.deepEqual(toolFailure({ isError: true, texts: [JSON.stringify(payload)], requestId: "r" }), { + statusCode: 403, + code: "INSUFFICIENT_SCOPES", + message: "needs a scope", + details: { a: 1 }, + }); +}); + +test("toolFailure falls back to the text and a 500 for a plain-text error", () => { + assert.deepEqual(toolFailure({ isError: true, texts: ["something broke"], requestId: "r" }), { statusCode: 500, message: "something broke" }); + assert.deepEqual(toolFailure({ isError: true, texts: [], requestId: "r" }), { statusCode: 500, message: "The tool call failed." }); +}); diff --git a/test/oauth.test.ts b/test/oauth.test.ts index 13d71d3..c3e2a9e 100644 --- a/test/oauth.test.ts +++ b/test/oauth.test.ts @@ -4,7 +4,7 @@ import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, readFileSync, readdirSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { CHUNK_SIZE, DEFAULT_TOKEN_LIFETIME_MS, LOCK_MAX_AGE_MS, discover, entryFromTokenResponse, isFresh, postForm, readOAuthEntry, removeStaleLock, withLock, writeOAuthEntry } from "../src/core/oauth.ts"; +import { CHUNK_SIZE, DEFAULT_TOKEN_LIFETIME_MS, LOCK_MAX_AGE_MS, createOAuthSource, discover, entryFromTokenResponse, isFresh, postForm, readOAuthEntry, removeStaleLock, withLock, writeOAuthEntry } from "../src/core/oauth.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; import { tempDir } from "./stubs.ts"; import type { CliError } from "../src/core/errors.ts"; @@ -237,3 +237,35 @@ test("a login too large for the keychain is not written at all", () => { assert.equal(writeOAuthEntry(store, ISSUER, { ...stored, access_token: "a".repeat(CHUNK_SIZE * 65) }), false); assert.deepEqual(store.items, before); }); + +// A token endpoint that hands out "at2", counting the refreshes. +function refreshing() { + const refreshes: string[] = []; + const transport: Transport = async (request) => { + if (request.url.endsWith("/.well-known/oauth-authorization-server")) return { status: 200, headers: {}, text: "", json: METADATA } as HttpResponse; + refreshes.push(String(request.body)); + return { status: 200, headers: {}, text: "", json: { access_token: "at2", refresh_token: "rt2", expires_in: 3600 } } as HttpResponse; + }; + return { transport, refreshes }; +} + +test("renew refreshes a token the server rejected before its expiry", async () => { + const store = memoryStore(); + writeOAuthEntry(store, ISSUER, stored); + const { transport, refreshes } = refreshing(); + const source = createOAuthSource({ store, issuer: ISSUER, clientId: "c", entry: stored, transport }); + assert.equal(await source.token(), "at"); // still fresh: no refresh + assert.equal(await source.renew("at"), "at2"); + assert.equal(refreshes.length, 1); + assert.equal(source.current().access_token, "at2"); + assert.equal(readOAuthEntry(store, ISSUER)?.refresh_token, "rt2"); +}); + +test("renew keeps a token another process already stored instead of refreshing again", async () => { + const store = memoryStore(); + writeOAuthEntry(store, ISSUER, { ...stored, access_token: "at_other" }); + const { transport, refreshes } = refreshing(); + const source = createOAuthSource({ store, issuer: ISSUER, clientId: "c", entry: stored, transport }); + assert.equal(await source.renew("at"), "at_other"); + assert.equal(refreshes.length, 0); +}); diff --git a/test/output.test.ts b/test/output.test.ts index cfffe80..529c3b6 100644 --- a/test/output.test.ts +++ b/test/output.test.ts @@ -97,3 +97,9 @@ test("render --jq and --quiet keep operating on data only (page is not printed)" await render(io2, paged, opts({ quiet: true })); assert.equal(io2.stdout.join("").trim(), "a\nb"); }); + +test("--jq gets a text payload as a string, not as JSON to parse", async () => { + const io = captureIO(); + await render(io, envelope('{"cut": "text'), { json: true, jq: "type", raw: true, quiet: false }); + assert.equal(io.stdout.join(""), "string\n"); +}); From 17078151e391c08350881839a821e9b15190588a Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Mon, 9 Nov 2026 19:18:49 -0300 Subject: [PATCH 2/7] fix: address review of deel app (token host check, exact input, log bodies, rpc results) - DEEL_MCP_URL only receives a stored OAuth login on the API or issuer host - shorthand --input numbers stay text and are typed by the action schema - MCP replies are never written to the local log, even with --log-bodies - allOf skeletons merge properties; JSON-RPC replies without a tool result are errors - a write that fails after it was sent reports an unknown outcome; 4xx do not - search/describe results are shape-checked; unused flags are refused - tests for main.ts exit paths, the citty wiring, retry cap and declined renew Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +- scripts/doctor-hashes.json | 34 +++++---- src/commands/app.ts | 79 +++++++++++++------- src/core/app-actions.ts | 147 +++++++++++++++++++++++++++++-------- src/core/config.ts | 21 +++++- src/core/constants.ts | 7 ++ src/core/http.ts | 5 +- src/core/input.ts | 27 ++++--- src/core/io.ts | 5 +- src/core/mcp.ts | 21 ++++-- test/app-actions.test.ts | 104 +++++++++++++++++++++++++- test/app.test.ts | 70 ++++++++++++++---- test/config.test.ts | 32 +++++++- test/input.test.ts | 9 +++ test/io.test.ts | 25 +++++-- test/logging.test.ts | 9 +++ test/main.test.ts | 29 ++++++++ test/mcp.test.ts | 20 ++++- 18 files changed, 520 insertions(+), 129 deletions(-) create mode 100644 test/main.test.ts diff --git a/README.md b/README.md index 5c4f914..55aedfc 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,7 @@ deel app run --input ... --dry-run # print the call, run noth - `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. - `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. Writes are never retried; when a write gets no answer, the error says so and asks you to check with a read before running it again. +- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged). Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`) are refused rather than ignored. - Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much, and stderr has a warning. - A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). @@ -360,7 +361,7 @@ All failure detail lives in the error envelope printed to stderr — never encod Each HTTP exchange is written as NDJSON to a size-capped, rotating local log (separate from any network telemetry). **By default only metadata is logged** — command, method, URL path (query string omitted), status, request id, duration, and request headers (the `Authorization` header masked to `Bearer ***`). **Response bodies are not written by default.** -Opt in to full response bodies with `--log-bodies` per command, or `DEEL_LOG_BODIES=1` globally. When bodies are logged, keys whose names look sensitive (`token`, `password`, `email`, `iban`, `tax_id`, and similar) are masked — but a response body may still contain personal data, so enable this only when you need it. Disable logging entirely per-command with `--no-log`, or globally with `DEEL_LOG=off`. +Opt in to full response bodies with `--log-bodies` per command, or `DEEL_LOG_BODIES=1` globally. When bodies are logged, keys whose names look sensitive (`token`, `password`, `email`, `iban`, `tax_id`, and similar) are masked — but a response body may still contain personal data, so enable this only when you need it. `deel app run` never logs response bodies, since an action's output is a JSON string the masking can't look into. Disable logging entirely per-command with `--no-log`, or globally with `DEEL_LOG=off`. Location: `~/Library/Logs/deel/deel.log` (macOS), `%LOCALAPPDATA%\deel\logs` (Windows), `$XDG_STATE_HOME/deel/logs` (Linux). @@ -371,7 +372,7 @@ Location: `~/Library/Logs/deel/deel.log` (macOS), | ------------------- | ----------------------------------------------------------- | | `DEEL_TOKEN` | PAT value | | `DEEL_ENV` | Default environment (`prod` / `demo`) | -| `DEEL_MCP_URL` | MCP endpoint for `deel app` (https; default `/mcp` on the API host) | +| `DEEL_MCP_URL` | MCP endpoint for `deel app` (https; default `/mcp` on the API host). A saved login is only sent to the API host or the issuer's host; use `DEEL_TOKEN` or `--token-stdin` for another | | `DEEL_LOG` | `off` to disable local logging | | `DEEL_LOG_BODIES` | `1` to include response bodies in the local log (off by default) | | `DEEL_LOG_DIR` | Override the log directory | diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index b81142b..2645baf 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "1e16934186ca0a16a9ad3631023eed947bebf2ca4a66e12c3c2a122569996dee", "CONTRIBUTING.md": "c3d910ec4cf50a54b483fff388f1e9b226272e28fff44d047fd3293fb3a49794", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "87330aa3c061e8d99321608bc33e98ceef1c0aee7d391f71339d138fb04f6203", + "README.md": "73b7ec43c840be0725de3a9f9e1189a143d9e5387d542626bb0496deda1c8b0f", "SECURITY.md": "5759dae591c598f64383beb8570e8b7c1302e91b82d4baca019f301d31a01565", "package-lock.json": "d1712a62a91a8de27ed484df07ed2fe23fb9c0b4ffb242f7d7b6a753a8c519f5", "package.json": "82ea75b867ea139e0cb32bde07ed8ecad6713ce557fff8876ac87c7f68fde335", @@ -36,7 +36,7 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "8d0ef6ddccb68f68233b609ff4159583b30f4c15d88dbd3b7a7ec912120c18aa", "src/commands.map.ts": "f8437737b33ba7597e1dde683929fafba48ee912226895c303c5df54cc866a5e", - "src/commands/app.ts": "af8dea8471d35434537d71191102a04d41a1f45377696d25a299d3fafb082b56", + "src/commands/app.ts": "293201ac85cabdeefe214c5e5ff22e4fae03cfd1969e7b0580ae5c13eabd34e3", "src/commands/auth.ts": "9fca7b582ab961b1a492d24e31b13492eb14e8eab65eb4cf486dd7290a155dcd", "src/commands/index.ts": "c50028d436ff6812394cbe6a64562d09001eaf5080ad7af76b275a7b9058e027", "src/commands/job.ts": "0a3ac3245f3d52867a64c414e8ea87a137030d55952f4121b8199e9660bdf935", @@ -44,21 +44,22 @@ "src/commands/tokens.ts": "ae352c15ab6fcc6bd142cee7dbe5b38468d772da0309acb14bf6f3d2ff61f0ae", "src/commands/webhooks.ts": "77ba46b73e6e064bc33234bf0071a5bedd5b6f5a2d49e60a7e92da0c5678aa4d", "src/core/api-tokens.ts": "75401f0286850467a71341dcbe643d39913988c601154112dc81cb8649eba8f0", - "src/core/app-actions.ts": "51ed6d1b0eed3c06dcd1790e8d855bea24abdfcaa33a817320793701cc41e3bd", + "src/core/app-actions.ts": "fa797cc0fddcefda94115dc452b14809d33b803e3a28109a813c6b6f1abeec78", + "src/core/app-actions.ts.bak": "b7661ec8649dc0269f9678616f47bc1c4abb006d5706b88b077943a2401d6b6f", "src/core/auth.ts": "ca9f32e3c7167f572b39eb363925760f3e7d87241f978e2068c7e527940ef920", - "src/core/config.ts": "3a9ae869e0c2710a33441a5c67054d88203a0f403448a17327cd55716f6fd6ac", - "src/core/constants.ts": "f81f2a9b8c22f9f7deba3be00e88433440716f1304f3c485c79c7fd5cb3386ab", + "src/core/config.ts": "42e062892e5dad852dac98cbe6375e04ee452c44c065fc350955348be3bb6408", + "src/core/constants.ts": "133ba728bdeb3448bcbdacc49d22c725cb436beda80d8b2c5ccdf8b36678aa89", "src/core/context.ts": "cd446ae728060675f03db31cc767f469df1a01b4bba7843f3d6255b9bd5d996d", "src/core/errors.ts": "26d099836c3d67bbde90d28143485acc7f679129e3905e5bed996e9720dea333", "src/core/executor.ts": "4ef86601ae12ea70721f3d6770b9fe3064b692e220d39c6685695971e885a4b5", - "src/core/http.ts": "4926b0be50c59ca0995c160b790ed5243b360926bbd163d3d04352475ce9a262", + "src/core/http.ts": "e19064b7eb900c1889ed1bc926c000ef84beca7772daf85bd13ac84914619895", "src/core/idempotency.ts": "ec9f2af6d12cb739aa53ee17bdbc932fc07e6c5087011718cf8d81a4d08fa04b", - "src/core/input.ts": "4ba032c97dca34ebc1a3ab159d7d1289fa86c7443ec6c4e456d92bf9376c49cc", - "src/core/io.ts": "62bb99bce19c926533d41dd66a08f4735d578d17ddcce4a55f6dcf8507444fc4", + "src/core/input.ts": "d6c8fc512344d69fde530c7888d4af3447cb583134224e3940f16068ad6105c2", + "src/core/io.ts": "f0321095193d41d1c95282ddf36297e0fb38b6fe46ed015058a4b9491aea71dd", "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "d660e82ee1700b8a9926c83174268b1b4fc650a6ae6848dbf83f63f9bc15d9bc", - "src/core/mcp.ts": "29d95f990bf20a3ae17522a9d4c1115d05732e5a0e7f50feaee9680d845459ad", + "src/core/mcp.ts": "ff253e702e551ba36bd43d9c7e46dd907d6868a892a093f0f649d0dc5d60b360", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", "src/core/output.ts": "d1fce35d4d75563ddb7544eca9752d82dc6d2b08c07ecdf60f6a8268083cae82", @@ -69,8 +70,8 @@ "src/manifest.generated.ts": "884b86be368ceef6be7f8010464abc42b8d0375d710c7004adb5158f264a82b1", "src/types.ts": "0ed148b9bf21c59f455e8d5a79a9bf7d637d1b51003903b02d4c976bd8a66f2d", "src/version.ts": "4428bcfed17f7d5e084e9b3faf40d85ae44fe71cc3a81770ab348774c3dc0d68", - "test/app-actions.test.ts": "26f40964c7be506348f812027cb60cb59fc735d34a19c33dbad9e475d2ef54a5", - "test/app.test.ts": "eb23b2a6edf1bef92af664508d37d36eea6306da8097bf0b4be3c35285558b99", + "test/app-actions.test.ts": "056f18b0f40c6c8a499ac6e17e1905eec58e8a2a0daea1d84e30fe4e5c23bdc7", + "test/app.test.ts": "7cf573c6075addc0ba076ee4cfd6332650337f0dff9fbb3a0f27cc0deecaf6f4", "test/auth-command.test.ts": "6efb94a0c3754bc0057ee62249df6c57b558ad82a0a6919d2f5ed695c4769839", "test/auth.test.ts": "f309ecfbdeaa8bcb6ec179410f29efe4923e663485bb1b35d0cec4096313aed4", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", @@ -79,20 +80,21 @@ "test/check-pr.test.ts": "b918630bbe74071bebe1348b75fa42ec1f7924e6421f869cb560653f6c5ea53c", "test/check-version.test.ts": "68a7615fd46a9212f6c1e1901f562feb384c75a1302228b7bf752eab1a96927a", "test/cli.test.ts": "9a3595bb6274d952b85fe92941cfa1d80dc0c0f84364c995800f4fe8ce27cde8", - "test/config.test.ts": "162329691715d017d4fb594df3f2d69d3914f5f9126edb50da789cd47cbdfbb0", + "test/config.test.ts": "7e96e13dd5de0271682c569370d97af8619e88f5b08f847641ec9bc10816e2e4", "test/errors.test.ts": "c963c864df30dd6f948f6b8dfcc0c4a0850716cfa73186bfef04c53f274ac254", "test/executor.test.ts": "cc12dbf2ce6cd673a63bed74b86fea16bda76c361080cf140416b48d406db8f5", "test/extract.test.ts": "8b6e133934ec7cb546efda1a72eadedbe89736746a30056e2099fb6221db752f", "test/http.test.ts": "91a45f8c113ac5152551a80dd0b8a6e39a99affc26514f94ffc25ccd1eedba70", "test/idempotency.test.ts": "82ff10c19c9979ce27839c1fd25a503c6695e622cf630bacc5783c15951d1de3", - "test/input.test.ts": "7df58c54b10328faa956c8f4819966006ec356348c47f6508ec188529ddf498d", + "test/input.test.ts": "c9f27bf62b1231d2ce52025c85a4e4c0317812d017af881a153a1f37757ccc13", "test/install.test.ts": "f68a3ee5f08eb2172e9c12823ed46e120ea156fc2695abc77626e32dd57b826e", - "test/io.test.ts": "8214a9ec3dee20c5d9b75e9b5b3b46b2ea18b5c284d05aa8e91b0b4fcba3ab82", + "test/io.test.ts": "45de89bc93e7af19ebafaef896222e5d1aad397c4cb20faff6d683fd44d56651", "test/jobs.test.ts": "0a37b7204e5c5f9c2ffef3efa062256f6d1e061885189b2809698c3baf36bc13", "test/keychain.test.ts": "0f1fad8ae0d351ffecc051e551f0c5ad6e9be263e6ff1246589eae2dbf2f8856", - "test/logging.test.ts": "9ed74d04fef5727186b7aa40e06d30e5eeb31210f1ae6a072c7cf1330be6a69b", + "test/logging.test.ts": "64fbe3b5ad1e11c0725af41de076af2645f6ca87ddb2f5ebd40e3b339b1b686f", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", - "test/mcp.test.ts": "f6c28cb28444ca3764f4209ba8f52b3fef1f86f66c7074234c40a34676451e50", + "test/main.test.ts": "cbcd8979e1a54d4f269932492d567a3eb9154c59a76d2eb03973ff252fbbce5d", + "test/mcp.test.ts": "f85244fa79fd1d6284d380b6e46cdd78e1b2dbd28a0caaa2b1462abf718b51c5", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", "test/output.test.ts": "3b898699a31c7da7e5cac5dc973d9eff186bdcff9f0f8f10355d9e02ffebfe65", diff --git a/src/commands/app.ts b/src/commands/app.ts index 30ea41d..65958d5 100644 --- a/src/commands/app.ts +++ b/src/commands/app.ts @@ -41,7 +41,7 @@ function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { const config = configFrom(args, rawArgs); const resolved: ResolvedToken = resolveToken({ tokenStdin: Boolean(args["token-stdin"]), config, store: deps.store, transport: deps.baseTransport }); assertEligible(resolved); - const url = resolveMcpUrl(config); + const url = resolveMcpUrl(config, { oauth: resolved.source === "oauth" }); const ctx = createContext({ config, token: authFor(resolved), io: deps.io, baseTransport: deps.baseTransport }); const oauth = resolved.oauth; const client = createAppClient({ @@ -59,6 +59,20 @@ function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { return { ctx, client }; } +// Global flags the app commands honour; the rest of commonArgs (--file, --form, --idempotency-key, --debug ...) +// would be accepted and ignored, which is worse than an error for a write. +const HONOURED_FLAGS = ["json", "quiet", "fields", "jq", "raw", "env", "beta", "ca-cert", "token-stdin", "log", "log-bodies"] as const; +const appArgs = Object.fromEntries(HONOURED_FLAGS.map((flag) => [flag, commonArgs[flag]])); +const UNSUPPORTED_FLAGS = ["file", "form", "idempotency-key", "debug"]; + +function refuseUnsupported(rawArgs: string[], extra: string[]): void { + for (const flag of [...UNSUPPORTED_FLAGS, ...extra]) { + if (rawArgs.some((token) => token === `--${flag}` || token.startsWith(`--${flag}=`))) { + throw new CliError("usage.app", `--${flag} isn't supported by this 'deel app' command.`, "See 'deel app --help'."); + } + } +} + // Hidden flags citty doesn't declare, so `--flag value` would leave the value among the positionals. const HIDDEN_VALUE_FLAGS = ["base-url"]; @@ -75,6 +89,7 @@ export function positionals(args: Args, rawArgs: string[]): string[] { } export async function runSearch(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + refuseUnsupported(rawArgs, ["input", "generate-input", "dry-run"]); const query = positionals(args, rawArgs).join(" "); const limit = args.limit === undefined ? undefined : Number(args.limit); if (!query.trim()) throw new CliError("usage.app", "Usage: deel app search [--limit 1-20]"); @@ -84,6 +99,7 @@ export async function runSearch(args: Args, rawArgs: string[], deps?: AppDeps): } export async function runDescribe(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + refuseUnsupported(rawArgs, ["input", "dry-run"]); const names = positionals(args, rawArgs); if (names.length === 0) throw new CliError("usage.app", "Usage: deel app describe ... [--generate-input]"); if (args["generate-input"] && names.length > 1) throw new CliError("usage.app", "--generate-input takes one action name."); @@ -99,9 +115,10 @@ export async function runDescribe(args: Args, rawArgs: string[], deps?: AppDeps) } export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Promise { + refuseUnsupported(rawArgs, ["generate-input"]); const [name, ...extra] = positionals(args, rawArgs); if (!name || extra.length > 0) throw new CliError("usage.app", "Usage: deel app run [--input ...] [--dry-run]"); - const input = actionInput(args.input === undefined ? undefined : parseInput(String(args.input), [])); + const input = actionInput(args.input === undefined ? undefined : parseInput(String(args.input), [], { exactScalars: true })); const { ctx, client } = prepare(args, rawArgs, deps); const { action, requestId } = await getAction(client, name); if (args["dry-run"]) { @@ -118,29 +135,37 @@ export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Pro await render(ctx.io, envelope(outcome.data, meta), outputOpts(args)); } -const appArgs = { ...commonArgs }; +// `deps` are the test seams of the run functions; the real transport, keychain and IO otherwise. +export function createAppCommand(deps?: AppDeps) { + return defineCommand({ + meta: { name: "app", description: "Deel web-app actions through /mcp, as the signed-in user" }, + subCommands: { + search: defineCommand({ + meta: { name: "search", description: "Find actions the signed-in user can run: deel app search " }, + args: { query: { type: "positional", required: false, description: "What the action does" }, limit: { type: "string", description: `Maximum results, 1-${SEARCH_MAX_LIMIT} (default 10)` }, ...appArgs }, + run: (cittyCtx) => runSearch(cittyCtx.args as Args, cittyCtx.rawArgs, deps), + }), + describe: defineCommand({ + meta: { name: "describe", description: "Show an action's input schema, scopes and run tool: deel app describe ..." }, + args: { + name: { type: "positional", required: false, description: "Action name(s), as search returns them" }, + "generate-input": commonArgs["generate-input"], + ...appArgs, + }, + run: (cittyCtx) => runDescribe(cittyCtx.args as Args, cittyCtx.rawArgs, deps), + }), + run: defineCommand({ + meta: { name: "run", description: "Run an action: deel app run --input '{path_params, query, body}'" }, + args: { + name: { type: "positional", required: false, description: "Action name, as search returns it" }, + input: commonArgs.input, + "dry-run": { type: "boolean", description: "Print the tools/call that would be sent, without running it" }, + ...appArgs, + }, + run: (cittyCtx) => runRun(cittyCtx.args as Args, cittyCtx.rawArgs, deps), + }), + }, + }); +} -export const appCommand = defineCommand({ - meta: { name: "app", description: "Deel web-app actions through /mcp, as the signed-in user" }, - subCommands: { - search: defineCommand({ - meta: { name: "search", description: "Find actions the signed-in user can run: deel app search " }, - args: { query: { type: "positional", required: false, description: "What the action does" }, limit: { type: "string", description: `Maximum results, 1-${SEARCH_MAX_LIMIT} (default 10)` }, ...appArgs }, - run: (cittyCtx) => runSearch(cittyCtx.args as Args, cittyCtx.rawArgs), - }), - describe: defineCommand({ - meta: { name: "describe", description: "Show an action's input schema, scopes and run tool: deel app describe ..." }, - args: { name: { type: "positional", required: false, description: "Action name(s), as search returns them" }, ...appArgs }, - run: (cittyCtx) => runDescribe(cittyCtx.args as Args, cittyCtx.rawArgs), - }), - run: defineCommand({ - meta: { name: "run", description: "Run an action: deel app run --input '{path_params, query, body}'" }, - args: { - name: { type: "positional", required: false, description: "Action name, as search returns it" }, - "dry-run": { type: "boolean", description: "Print the tools/call that would be sent, without running it" }, - ...appArgs, - }, - run: (cittyCtx) => runRun(cittyCtx.args as Args, cittyCtx.rawArgs), - }), - }, -}); +export const appCommand = createAppCommand(); diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts index a657012..b3368c9 100644 --- a/src/core/app-actions.ts +++ b/src/core/app-actions.ts @@ -26,7 +26,7 @@ const TRUNCATION_NOTICE = /^\[Response truncated: the action returned (\d+) byte const TRANSIENT_CODES = new Set(["UPSTREAM_UNAVAILABLE", "UPSTREAM_TIMEOUT", "UPSTREAM_SERVER_ERROR"]); const NO_RESPONSE_CODES = new Set(["UPSTREAM_TIMEOUT", "UPSTREAM_UNAVAILABLE"]); -export type JsonSchema = { type?: string; properties?: Record; required?: string[]; enum?: unknown[]; [key: string]: unknown }; +export type JsonSchema = { type?: string | string[]; properties?: Record; required?: string[]; enum?: unknown[]; [key: string]: unknown }; export type ActionSummary = { name: string; title?: string; description?: string; method?: string; scopes?: string[] }; export type ActionDetail = ActionSummary & { run_with?: string; input_schema?: JsonSchema }; @@ -152,14 +152,16 @@ function mapFailure(failure: ToolFailure, context: FailureContext): CliError { case "WRONG_ACTION_KIND": return new CliError("app.wrong_kind", message); } - if (context.write && (code === undefined || NO_RESPONSE_CODES.has(code) || failure.statusCode >= 500)) { - const sentence = /[.!?]$/.test(message) ? message : `${message}.`; - return new CliError("app.outcome_unknown", `${sentence} The action may or may not have run.`, "Check the result with a read action before running it again."); - } + if (context.write && ((code !== undefined && NO_RESPONSE_CODES.has(code)) || failure.statusCode >= 500)) return outcomeUnknown(message); const suffix = code ? code.toLowerCase().replace(/[^a-z0-9_]/g, "_") : `http_${failure.statusCode}`; return new CliError(`app.${suffix}`, message); } +function outcomeUnknown(message: string): CliError { + const sentence = /[.!?]$/.test(message) ? message : `${message}.`; + return new CliError("app.outcome_unknown", `${sentence} The action may or may not have run.`, "Check the result with a read action before running it again."); +} + function failed(result: ToolResult, context: FailureContext): never { throw appError(toolFailure(result), result.requestId, context); } @@ -174,6 +176,30 @@ function jsonText(result: ToolResult): unknown { } } +function isRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +function malformed(result: ToolResult, what: string): CliError { + const error = new CliError("mcp.response", `The MCP endpoint sent ${what} in an unexpected shape.`); + error.requestId = result.requestId; + return error; +} + +function asActionSummary(value: unknown, result: ToolResult): ActionSummary { + if (!isRecord(value) || typeof value.name !== "string" || !value.name) throw malformed(result, "an action"); + return value as ActionSummary; +} + +function asActionDetail(value: unknown, result: ToolResult): ActionDetail { + const action = asActionSummary(value, result) as ActionDetail & Record; + const scopes = action.scopes as unknown; + if (scopes !== undefined && !(Array.isArray(scopes) && scopes.every((scope) => typeof scope === "string"))) throw malformed(result, "an action"); + if (action.run_with !== undefined && typeof action.run_with !== "string") throw malformed(result, "an action"); + if (action.input_schema !== undefined && !isRecord(action.input_schema)) throw malformed(result, "an action"); + return action; +} + // ---------------- operations ---------------- export async function searchActions(client: AppClient, query: string, limit?: number): Promise<{ actions: ActionSummary[]; requestId: string }> { @@ -183,50 +209,68 @@ export async function searchActions(client: AppClient, query: string, limit?: nu } const result = await client.call(APP_TOOL.search, { query, ...(limit !== undefined ? { limit } : {}) }, { retryable: true }); if (result.isError) failed(result, {}); - const payload = jsonText(result) as { actions?: unknown }; - return { actions: Array.isArray(payload.actions) ? (payload.actions as ActionSummary[]) : [], requestId: result.requestId }; + const payload = jsonText(result); + if (!isRecord(payload) || (payload.actions !== undefined && !Array.isArray(payload.actions))) throw malformed(result, "the action list"); + return { actions: (payload.actions ?? []).map((item) => asActionSummary(item, result)), requestId: result.requestId }; } export async function getAction(client: AppClient, name: string): Promise<{ action: ActionDetail; requestId: string }> { const result = await client.call(APP_TOOL.get, { name }, { retryable: true }); if (result.isError) failed(result, { action: name }); - return { action: jsonText(result) as ActionDetail, requestId: result.requestId }; + return { action: asActionDetail(jsonText(result), result), requestId: result.requestId }; } // --input for `run`: the whole {path_params, query, body} object. export function actionInput(value: unknown): ActionInput { if (value === undefined) return {}; - if (!value || typeof value !== "object" || Array.isArray(value)) { + if (!isRecord(value)) { throw new CliError("usage.app_input", "--input must be an object with path_params, query and/or body.", "Try: --input 'path_params={id=123}'"); } const extra = Object.keys(value).filter((key) => !(INPUT_KEYS as readonly string[]).includes(key)); if (extra.length > 0) { throw new CliError("usage.app_input", `Unknown --input key(s): ${extra.join(", ")}. Use path_params, query and body.`, "See the input with 'deel app describe '."); } + for (const key of ["path_params", "query"] as const) { + if (value[key] !== undefined && !isRecord(value[key])) throw new CliError("usage.app_input", `--input ${key} must be an object.`, "Try: --input 'path_params={id=123}'"); + } return value as ActionInput; } -// The CLI parses `id=123` as a number; path and query values the schema declares as strings are sent as strings, -// and numeric strings the schema declares as numbers are sent as numbers. Everything else is left to the server. -function coerceSection(values: Record | undefined, schema: JsonSchema | undefined): Record | undefined { - if (!values || typeof values !== "object" || Array.isArray(values)) return values; - const coerced: Record = {}; - for (const [key, value] of Object.entries(values)) { - const type = schema?.properties?.[key]?.type; - if (type === "string" && (typeof value === "number" || typeof value === "boolean")) coerced[key] = String(value); - else if ((type === "integer" || type === "number") && typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) coerced[key] = Number(value); - else coerced[key] = value; +const DECIMAL = /^-?\d+(\.\d+)?$/; + +// The schema's type, with OpenAPI 3.1's `["integer", "null"]` read as its first non-null entry. +function typeOf(schema: JsonSchema | undefined): string | undefined { + const type: unknown = schema?.type; + return Array.isArray(type) ? type.find((item): item is string => typeof item === "string" && item !== "null") : typeof type === "string" ? type : undefined; +} + +// `--input` shorthand arrives as text (so `00123`, `1.10` and ids past 2^53 survive); this types it by the +// action's schema: text the schema declares a number becomes one when that is exact, through objects and lists. +// With `stringify`, numbers and booleans the schema declares a string are sent as strings. What the schema doesn't +// describe is left to the server. +function coerceValue(value: unknown, schema: JsonSchema | undefined, stringify: boolean): unknown { + if (Array.isArray(value)) return value.map((item) => coerceValue(item, isRecord(schema?.items) ? (schema.items as JsonSchema) : undefined, stringify)); + if (isRecord(value)) { + const properties = isRecord(schema?.properties) ? (schema.properties as Record) : {}; + return Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, coerceValue(nested, properties[key], stringify)])); + } + const type = typeOf(schema); + if (stringify && type === "string" && (typeof value === "number" || typeof value === "boolean")) return String(value); + if ((type === "number" || type === "integer") && typeof value === "string" && DECIMAL.test(value.trim())) { + const number = Number(value); + if (type === "number" ? Number.isFinite(number) : Number.isSafeInteger(number)) return number; } - return coerced; + return value; } export function coerceInput(input: ActionInput, schema: JsonSchema | undefined): ActionInput { - const path = coerceSection(input.path_params, schema?.properties?.path_params); - const query = coerceSection(input.query, schema?.properties?.query); + const section = (name: "path_params" | "query") => (input[name] === undefined ? undefined : coerceValue(input[name], schema?.properties?.[name], true)); + const path = section("path_params"); + const query = section("query"); return { - ...(path !== undefined ? { path_params: path } : {}), - ...(query !== undefined ? { query } : {}), - ...(input.body !== undefined ? { body: input.body } : {}), + ...(path !== undefined ? { path_params: path as Record } : {}), + ...(query !== undefined ? { query: query as Record } : {}), + ...(input.body !== undefined ? { body: coerceValue(input.body, schema?.properties?.body, false) } : {}), }; } @@ -254,15 +298,36 @@ export function runOutcome(result: ToolResult): RunOutcome { return { data, requestId: result.requestId }; } +// Errors that can happen after a write request left the machine: the action may have run all the same. +const SENT_UNKNOWN = /^(network\.(timeout|error)|http\.5\d\d|mcp\.response)$/; +// A JSON-RPC internal or server error (-32603, -32000..-32099) may come after the action started; invalid params +// and an unknown method are answered before it. +const RPC_SERVER_ERROR = /\(JSON-RPC -(32603|320\d\d)\)$/; +const sentWithoutAnswer = (error: CliError) => SENT_UNKNOWN.test(error.code) || (error.code === "mcp.rpc" && RPC_SERVER_ERROR.test(error.message)); + +async function send(client: AppClient, call: RunCall): Promise { + const write = call.tool === APP_TOOL.runWrite; + try { + return await client.call(call.tool, call.arguments, { retryable: !write }); + } catch (error) { + if (write && error instanceof CliError && sentWithoutAnswer(error)) { + const unknown = outcomeUnknown(error.message); + unknown.requestId = error.requestId; + throw unknown; + } + throw error; + } +} + export async function runAction(client: AppClient, action: ActionDetail, input: ActionInput): Promise { let call = runCall(action, input); const context = (tool: string): FailureContext => ({ action: action.name, scopes: action.scopes, write: tool === APP_TOOL.runWrite }); - let result = await client.call(call.tool, call.arguments, { retryable: call.tool === APP_TOOL.runRead }); + let result = await send(client, call); if (result.isError && toolFailure(result).code === "WRONG_ACTION_KIND") { // The catalog changed between get_action and the run; the check runs before anything is called, so the // other tool is safe to try once. call = { ...call, tool: call.tool === APP_TOOL.runRead ? APP_TOOL.runWrite : APP_TOOL.runRead }; - result = await client.call(call.tool, call.arguments, { retryable: call.tool === APP_TOOL.runRead }); + result = await send(client, call); } if (result.isError) failed(result, context(call.tool)); return runOutcome(result); @@ -270,14 +335,34 @@ export async function runAction(client: AppClient, action: ActionDetail, input: // ---------------- describe --generate-input ---------------- +// One schema from `allOf`: the parent's own keywords and every part, with `properties` and `required` combined. +function mergeAllOf(schema: JsonSchema): JsonSchema { + const { allOf, ...own } = schema; + const parts = [own as JsonSchema, ...(allOf as unknown[]).filter(isRecord).map((part) => (Array.isArray(part.allOf) ? mergeAllOf(part as JsonSchema) : (part as JsonSchema)))]; + const merged: JsonSchema = {}; + for (const { properties, required, ...rest } of parts) { + Object.assign(merged, rest); + if (isRecord(properties)) { + merged.properties = { ...merged.properties }; + for (const [key, next] of Object.entries(properties as Record)) { + const previous = merged.properties[key]; + merged.properties[key] = previous && isRecord(next) ? mergeAllOf({ allOf: [previous, next] }) : next; + } + } + if (Array.isArray(required)) merged.required = [...new Set([...(merged.required ?? []), ...required])]; + } + return merged; +} + function skeletonOf(schema: JsonSchema | undefined): unknown { - if (!schema || typeof schema !== "object") return ""; + if (!isRecord(schema)) return ""; if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0]; - if (Array.isArray(schema.allOf)) return skeletonOf({ ...(schema.allOf as JsonSchema[]).reduce((merged, part) => ({ ...merged, ...part }), {}) }); - switch (schema.type) { + if (Array.isArray(schema.allOf)) return skeletonOf(mergeAllOf(schema)); + const properties = isRecord(schema.properties) ? (schema.properties as Record) : undefined; + switch (typeOf(schema) ?? (properties ? "object" : undefined)) { case "object": { const skeleton: Record = {}; - for (const [key, property] of Object.entries(schema.properties ?? {})) skeleton[key] = skeletonOf(property); + for (const [key, property] of Object.entries(properties ?? {})) skeleton[key] = skeletonOf(property); return skeleton; } case "array": diff --git a/src/core/config.ts b/src/core/config.ts index dadc2f5..c33b6dc 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -101,12 +101,25 @@ export function resolveConfig(opts: { env?: string; baseUrl?: string; beta?: boo } // The MCP endpoint the `deel app` commands call: `/mcp` on the API host, or DEEL_MCP_URL (https) for a test -// environment that serves it on its own host. The override is the user's explicit choice of server, like -// --base-url, so the login is sent there too. -export function resolveMcpUrl(config: Config): string { +// environment that serves it on its own host. A stored OAuth login only travels to the environment that issued +// it, so with one the override must sit on the API host or the issuer's host; any other host needs DEEL_TOKEN +// or --token-stdin, which are the user's explicit choice of where that token goes. +export function resolveMcpUrl(config: Config, opts: { oauth?: boolean } = {}): string { const override = httpsOverride("DEEL_MCP_URL"); if (override.error) throw new CliError("config.mcp", override.error); - return override.value ?? `${new URL(config.baseUrl).origin}/mcp`; + if (override.value === undefined) return `${new URL(config.baseUrl).origin}/mcp`; + if (opts.oauth) { + const trusted = [originOf(config.baseUrl), config.issuer ? originOf(config.issuer) : null]; + const origin = originOf(override.value); + if (!origin || !trusted.includes(origin)) { + throw new CliError( + "auth.base_url", + `DEEL_MCP_URL points at ${new URL(override.value).host}, which is not the server your saved login belongs to.`, + "Unset DEEL_MCP_URL, or use DEEL_TOKEN or --token-stdin with an OAuth access token for that server.", + ); + } + } + return override.value; } // The legacy PAT stored under the bare env name belongs to the environment's own server. Talking to another diff --git a/src/core/constants.ts b/src/core/constants.ts index f2f2e8f..9918638 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -6,6 +6,13 @@ export const HTTP_TIMEOUT_MS = 30_000; export const RETRY_MAX_ATTEMPTS = 3; export const RETRY_BASE_DELAY_MS = 200; +// --- Process exit --- +// How long a process with nothing left to write may stay up before it is forced to exit. +export const FORCED_EXIT_MS = 5_000; + +// --- MCP --- +export const MCP_ACCEPT = "application/json, text/event-stream"; + // --- Local logging --- export const LOG_MAX_BYTES_DEFAULT = 10 * 1024 * 1024; export const LOG_MAX_FILES_DEFAULT = 5; diff --git a/src/core/http.ts b/src/core/http.ts index 873bc01..f87e310 100644 --- a/src/core/http.ts +++ b/src/core/http.ts @@ -17,6 +17,8 @@ export type HttpRequest = { timeoutMs?: number; retryable?: boolean; meta?: Record; // extra fields for logging (command, idempotency key, ...) + // Never log the response body, not even under --log-bodies: it carries data under keys the log can't mask. + omitBodyFromLog?: boolean; }; export type HttpResponse = { @@ -150,6 +152,7 @@ export function withLogging(logger: Logger, clock: () => number): Middleware { const startedAt = clock(); const response = await next(request); const withBodies = bodyLoggingEnabled(); + const logBody = withBodies && !request.omitBodyFromLog; const entry: Record = { kind: "request", ...(request.meta ?? {}), @@ -160,7 +163,7 @@ export function withLogging(logger: Logger, clock: () => number): Middleware { duration_ms: clock() - startedAt, headers: redactHeaders(request.headers), }; - if (withBodies) entry.response = response.json; + if (logBody) entry.response = response.json; logger(entry); return response; }; diff --git a/src/core/input.ts b/src/core/input.ts index a6a75fc..7b15cd0 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -9,14 +9,16 @@ import { CliError } from "./errors.ts"; export type ParsedInput = unknown; -export function parseInput(raw: string, bodyProps: CliParam[]): ParsedInput { +export type ParseOpts = { exactScalars?: boolean }; + +export function parseInput(raw: string, bodyProps: CliParam[], opts: ParseOpts = {}): ParsedInput { const value = readRawValue(raw); const trimmed = value.trimStart(); if (trimmed.startsWith("{") || trimmed.startsWith("[")) { return coerceTopLevel(parseJson(value), bodyProps, false); } if (value.includes("=")) { - return coerceTopLevel(parseShorthandObject(value), bodyProps, true); + return coerceTopLevel(parseShorthandObject(value, Boolean(opts.exactScalars)), bodyProps, true); } throw new CliError( "input.unrecognized", @@ -78,7 +80,7 @@ function unescape(text: string): string { return text.replace(/\\(.)/g, "$1"); } -function parseShorthandObject(text: string): Record { +function parseShorthandObject(text: string, exact: boolean): Record { const result: Record = {}; for (const pair of splitTopLevel(text, ",")) { if (pair.trim() === "") continue; @@ -87,7 +89,7 @@ function parseShorthandObject(text: string): Record { throw new CliError("input.shorthand", `Malformed shorthand segment (expected key=value): "${pair}"`); } const key = unescape(pair.slice(0, equalsIndex).trim()); - result[key] = parseValue(pair.slice(equalsIndex + 1)); + result[key] = parseValue(pair.slice(equalsIndex + 1), exact); } return result; } @@ -107,25 +109,26 @@ function firstTopLevelEquals(text: string): number { return -1; } -function parseValue(raw: string): unknown { +function parseValue(raw: string, exact: boolean): unknown { const value = raw.trim(); - if (value.startsWith("{") && value.endsWith("}")) return parseShorthandObject(value.slice(1, -1)); + if (value.startsWith("{") && value.endsWith("}")) return parseShorthandObject(value.slice(1, -1), exact); if (value.startsWith("[") && value.endsWith("]")) { return splitTopLevel(value.slice(1, -1), ",") .filter((item) => item.trim() !== "") - .map((item) => parseValue(item)); + .map((item) => parseValue(item, exact)); } // Space-separated scalar list (e.g. tags=a b c) — spaces not inside braces/brackets. const parts = splitTopLevel(value, " ").filter((part) => part.trim() !== ""); - if (parts.length > 1) return parts.map((part) => parseScalar(unescape(part.trim()))); - return parseScalar(unescape(value)); + if (parts.length > 1) return parts.map((part) => parseScalar(unescape(part.trim()), exact)); + return parseScalar(unescape(value), exact); } -// Heuristic scalar coercion for nested values (top-level is re-coerced against the schema). -function parseScalar(text: string): unknown { +// Heuristic scalar coercion for nested values (top-level is re-coerced against the schema). With `exact`, numbers +// stay text (`00123`, `1.10`, ids past 2^53 would not survive a round trip) for the caller to type by its schema. +function parseScalar(text: string, exact: boolean): unknown { if (text === "true") return true; if (text === "false") return false; - if (text !== "" && !Number.isNaN(Number(text)) && /^-?\d+(\.\d+)?$/.test(text)) return Number(text); + if (!exact && text !== "" && !Number.isNaN(Number(text)) && /^-?\d+(\.\d+)?$/.test(text)) return Number(text); return text; } diff --git a/src/core/io.ts b/src/core/io.ts index 2b535f7..4346ddc 100644 --- a/src/core/io.ts +++ b/src/core/io.ts @@ -3,7 +3,7 @@ // which makes output capturable in tests and TTY handling consistent. import { readFileSync } from "node:fs"; -import { AGENT_ENV_SIGNALS } from "./constants.ts"; +import { AGENT_ENV_SIGNALS, FORCED_EXIT_MS } from "./constants.ts"; export type IOStreams = { out(text: string): void; @@ -30,9 +30,6 @@ export function realIO(): IOStreams { }; } -// How long a process with nothing left to write may stay up before it is forced to exit. -export const FORCED_EXIT_MS = 5_000; - export type ExitOpts = { streams?: Array>; setExitCode?: (code: number) => void; diff --git a/src/core/mcp.ts b/src/core/mcp.ts index 9801324..00b901d 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -3,11 +3,9 @@ // and a JSON text payload; this module returns it as data and leaves its meaning to the caller. import { CliError } from "./errors.ts"; -import { HEADER } from "./constants.ts"; +import { HEADER, MCP_ACCEPT } from "./constants.ts"; import type { Transport } from "./http.ts"; -export const MCP_ACCEPT = "application/json, text/event-stream"; - export type ToolResult = { isError: boolean; texts: string[]; // the text items of `content`, in order @@ -53,8 +51,8 @@ export function parseRpcBody(text: string, contentType: string | undefined, id: return messages.find((message) => message.id === id) ?? null; } try { - const message = JSON.parse(text) as RpcMessage; - return message && typeof message === "object" ? message : null; + const message: unknown = JSON.parse(text); + return message && typeof message === "object" && !Array.isArray(message) ? (message as RpcMessage) : null; } catch { return null; } @@ -77,6 +75,8 @@ export async function callTool(opts: CallToolOpts): Promise { }, body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name: opts.name, arguments: opts.args } }), retryable: opts.retryable, + // The reply carries the action's output as a JSON string, so the log's key masking can't see into it. + omitBodyFromLog: true, meta: { command: opts.command ?? "mcp", tool: opts.name }, }); @@ -101,8 +101,15 @@ export async function callTool(opts: CallToolOpts): Promise { throw withRequestId(new CliError("mcp.rpc", `${text} (JSON-RPC ${String(message.error.code ?? "error")})`), opts.requestId); } - const result = (message.result ?? {}) as { isError?: unknown; content?: unknown }; - const content = Array.isArray(result.content) ? result.content : []; + // A gateway's own 200 (`{}`, a plain message) is not a tool result, and must not read as an empty success. + if (!message.result || typeof message.result !== "object" || Array.isArray(message.result)) { + throw withRequestId(new CliError("mcp.response", "The MCP endpoint sent a response without a tool result."), opts.requestId); + } + const result = message.result as { isError?: unknown; content?: unknown }; + if (!Array.isArray(result.content)) { + throw withRequestId(new CliError("mcp.response", "The MCP endpoint sent a tool result without content."), opts.requestId); + } + const content = result.content; const texts = content .filter((item): item is { type: string; text: string } => Boolean(item) && (item as { type?: unknown }).type === "text" && typeof (item as { text?: unknown }).text === "string") .map((item) => item.text); diff --git a/test/app-actions.test.ts b/test/app-actions.test.ts index 64eaca6..768fdff 100644 --- a/test/app-actions.test.ts +++ b/test/app-actions.test.ts @@ -1,5 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { RETRY_MAX_ATTEMPTS } from "../src/core/constants.ts"; import { APP_TOOL, actionInput, @@ -16,7 +17,7 @@ import { } from "../src/core/app-actions.ts"; import type { ActionDetail, AppClient } from "../src/core/app-actions.ts"; import type { ResolvedToken } from "../src/core/auth.ts"; -import type { CliError } from "../src/core/errors.ts"; +import { CliError } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; import type { ToolResult } from "../src/core/mcp.ts"; import type { OAuthSource } from "../src/core/oauth.ts"; @@ -135,6 +136,22 @@ test("a login is renewed at most once per call, across an HTTP 401 and an isErro assert.equal(renewals, 1); }); +test("a read retries a transient failure up to the attempt cap, then returns it", async () => { + const { appClient, requests, sleeps } = client([1, 2, 3, 4].map(() => content([failure(503, "UPSTREAM_UNAVAILABLE")], true))); + assert.equal((await appClient.call(APP_TOOL.search, { query: "x" }, { retryable: true })).isError, true); + assert.equal(requests.length, RETRY_MAX_ATTEMPTS); + assert.equal(sleeps.length, RETRY_MAX_ATTEMPTS - 1); +}); + +test("a login the client can't renew leaves the AUTHENTICATION_REQUIRED failure as the answer", async () => { + let renewals = 0; + const { appClient, requests } = client([content([failure(401, "AUTHENTICATION_REQUIRED")], true)], { renew: async () => (renewals++, false) }); + const result = await appClient.call(APP_TOOL.search, { query: "x" }, { retryable: true }); + assert.equal(result.isError, true); + assert.equal(renewals, 1); + assert.equal(requests.length, 1); +}); + // ---------------- errors ---------------- test("the server's error codes map to CLI errors with a next step", () => { @@ -173,6 +190,8 @@ test("a write that got no answer has an unknown outcome", () => { assert.match(error.next ?? "", /read action/); } assert.equal(appError({ statusCode: 400, code: "UPSTREAM_CLIENT_ERROR", message: "bad" }, "r", { write: true }).code, "app.upstream_client_error"); + // A 4xx without a code is a definitive rejection, not an unknown outcome. + for (const statusCode of [400, 404, 422]) assert.equal(appError({ statusCode, message: "no" }, "r", { write: true }).code, `app.http_${statusCode}`); assert.equal(appError({ statusCode: 504, code: "UPSTREAM_TIMEOUT", message: "The action timed out" }, "r", { write: true }).message, "The action timed out. The action may or may not have run."); assert.equal(appError({ statusCode: 504, code: "UPSTREAM_TIMEOUT", message: "No answer." }, "r", { write: true }).message, "No answer. The action may or may not have run."); }); @@ -199,6 +218,13 @@ test("search maps an isError result and rejects a result that isn't JSON", async assert.deepEqual((await searchActions(scripted(ok("{}")).client, "x")).actions, []); }); +test("a result in an unexpected shape is mcp.response, with the request id", async () => { + const bad = (text: string, run: (client: AppClient) => Promise) => assert.rejects(() => run(scripted(ok(text)).client), (error: CliError) => error.code === "mcp.response" && error.requestId === "req", text); + for (const text of ["[]", "7", '{"actions":"x"}', '{"actions":[1]}', '{"actions":[{"title":"no name"}]}']) await bad(text, (c) => searchActions(c, "x")); + for (const text of ["[]", '"x"', "{}", '{"name":"a","scopes":"x"}', '{"name":"a","scopes":[1]}', '{"name":"a","run_with":1}', '{"name":"a","input_schema":[]}']) await bad(text, (c) => getAction(c, "a")); + assert.deepEqual((await searchActions(scripted(ok("{}")).client, "x")).actions, []); +}); + test("getAction returns the action and names it in errors", async () => { assert.deepEqual((await getAction(scripted(ok(JSON.stringify(LIST))).client, "list_widgets")).action, LIST); await assert.rejects(() => getAction(scripted(err(404, "ACTION_NOT_FOUND")).client, "nope"), (error: CliError) => error.code === "app.action_not_found" && /"nope"/.test(error.message)); @@ -210,6 +236,7 @@ test("--input must be an object of path_params, query and body", () => { assert.deepEqual(actionInput(undefined), {}); assert.deepEqual(actionInput({ path_params: { a: 1 }, body: [] }), { path_params: { a: 1 }, body: [] }); for (const bad of ["x", [1], null]) assert.throws(() => actionInput(bad), (error: CliError) => error.code === "usage.app_input"); + for (const bad of [{ path_params: "x" }, { query: [1] }, { path_params: null }]) assert.throws(() => actionInput(bad), (error: CliError) => error.code === "usage.app_input" && /must be an object/.test(error.message)); assert.throws(() => actionInput({ widget_id: 1 }), (error: CliError) => error.code === "usage.app_input" && /widget_id/.test(error.message)); }); @@ -220,6 +247,33 @@ test("path and query values follow the schema's string or number types; the body assert.deepEqual(coerceInput({}, undefined), {}); }); +test("shorthand text is typed by the schema through the body, objects and lists; JSON values are left as they are", () => { + const schema: ActionDetail["input_schema"] = { + type: "object", + properties: { + path_params: { type: "object", properties: { version: { type: "string" } } }, + body: { type: "object", properties: { price: { type: "number" }, qty: { type: "integer" }, ids: { type: "array", items: { type: "integer" } }, nested: { type: "object", properties: { rate: { type: ["number", "null"] } } }, note: { type: "string" } } }, + }, + }; + assert.deepEqual( + coerceInput({ path_params: { version: "1.10" }, body: { price: "1.50", qty: "3", ids: ["1", "2"], nested: { rate: "0.5" }, note: "007", other: "9" } }, schema), + { path_params: { version: "1.10" }, body: { price: 1.5, qty: 3, ids: [1, 2], nested: { rate: 0.5 }, note: "007", other: "9" } }, + ); + assert.deepEqual(coerceInput({ body: { qty: 3, note: 5 } }, schema), { body: { qty: 3, note: 5 } }); +}); + +test("a number-typed field only takes decimal text: hex and exponent forms stay text", () => { + const schema: ActionDetail["input_schema"] = { type: "object", properties: { query: { type: "object", properties: { a: { type: "integer" }, b: { type: "number" } } } } }; + assert.deepEqual(coerceInput({ query: { a: "0x10", b: "1e3" } }, schema), { query: { a: "0x10", b: "1e3" } }); +}); + +test("ids a number can't hold stay text, and integers only coerce when exact", () => { + assert.deepEqual(coerceInput({ path_params: { code: "00123" }, query: { id: "12345678901234567890", n: "007", ratio: "1.50" } }, { type: "object", properties: { path_params: { type: "object", properties: { code: { type: "string" } } }, query: { type: "object", properties: { id: { type: "integer" }, n: { type: "integer" }, ratio: { type: "number" } } } } }), { + path_params: { code: "00123" }, + query: { id: "12345678901234567890", n: 7, ratio: 1.5 }, + }); +}); + test("run uses the tool get_action names in run_with, and a write when it names none", () => { assert.equal(runCall(LIST, {}).tool, APP_TOOL.runRead); assert.equal(runCall(APPROVE, {}).tool, APP_TOOL.runWrite); @@ -248,6 +302,28 @@ test("a failed run carries the action's scopes into the next step", async () => await assert.rejects(() => runAction(scripted(err(504, "UPSTREAM_TIMEOUT")).client, APPROVE, {}), (error: CliError) => error.code === "app.outcome_unknown"); }); +test("a write that fails after it was sent has an unknown outcome; a read, and a failure before it ran, keep their own error", async () => { + const failing = (error: CliError): AppClient => ({ call: async () => { throw error; } }); + for (const code of ["network.timeout", "network.error", "http.502", "http.504", "mcp.response"]) { + const sent = new CliError(code, "Connection reset"); + sent.requestId = "r9"; + await assert.rejects(() => runAction(failing(sent), APPROVE, {}), (error: CliError) => error.code === "app.outcome_unknown" && error.requestId === "r9" && /may or may not have run/.test(error.message), code); + await assert.rejects(() => runAction(failing(sent), LIST, {}), (error: CliError) => error.code === code, code); + } + const rpc = (code: number) => new CliError("mcp.rpc", `boom (JSON-RPC ${code})`); + for (const code of [-32603, -32000, -32099]) await assert.rejects(() => runAction(failing(rpc(code)), APPROVE, {}), (error: CliError) => error.code === "app.outcome_unknown", String(code)); + for (const code of [-32602, -32601]) await assert.rejects(() => runAction(failing(rpc(code)), APPROVE, {}), (error: CliError) => error.code === "mcp.rpc", String(code)); + for (const code of ["auth.expired", "http.400", "http.429", "network.tls", "app.unavailable"]) { + await assert.rejects(() => runAction(failing(new CliError(code, "x")), APPROVE, {}), (error: CliError) => error.code === code, code); + } +}); + +test("the retry with the other tool is also checked for an unknown outcome", async () => { + let calls = 0; + const flaky: AppClient = { call: async () => (++calls === 1 ? err(400, "WRONG_ACTION_KIND") : Promise.reject(new CliError("network.timeout", "timed out"))) }; + await assert.rejects(() => runAction(flaky, LIST, {}), (error: CliError) => error.code === "app.outcome_unknown"); +}); + test("a run returns the body as JSON when it parses, as text otherwise", () => { assert.deepEqual(runOutcome(ok('{"id":"w1"}')), { data: { id: "w1" }, requestId: "req" }); assert.deepEqual(runOutcome(ok("plain text")), { data: "plain text", requestId: "req" }); @@ -272,3 +348,29 @@ test("the input skeleton follows the schema", () => { const combined: ActionDetail = { name: "x", input_schema: { type: "object", properties: { path_params: { type: "object", properties: { id: { allOf: [{ type: "string" }, { pattern: "x" }] }, tags: { type: "array" }, n: { type: "number" } } } } } }; assert.deepEqual(inputSkeleton(combined), { path_params: { id: "", tags: [], n: 0 } }); }); + +test("allOf parts are merged, with the parent's own keywords, not replaced by the last part", () => { + const schema: ActionDetail["input_schema"] = { + type: "object", + properties: { + body: { + type: "object", + properties: { own: { type: "boolean" } }, + allOf: [ + { type: "object", properties: { a: { type: "string" } }, required: ["a"] }, + { properties: { b: { type: "integer" } }, required: ["b"] }, + { allOf: [{ properties: { c: { enum: ["x", "y"] } } }] }, + ], + }, + }, + }; + assert.deepEqual(inputSkeleton({ name: "x", input_schema: schema }), { body: { own: false, a: "", b: 0, c: "x" } }); + assert.deepEqual(inputSkeleton({ name: "x", input_schema: { allOf: [{ properties: { a: { type: "string" } } }, { properties: { b: { type: "string" } } }] } }), { a: "", b: "" }); + assert.deepEqual(inputSkeleton({ name: "x", input_schema: { type: "object", properties: "oops" as never } }), {}); + // The same property in two parts is merged too, and a nullable type list reads as its non-null type. + assert.deepEqual( + inputSkeleton({ name: "x", input_schema: { allOf: [{ properties: { a: { type: "object", properties: { x: { type: "string" } } } } }, { properties: { a: { properties: { y: { type: "integer" } } } } }] } }), + { a: { x: "", y: 0 } }, + ); + assert.deepEqual(inputSkeleton({ name: "x", input_schema: { type: ["object", "null"], properties: { n: { type: ["null", "integer"] } } } }), { n: 0 }); +}); diff --git a/test/app.test.ts b/test/app.test.ts index cbf4166..58866fc 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -1,11 +1,11 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import type { TestContext } from "node:test"; -import { positionals, runDescribe, runRun, runSearch } from "../src/commands/app.ts"; +import { runCommand } from "citty"; +import { createAppCommand, positionals, runDescribe, runRun, runSearch } from "../src/commands/app.ts"; import type { AppDeps } from "../src/commands/app.ts"; import { staticCommands } from "../src/commands/index.ts"; import { RESERVED_COMMANDS } from "../src/core/constants.ts"; -import { resolveConfig, resolveMcpUrl } from "../src/core/config.ts"; import type { CliError } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; import type { IOStreams } from "../src/core/io.ts"; @@ -92,16 +92,6 @@ test("app is a static command and a reserved name", () => { assert.ok(RESERVED_COMMANDS.has("app")); }); -test("the MCP URL is /mcp on the API host, or DEEL_MCP_URL", (t) => { - isolated(t); - assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), MCP); - assert.equal(resolveMcpUrl(resolveConfig({ env: "demo" })), "https://api-staging.letsdeel.com/mcp"); - process.env.DEEL_MCP_URL = "https://mcp.example.test/mcp/"; - assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), "https://mcp.example.test/mcp"); - process.env.DEEL_MCP_URL = "http://mcp.example.test/mcp"; - assert.throws(() => resolveMcpUrl(resolveConfig({ env: "prod" })), (error: CliError) => error.code === "config.mcp"); -}); - test("search prints the actions with the request id", async (t) => { isolated(t); const io = captureIO(); @@ -216,11 +206,63 @@ test("an HTTP 401 renews the stored login and retries with the new token", async assert.deepEqual(io.json().data, { actions: [] }); }); -test("DEEL_MCP_URL points the commands at another /mcp", async (t) => { - isolated(t, { DEEL_MCP_URL: "https://mcp.example.test/mcp" }); +test("DEEL_MCP_URL points a DEEL_TOKEN at another /mcp", async (t) => { + isolated(t, { DEEL_MCP_URL: "https://mcp.example.test/mcp", DEEL_TOKEN: ACCESS }); const { transport, requests } = server(() => ({ texts: ['{"actions":[]}'] })); await runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, loggedIn(), captureIO().io)); assert.equal(requests[0].url, "https://mcp.example.test/mcp"); + assert.equal(requests[0].headers.authorization, `Bearer ${ACCESS}`); +}); + +test("DEEL_MCP_URL on the API host works with the stored login", async (t) => { + isolated(t, { DEEL_MCP_URL: `${ISSUER}/alt/mcp` }); + const { transport, requests } = server(() => ({ texts: ['{"actions":[]}'] })); + await runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, loggedIn(), captureIO().io)); + assert.equal(requests[0].url, `${ISSUER}/alt/mcp`); +}); + +test("DEEL_MCP_URL on another host never receives the stored login", async (t) => { + isolated(t, { DEEL_MCP_URL: "https://attacker.example.test/mcp" }); + const { transport, requests } = server(() => assert.fail("no call expected")); + await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, [], deps(transport, loggedIn(), captureIO().io)), (error: CliError) => error.code === "auth.base_url"); + assert.equal(requests.length, 0); +}); + +test("the citty command runs search, describe and run with their words and flags", async (t) => { + isolated(t); + const actions: Record = { list_widgets: LIST }; + const { transport, tools } = server((tool, args) => ({ texts: [tool === "get_action" ? JSON.stringify(actions[String(args.name)]) : tool === "search_actions" ? '{"actions":[{"name":"list_widgets"}]}' : '{"ok":true}'] })); + const io = captureIO(); + const command = createAppCommand(deps(transport, loggedIn(), io.io)); + await runCommand(command, { rawArgs: ["search", "pending", "widgets", "--limit", "3", "--json"] }); + await runCommand(command, { rawArgs: ["describe", "list_widgets", "--json"] }); + await runCommand(command, { rawArgs: ["run", "list_widgets", "--input", "query={status=open}", "--json"] }); + assert.deepEqual(tools(), [ + { name: "search_actions", arguments: { query: "pending widgets", limit: 3 } }, + { name: "get_action", arguments: { name: "list_widgets" } }, + { name: "get_action", arguments: { name: "list_widgets" } }, + { name: "run_read_action", arguments: { name: "list_widgets", query: { status: "open" } } }, + ]); +}); + +test("flags a command would ignore are refused, before any call", async (t) => { + isolated(t); + const { transport, requests } = server(() => assert.fail("no call expected")); + const d = deps(transport, loggedIn(), captureIO().io); + const usage = (error: CliError) => error.code === "usage.app"; + await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--generate-input"], d), usage); + await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--idempotency-key=k"], d), usage); + await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--file", "a=@b"], d), usage); + await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, ["search", "x", "--input", "a=1"], d), usage); + await assert.rejects(() => runDescribe({ ...ARGS, _: ["x"] }, ["describe", "x", "--dry-run"], d), usage); + assert.equal(requests.length, 0); +}); + +test("run keeps shorthand numbers exact, typed by the action's schema", async (t) => { + isolated(t); + const { transport, tools } = server((tool) => ({ texts: [tool === "get_action" ? JSON.stringify(APPROVE) : "{}"] })); + await runRun({ ...ARGS, _: ["approve_widget"], input: "path_params={widget_id=00123}" }, ["run", "approve_widget"], deps(transport, loggedIn(), captureIO().io)); + assert.deepEqual(tools()[1], { name: "run_write_action", arguments: { name: "approve_widget", path_params: { widget_id: "00123" } } }); }); test("the value of the hidden --base-url flag is not a positional word", () => { diff --git a/test/config.test.ts b/test/config.test.ts index c8c8d8c..f2c6770 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { resolveConfig, requireIssuer, ENVIRONMENTS } from "../src/core/config.ts"; +import { resolveConfig, resolveMcpUrl, requireIssuer, ENVIRONMENTS } from "../src/core/config.ts"; import { configFrom } from "../src/commands/shared.ts"; import type { CliError } from "../src/core/errors.ts"; @@ -143,3 +143,33 @@ test("configFrom wires the --beta flag into the config", () => { assert.equal(configFrom({ beta: true }, []).beta, true); assert.equal(configFrom({}, []).beta, undefined); }); + +test("the MCP URL is /mcp on the API host, or DEEL_MCP_URL", () => { + withEnvVars({ DEEL_MCP_URL: undefined }, () => { + assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), "https://api.letsdeel.com/mcp"); + assert.equal(resolveMcpUrl(resolveConfig({ env: "demo" })), "https://api-staging.letsdeel.com/mcp"); + }); + withEnvVars({ DEEL_MCP_URL: "https://mcp.example.test/mcp/" }, () => { + assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" })), "https://mcp.example.test/mcp"); + }); + withEnvVars({ DEEL_MCP_URL: "http://mcp.example.test/mcp" }, () => { + assert.throws(() => resolveMcpUrl(resolveConfig({ env: "prod" })), (error: CliError) => error.code === "config.mcp"); + }); +}); + +test("a stored OAuth login is only sent to DEEL_MCP_URL on the API host or the issuer's host", () => { + withEnvVars({ DEEL_MCP_URL: "https://attacker.example.test/mcp", DEEL_OAUTH_ISSUER: undefined }, () => { + const config = resolveConfig({ env: "prod" }); + assert.throws( + () => resolveMcpUrl(config, { oauth: true }), + (error: CliError) => error.code === "auth.base_url" && /attacker\.example\.test/.test(error.message) && /DEEL_TOKEN/.test(error.next ?? ""), + ); + assert.equal(resolveMcpUrl(config, { oauth: false }), "https://attacker.example.test/mcp"); // DEEL_TOKEN / --token-stdin: the user's choice + }); + withEnvVars({ DEEL_MCP_URL: "https://api.letsdeel.com/other/mcp", DEEL_OAUTH_ISSUER: undefined }, () => { + assert.equal(resolveMcpUrl(resolveConfig({ env: "prod" }), { oauth: true }), "https://api.letsdeel.com/other/mcp"); + }); + withEnvVars({ DEEL_MCP_URL: "https://dev.example.test/mcp", DEEL_OAUTH_ISSUER: "https://dev.example.test" }, () => { + assert.equal(resolveMcpUrl(resolveConfig({ env: "nope", baseUrl: "https://dev.example.test/rest" }), { oauth: true }), "https://dev.example.test/mcp"); + }); +}); diff --git a/test/input.test.ts b/test/input.test.ts index 18de800..cd1c6ae 100644 --- a/test/input.test.ts +++ b/test/input.test.ts @@ -72,3 +72,12 @@ test("a JSON string \"null\" on a nullable field stays text; only shorthand maps assert.deepEqual(parseInput('{"note":"null"}', props), { note: "null" }); assert.deepEqual(parseInput("note=null", props), { note: null }); }); + +test("exact shorthand keeps every number as text, nested and in lists; booleans are still parsed", () => { + const exact = { exactScalars: true }; + assert.deepEqual(parseInput("path_params={code=00123,id=12345678901234567890},query={v=1.10,n=-0,on=true,ids=[1,2],tags=3 4}", [], exact), { + path_params: { code: "00123", id: "12345678901234567890" }, + query: { v: "1.10", n: "-0", on: true, ids: ["1", "2"], tags: ["3", "4"] }, + }); + assert.deepEqual(parseInput("a={n=5}", []), { a: { n: 5 } }); // the default is unchanged +}); diff --git a/test/io.test.ts b/test/io.test.ts index eb65877..065cf41 100644 --- a/test/io.test.ts +++ b/test/io.test.ts @@ -1,8 +1,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; +import { spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; -import { FORCED_EXIT_MS, exitAfterFlush } from "../src/core/io.ts"; +import { FORCED_EXIT_MS } from "../src/core/constants.ts"; +import { exitAfterFlush } from "../src/core/io.ts"; const IO_MODULE = fileURLToPath(new URL("../src/core/io.ts", import.meta.url)); @@ -39,11 +40,19 @@ test("exitAfterFlush with no streams schedules the forced exit at once", () => { assert.deepEqual(exits, [0]); }); -test("a large output piped to a slow reader arrives whole", () => { +test("a large output nobody is reading yet still arrives whole", { timeout: 30_000 }, async () => { const size = 300_000; // well past the 64 KB a pipe holds - const script = `import { exitAfterFlush } from ${JSON.stringify(IO_MODULE)}; process.stdout.write("x".repeat(${size})); exitAfterFlush(0);`; - const reader = `import sys, time; time.sleep(0.3); print(len(sys.stdin.read()))`; - const result = spawnSync("sh", ["-c", `"${process.execPath}" --input-type=module -e '${script}' | python3 -c '${reader}'`], { encoding: "utf8" }); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.stdout.trim(), String(size)); + // The child queues its output, then says so on stderr; only then does the parent start reading stdout. + const script = `import { exitAfterFlush } from ${JSON.stringify(IO_MODULE)}; process.stdout.write("x".repeat(${size})); process.stderr.write("queued"); exitAfterFlush(0);`; + const child = spawn(process.execPath, ["--input-type=module", "-e", script], { stdio: ["ignore", "pipe", "pipe"] }); + let received = 0; + let reading = false; + child.stderr.on("data", () => { + if (reading) return; + reading = true; + child.stdout.on("data", (chunk: Buffer) => (received += chunk.length)); + }); + const code = await new Promise((resolve) => child.on("close", resolve)); + assert.equal(code, 0); + assert.equal(received, size); }); diff --git a/test/logging.test.ts b/test/logging.test.ts index 17a425b..49da66e 100644 --- a/test/logging.test.ts +++ b/test/logging.test.ts @@ -36,6 +36,15 @@ test("withLogging includes the response body when body logging is opted in", asy setLogBodiesEnabled(false); }); +test("withLogging leaves out a body the request says carries unmaskable data, even when body logging is on", async () => { + setLogBodiesEnabled(true); + const c = captured(); + const next: Transport = async () => res({ result: { content: [{ type: "text", text: '{"email":"a@b.test"}' }] } }); + await withLogging(c.logger, () => 0)(next)(req({ omitBodyFromLog: true })); + assert.equal("response" in c.entries[0], false); + setLogBodiesEnabled(false); +}); + test("the default sink redacts sensitive keys by substring (access_token, email, iban, tax_id)", () => { const dir = mkdtempSync(join(tmpdir(), "deel-log-")); process.env.DEEL_LOG_DIR = dir; diff --git a/test/main.test.ts b/test/main.test.ts new file mode 100644 index 0000000..c7a5a70 --- /dev/null +++ b/test/main.test.ts @@ -0,0 +1,29 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { CLI_VERSION } from "../src/version.ts"; +import { tempDir } from "./stubs.ts"; + +const MAIN = fileURLToPath(new URL("../src/main.ts", import.meta.url)); + +// The real entry point in a child process, with no token, no keychain entries and no local log. +function deel(t: Parameters[0], ...args: string[]) { + const env = { PATH: process.env.PATH ?? "", HOME: tempDir(t), DEEL_LOG: "off" }; + return spawnSync(process.execPath, [MAIN, ...args], { encoding: "utf8", env, timeout: 30_000 }); +} + +test("a successful command exits 0 and prints to stdout only", (t) => { + const result = deel(t, "--version"); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), `deel ${CLI_VERSION}`); + assert.equal(result.stderr, ""); +}); + +test("a failing command exits 1 with exactly one JSON error envelope on stderr", (t) => { + const result = deel(t, "app", "search"); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + // JSON.parse of the whole stream fails if a second envelope follows the first. + assert.deepEqual(JSON.parse(result.stderr), { error: { code: "usage.app", message: "Usage: deel app search [--limit 1-20]" } }); +}); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 7c0c59a..1ae13ea 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { MCP_ACCEPT, callTool, parseRpcBody, toolFailure } from "../src/core/mcp.ts"; +import { MCP_ACCEPT } from "../src/core/constants.ts"; +import { callTool, parseRpcBody, toolFailure } from "../src/core/mcp.ts"; import type { CliError } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; @@ -86,6 +87,23 @@ test("a body that is not JSON-RPC is mcp.response", async () => { await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.response"); }); +test("a 200 reply with no tool result is mcp.response, not an empty success", async () => { + for (const body of [{}, [], { message: "Service Unavailable" }, { jsonrpc: "2.0", id: 1 }, { jsonrpc: "2.0", id: 1, result: "ok" }, { jsonrpc: "2.0", id: 1, result: [] }, { jsonrpc: "2.0", id: 1, result: {} }, { jsonrpc: "2.0", id: 1, result: { content: "x" } }]) { + const { transport } = recording(reply(200, body)); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.response" && error.requestId === "req-1", JSON.stringify(body)); + } +}); + +test("parseRpcBody rejects a JSON array", () => { + assert.equal(parseRpcBody("[]", "application/json", 1), null); +}); + +test("the request keeps the reply out of the local log", async () => { + const { transport, requests } = recording(reply(200, result(["ok"]))); + await call(transport); + assert.equal(requests[0].omitBodyFromLog, true); +}); + test("an unknown tool means app actions are off on the server", async () => { const { transport } = recording(reply(200, { jsonrpc: "2.0", id: 1, error: { code: -32602, message: "Tool search_actions not found" } })); await assert.rejects(() => call(transport), (error: CliError) => error.code === "app.unavailable"); From e2b28bfd7b976aa334fd3163dffc64bfb9d54879 Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Mon, 9 Nov 2026 20:29:15 -0300 Subject: [PATCH 3/7] fix: address the second review of deel app - keep shorthand true/false as text until the schema says boolean - a failed login refresh or an unreachable host is never an unknown outcome - search/describe return the action list as data (--fields, --quiet work) - main.ts prints one envelope via failureEnvelope(); tested directly - refuse unknown flags so a mistyped --dry-run cannot run a write - number coercion only when it reads back as written; read allOf/anyOf/oneOf - statusless tool failures and non-tool "not found" errors keep their own code - search rejects a reply without an actions list; refuse --log-bodies Co-Authored-By: Claude Sonnet 5.5 --- README.md | 8 ++-- scripts/doctor-hashes.json | 28 +++++++------- src/commands/app.ts | 48 +++++++++++++++++++----- src/core/app-actions.ts | 65 +++++++++++++++++++++++++------- src/core/errors.ts | 21 +++++++++++ src/core/http.ts | 10 ++++- src/core/input.ts | 7 ++-- src/core/mcp.ts | 8 ++-- src/main.ts | 17 ++------- test/app-actions.test.ts | 76 ++++++++++++++++++++++++++++++++++++-- test/app.test.ts | 54 +++++++++++++++++++++++++-- test/errors.test.ts | 16 +++++++- test/http.test.ts | 23 +++++++++++- test/input.test.ts | 6 +-- test/mcp.test.ts | 11 ++++-- 15 files changed, 319 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index 55aedfc..f2fd5d6 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ An invalidated token stops working at once and cannot be restored. ## Idempotency -Every mutating request (`POST`/`PUT`/`PATCH`/`DELETE`) carries an `Idempotency-Key`. By default it is a **deterministic UUIDv5** derived from a canonicalized form of the request (method + path + query + body), so re-running the identical command sends the identical key and the server can dedupe a retry. Override it with `--idempotency-key ` when you want a fresh attempt. +Every mutating request (`POST`/`PUT`/`PATCH`/`DELETE`) to the REST API carries an `Idempotency-Key` (`deel app run` is not one: it calls the MCP endpoint and sends none). By default it is a **deterministic UUIDv5** derived from a canonicalized form of the request (method + path + query + body), so re-running the identical command sends the identical key and the server can dedupe a retry. Override it with `--idempotency-key ` when you want a fresh attempt. ## Webhooks @@ -291,7 +291,7 @@ A webhook id can start with `-`, which the argument parser reads as a flag. Pass ```bash deel auth login # once; a PAT can't run web-app actions -deel app search "time off" # actions this login can run (--limit 1-20) +deel app search "time off" # actions this login can run (--limit 1-20; --quiet prints the names) deel app describe # input schema, scopes, and whether it reads or writes deel app describe --generate-input > input.json deel app run --input file://input.json # or --input 'path_params={id=123},query={status=open}' @@ -299,8 +299,8 @@ deel app run --input ... --dry-run # print the call, run noth ``` - `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. -- `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. Writes are never retried; when a write gets no answer, the error says so and asks you to check with a read before running it again. -- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged). Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`) are refused rather than ignored. +- `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. A write is never re-sent after a timeout or a server error (reads are retried); it is sent again only after a 401 once the login is renewed, which is answered before the action runs. When a write may have run without an answer, the error says so and asks you to check with a read before running it again. +- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. - Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much, and stderr has a warning. - A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index 2645baf..820360a 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "1e16934186ca0a16a9ad3631023eed947bebf2ca4a66e12c3c2a122569996dee", "CONTRIBUTING.md": "c3d910ec4cf50a54b483fff388f1e9b226272e28fff44d047fd3293fb3a49794", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "73b7ec43c840be0725de3a9f9e1189a143d9e5387d542626bb0496deda1c8b0f", + "README.md": "f00c96f6e85895bf8cc5db8e17950aa8b13e29a06260ed6e39288e7db6daac23", "SECURITY.md": "5759dae591c598f64383beb8570e8b7c1302e91b82d4baca019f301d31a01565", "package-lock.json": "d1712a62a91a8de27ed484df07ed2fe23fb9c0b4ffb242f7d7b6a753a8c519f5", "package.json": "82ea75b867ea139e0cb32bde07ed8ecad6713ce557fff8876ac87c7f68fde335", @@ -36,7 +36,7 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "8d0ef6ddccb68f68233b609ff4159583b30f4c15d88dbd3b7a7ec912120c18aa", "src/commands.map.ts": "f8437737b33ba7597e1dde683929fafba48ee912226895c303c5df54cc866a5e", - "src/commands/app.ts": "293201ac85cabdeefe214c5e5ff22e4fae03cfd1969e7b0580ae5c13eabd34e3", + "src/commands/app.ts": "fb5bf2163eeda29381f9e3c31d49f9e018c8ade0fb35eb46ab6ed1acecf17ffc", "src/commands/auth.ts": "9fca7b582ab961b1a492d24e31b13492eb14e8eab65eb4cf486dd7290a155dcd", "src/commands/index.ts": "c50028d436ff6812394cbe6a64562d09001eaf5080ad7af76b275a7b9058e027", "src/commands/job.ts": "0a3ac3245f3d52867a64c414e8ea87a137030d55952f4121b8199e9660bdf935", @@ -44,34 +44,34 @@ "src/commands/tokens.ts": "ae352c15ab6fcc6bd142cee7dbe5b38468d772da0309acb14bf6f3d2ff61f0ae", "src/commands/webhooks.ts": "77ba46b73e6e064bc33234bf0071a5bedd5b6f5a2d49e60a7e92da0c5678aa4d", "src/core/api-tokens.ts": "75401f0286850467a71341dcbe643d39913988c601154112dc81cb8649eba8f0", - "src/core/app-actions.ts": "fa797cc0fddcefda94115dc452b14809d33b803e3a28109a813c6b6f1abeec78", + "src/core/app-actions.ts": "2bf718aca45087aff5d861bb8ce557da7e07552a807e054025d66977895e6018", "src/core/app-actions.ts.bak": "b7661ec8649dc0269f9678616f47bc1c4abb006d5706b88b077943a2401d6b6f", "src/core/auth.ts": "ca9f32e3c7167f572b39eb363925760f3e7d87241f978e2068c7e527940ef920", "src/core/config.ts": "42e062892e5dad852dac98cbe6375e04ee452c44c065fc350955348be3bb6408", "src/core/constants.ts": "133ba728bdeb3448bcbdacc49d22c725cb436beda80d8b2c5ccdf8b36678aa89", "src/core/context.ts": "cd446ae728060675f03db31cc767f469df1a01b4bba7843f3d6255b9bd5d996d", - "src/core/errors.ts": "26d099836c3d67bbde90d28143485acc7f679129e3905e5bed996e9720dea333", + "src/core/errors.ts": "0726eabcf768cb247612255a62cd5a2127d32d99af9197631742b726b90ccc79", "src/core/executor.ts": "4ef86601ae12ea70721f3d6770b9fe3064b692e220d39c6685695971e885a4b5", - "src/core/http.ts": "e19064b7eb900c1889ed1bc926c000ef84beca7772daf85bd13ac84914619895", + "src/core/http.ts": "ad050c0519b6d36fb882a5f0977403fb2f4ac0f6e6c9169087953ba263282329", "src/core/idempotency.ts": "ec9f2af6d12cb739aa53ee17bdbc932fc07e6c5087011718cf8d81a4d08fa04b", - "src/core/input.ts": "d6c8fc512344d69fde530c7888d4af3447cb583134224e3940f16068ad6105c2", + "src/core/input.ts": "fa5c46d1d40d66d41e804bc12ec680c427d0191e2cb48c6dfecf8b7dbb6875c5", "src/core/io.ts": "f0321095193d41d1c95282ddf36297e0fb38b6fe46ed015058a4b9491aea71dd", "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "d660e82ee1700b8a9926c83174268b1b4fc650a6ae6848dbf83f63f9bc15d9bc", - "src/core/mcp.ts": "ff253e702e551ba36bd43d9c7e46dd907d6868a892a093f0f649d0dc5d60b360", + "src/core/mcp.ts": "2f26223dad289709671538f2f0611f7fbecfb5248ded73e7d7df30fda6979c60", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", "src/core/output.ts": "d1fce35d4d75563ddb7544eca9752d82dc6d2b08c07ecdf60f6a8268083cae82", "src/core/tls.ts": "c06f0d810e91f0a7e959f2363750871d6e5e67edcf00ac3a9a05c2ba7fce9f65", "src/core/webhooks.ts": "63e98217b287327236769abb40358631176e68ee6ec698bd3becef2528cdf187", "src/help.ts": "382c3274cc4ab76eaca5b08a817d333c9b91d44e81958c0a2ae550158ba22be6", - "src/main.ts": "d126d9fc96e1050a93956d5a134705eec2923ea57787aa0a8544edcbcaf7a01b", + "src/main.ts": "7a0354ddd1bf5c73c860e56fbbfb44893fe9fb591cb6bb8c1f6cbac18169236d", "src/manifest.generated.ts": "884b86be368ceef6be7f8010464abc42b8d0375d710c7004adb5158f264a82b1", "src/types.ts": "0ed148b9bf21c59f455e8d5a79a9bf7d637d1b51003903b02d4c976bd8a66f2d", "src/version.ts": "4428bcfed17f7d5e084e9b3faf40d85ae44fe71cc3a81770ab348774c3dc0d68", - "test/app-actions.test.ts": "056f18b0f40c6c8a499ac6e17e1905eec58e8a2a0daea1d84e30fe4e5c23bdc7", - "test/app.test.ts": "7cf573c6075addc0ba076ee4cfd6332650337f0dff9fbb3a0f27cc0deecaf6f4", + "test/app-actions.test.ts": "9ce1e7238a04bff6a164705ca47a93f45be79b616e3fc6e3a9f626d4c68da9b1", + "test/app.test.ts": "a597c74fac9e77addff4053f3ca822c6a29ea3349e322acf6edc8f7536125494", "test/auth-command.test.ts": "6efb94a0c3754bc0057ee62249df6c57b558ad82a0a6919d2f5ed695c4769839", "test/auth.test.ts": "f309ecfbdeaa8bcb6ec179410f29efe4923e663485bb1b35d0cec4096313aed4", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", @@ -81,12 +81,12 @@ "test/check-version.test.ts": "68a7615fd46a9212f6c1e1901f562feb384c75a1302228b7bf752eab1a96927a", "test/cli.test.ts": "9a3595bb6274d952b85fe92941cfa1d80dc0c0f84364c995800f4fe8ce27cde8", "test/config.test.ts": "7e96e13dd5de0271682c569370d97af8619e88f5b08f847641ec9bc10816e2e4", - "test/errors.test.ts": "c963c864df30dd6f948f6b8dfcc0c4a0850716cfa73186bfef04c53f274ac254", + "test/errors.test.ts": "f5924c7adf6147313bea226ced286340a0ab8c28a204fc1b2603a1c0ced1271b", "test/executor.test.ts": "cc12dbf2ce6cd673a63bed74b86fea16bda76c361080cf140416b48d406db8f5", "test/extract.test.ts": "8b6e133934ec7cb546efda1a72eadedbe89736746a30056e2099fb6221db752f", - "test/http.test.ts": "91a45f8c113ac5152551a80dd0b8a6e39a99affc26514f94ffc25ccd1eedba70", + "test/http.test.ts": "7118fa748801060877b7b7ceb7bddc1c4dae78e2c5c73394f0d39ee7f16015ac", "test/idempotency.test.ts": "82ff10c19c9979ce27839c1fd25a503c6695e622cf630bacc5783c15951d1de3", - "test/input.test.ts": "c9f27bf62b1231d2ce52025c85a4e4c0317812d017af881a153a1f37757ccc13", + "test/input.test.ts": "dd71fa8f2f636ec9f1410609f2e13906ac9bba3475997d70d0c5f3f525e27192", "test/install.test.ts": "f68a3ee5f08eb2172e9c12823ed46e120ea156fc2695abc77626e32dd57b826e", "test/io.test.ts": "45de89bc93e7af19ebafaef896222e5d1aad397c4cb20faff6d683fd44d56651", "test/jobs.test.ts": "0a37b7204e5c5f9c2ffef3efa062256f6d1e061885189b2809698c3baf36bc13", @@ -94,7 +94,7 @@ "test/logging.test.ts": "64fbe3b5ad1e11c0725af41de076af2645f6ca87ddb2f5ebd40e3b339b1b686f", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", "test/main.test.ts": "cbcd8979e1a54d4f269932492d567a3eb9154c59a76d2eb03973ff252fbbce5d", - "test/mcp.test.ts": "f85244fa79fd1d6284d380b6e46cdd78e1b2dbd28a0caaa2b1462abf718b51c5", + "test/mcp.test.ts": "d24bc57332e9b16e677572c848b58cbe376564471cb2a8fcd0f0a2be8eaad2d3", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", "test/output.test.ts": "3b898699a31c7da7e5cac5dc973d9eff186bdcff9f0f8f10355d9e02ffebfe65", diff --git a/src/commands/app.ts b/src/commands/app.ts index 65958d5..2633cd2 100644 --- a/src/commands/app.ts +++ b/src/commands/app.ts @@ -6,7 +6,7 @@ import { defineCommand } from "citty"; import { createContext } from "../core/context.ts"; import type { Ctx } from "../core/context.ts"; import { envelope, render } from "../core/output.ts"; -import { setLoggingEnabled, setLogBodiesEnabled } from "../core/logging.ts"; +import { setLoggingEnabled } from "../core/logging.ts"; import { resolveMcpUrl } from "../core/config.ts"; import { authFor, resolveToken } from "../core/auth.ts"; import type { ResolvedToken } from "../core/auth.ts"; @@ -19,6 +19,7 @@ import { SEARCH_MAX_LIMIT, actionInput, assertEligible, + beforeRequest, createAppClient, getAction, inputSkeleton, @@ -37,12 +38,13 @@ type Session = { ctx: Ctx; client: AppClient }; function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { setLoggingEnabled(args.log !== false); - setLogBodiesEnabled(args["log-bodies"] === true); const config = configFrom(args, rawArgs); const resolved: ResolvedToken = resolveToken({ tokenStdin: Boolean(args["token-stdin"]), config, store: deps.store, transport: deps.baseTransport }); assertEligible(resolved); const url = resolveMcpUrl(config, { oauth: resolved.source === "oauth" }); - const ctx = createContext({ config, token: authFor(resolved), io: deps.io, baseTransport: deps.baseTransport }); + // A failed login refresh must not read as "the action may have run": it fails before the request is sent. + const token = authFor(resolved); + const ctx = createContext({ config, token: typeof token === "function" ? () => beforeRequest(token) : token, io: deps.io, baseTransport: deps.baseTransport }); const oauth = resolved.oauth; const client = createAppClient({ http: ctx.http, @@ -61,9 +63,13 @@ function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { // Global flags the app commands honour; the rest of commonArgs (--file, --form, --idempotency-key, --debug ...) // would be accepted and ignored, which is worse than an error for a write. -const HONOURED_FLAGS = ["json", "quiet", "fields", "jq", "raw", "env", "beta", "ca-cert", "token-stdin", "log", "log-bodies"] as const; -const appArgs = Object.fromEntries(HONOURED_FLAGS.map((flag) => [flag, commonArgs[flag]])); -const UNSUPPORTED_FLAGS = ["file", "form", "idempotency-key", "debug"]; +const HONOURED_FLAGS = ["json", "quiet", "fields", "jq", "raw", "env", "beta", "ca-cert", "token-stdin", "log"] as const; +const FLAG_HELP: Record = { + "token-stdin": "Read the OAuth access token from stdin", + quiet: "Print ids only (the action names for search and describe)", +}; +const appArgs = Object.fromEntries(HONOURED_FLAGS.map((flag) => [flag, flag in FLAG_HELP ? { ...commonArgs[flag], description: FLAG_HELP[flag] } : commonArgs[flag]])); +const UNSUPPORTED_FLAGS = ["file", "form", "idempotency-key", "debug", "log-bodies"]; function refuseUnsupported(rawArgs: string[], extra: string[]): void { for (const flag of [...UNSUPPORTED_FLAGS, ...extra]) { @@ -73,6 +79,20 @@ function refuseUnsupported(rawArgs: string[], extra: string[]): void { } } +// citty ignores a flag it doesn't know, so a mistyped `--dryrun` would run the write. Every `--flag` must be one this +// command declares, a `--no-` form of one, or the hidden `--base-url`. +function refuseUnknownFlags(rawArgs: string[], own: string[]): void { + const known = new Set([...HONOURED_FLAGS, ...own, ...HIDDEN_VALUE_FLAGS, "help"]); + for (const token of rawArgs) { + if (token === "--") return; + if (!token.startsWith("--")) continue; + const name = token.slice(2).split("=")[0]; + if (!known.has(name) && !known.has(name.replace(/^no-/, ""))) { + throw new CliError("usage.app", `Unknown flag --${name}.`, "See 'deel app --help'. Nothing was run."); + } + } +} + // Hidden flags citty doesn't declare, so `--flag value` would leave the value among the positionals. const HIDDEN_VALUE_FLAGS = ["base-url"]; @@ -88,18 +108,27 @@ export function positionals(args: Args, rawArgs: string[]): string[] { return words; } +// The actions as the `data` list. --quiet prints their names, one per line: the shared one looks for ids. +async function renderActions(io: IOStreams, actions: Array<{ name: string }>, requestId: string, args: Args): Promise { + const opts = outputOpts(args); + if (opts.quiet && !opts.jq) io.out(actions.map((action) => action.name).join("\n") + "\n"); + else await render(io, envelope(actions, { request_id: requestId }), opts); +} + export async function runSearch(args: Args, rawArgs: string[], deps?: AppDeps): Promise { refuseUnsupported(rawArgs, ["input", "generate-input", "dry-run"]); + refuseUnknownFlags(rawArgs, ["limit"]); const query = positionals(args, rawArgs).join(" "); const limit = args.limit === undefined ? undefined : Number(args.limit); if (!query.trim()) throw new CliError("usage.app", "Usage: deel app search [--limit 1-20]"); const { ctx, client } = prepare(args, rawArgs, deps); const { actions, requestId } = await searchActions(client, query, limit); - await render(ctx.io, envelope({ actions }, { request_id: requestId }), outputOpts(args)); + await renderActions(ctx.io, actions, requestId, args); } export async function runDescribe(args: Args, rawArgs: string[], deps?: AppDeps): Promise { refuseUnsupported(rawArgs, ["input", "dry-run"]); + refuseUnknownFlags(rawArgs, ["generate-input"]); const names = positionals(args, rawArgs); if (names.length === 0) throw new CliError("usage.app", "Usage: deel app describe ... [--generate-input]"); if (args["generate-input"] && names.length > 1) throw new CliError("usage.app", "--generate-input takes one action name."); @@ -111,11 +140,12 @@ export async function runDescribe(args: Args, rawArgs: string[], deps?: AppDeps) return; } const actions = found.map((item) => item.action); - await render(ctx.io, envelope({ actions }, { request_id: found[found.length - 1].requestId }), outputOpts(args)); + await renderActions(ctx.io, actions, found[found.length - 1].requestId, args); } export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Promise { refuseUnsupported(rawArgs, ["generate-input"]); + refuseUnknownFlags(rawArgs, ["input", "dry-run"]); const [name, ...extra] = positionals(args, rawArgs); if (!name || extra.length > 0) throw new CliError("usage.app", "Usage: deel app run [--input ...] [--dry-run]"); const input = actionInput(args.input === undefined ? undefined : parseInput(String(args.input), [], { exactScalars: true })); @@ -158,7 +188,7 @@ export function createAppCommand(deps?: AppDeps) { meta: { name: "run", description: "Run an action: deel app run --input '{path_params, query, body}'" }, args: { name: { type: "positional", required: false, description: "Action name, as search returns it" }, - input: commonArgs.input, + input: { ...commonArgs.input, description: "The call's input: one object with path_params, query and body" }, "dry-run": { type: "boolean", description: "Print the tools/call that would be sent, without running it" }, ...appArgs, }, diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts index b3368c9..fb1f0e8 100644 --- a/src/core/app-actions.ts +++ b/src/core/app-actions.ts @@ -4,7 +4,7 @@ // work at all, the read or write choice from `run_with`, retries for reads only, and errors mapped to // the CLI's envelope with a next step. -import { CliError } from "./errors.ts"; +import { CliError, markNotSent, wasNotSent } from "./errors.ts"; import { accessTokenClaims } from "./auth.ts"; import type { ResolvedToken } from "./auth.ts"; import { RETRY_BASE_DELAY_MS, RETRY_MAX_ATTEMPTS } from "./constants.ts"; @@ -44,6 +44,16 @@ export type AppClientOpts = { sleep?: (ms: number) => Promise; }; +// Runs a step that happens before a request is sent (a login refresh, a token lookup), so that an error from it +// is never read as "the action may have run". +export async function beforeRequest(step: () => Promise): Promise { + try { + return await step(); + } catch (error) { + throw markNotSent(error); + } +} + function oauthRequired(message: string): CliError { return new CliError("auth.oauth_required", message, "Run 'deel auth login' (a PAT can't run web-app actions)."); } @@ -75,6 +85,7 @@ const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(r export function createAppClient(opts: AppClientOpts): AppClient { const sleep = opts.sleep ?? defaultSleep; + const renewLogin = opts.renew ? () => beforeRequest(opts.renew!) : undefined; return { async call(tool, args, { retryable }) { const attempts = retryable ? RETRY_MAX_ATTEMPTS : 1; @@ -89,17 +100,17 @@ export function createAppClient(opts: AppClientOpts): AppClient { retryable, command: `app ${tool}`, onUnauthorized: async () => { - if (renewed || !opts.renew) return false; + if (renewed || !renewLogin) return false; renewed = true; - return opts.renew(); + return renewLogin(); }, }); if (!result.isError) return result; const failure = toolFailure(result); // A token introspection rejected: answered before anything runs, so a renewed login may retry once. - if (failure.code === "AUTHENTICATION_REQUIRED" && !renewed && opts.renew) { + if (failure.code === "AUTHENTICATION_REQUIRED" && !renewed && renewLogin) { renewed = true; - if (await opts.renew()) { + if (await renewLogin()) { attempt--; continue; } @@ -152,8 +163,8 @@ function mapFailure(failure: ToolFailure, context: FailureContext): CliError { case "WRONG_ACTION_KIND": return new CliError("app.wrong_kind", message); } - if (context.write && ((code !== undefined && NO_RESPONSE_CODES.has(code)) || failure.statusCode >= 500)) return outcomeUnknown(message); - const suffix = code ? code.toLowerCase().replace(/[^a-z0-9_]/g, "_") : `http_${failure.statusCode}`; + if (context.write && ((code !== undefined && NO_RESPONSE_CODES.has(code)) || (failure.statusCode !== undefined && failure.statusCode >= 500))) return outcomeUnknown(message); + const suffix = code ? code.toLowerCase().replace(/[^a-z0-9_]/g, "_") : failure.statusCode !== undefined ? `http_${failure.statusCode}` : "tool_failed"; return new CliError(`app.${suffix}`, message); } @@ -210,8 +221,8 @@ export async function searchActions(client: AppClient, query: string, limit?: nu const result = await client.call(APP_TOOL.search, { query, ...(limit !== undefined ? { limit } : {}) }, { retryable: true }); if (result.isError) failed(result, {}); const payload = jsonText(result); - if (!isRecord(payload) || (payload.actions !== undefined && !Array.isArray(payload.actions))) throw malformed(result, "the action list"); - return { actions: (payload.actions ?? []).map((item) => asActionSummary(item, result)), requestId: result.requestId }; + if (!isRecord(payload) || !Array.isArray(payload.actions)) throw malformed(result, "the action list"); + return { actions: payload.actions.map((item) => asActionSummary(item, result)), requestId: result.requestId }; } export async function getAction(client: AppClient, name: string): Promise<{ action: ActionDetail; requestId: string }> { @@ -238,17 +249,41 @@ export function actionInput(value: unknown): ActionInput { const DECIMAL = /^-?\d+(\.\d+)?$/; +// A number that parsed back to the digits it was written with: a whole one within 2^53, a decimal of at most 15 +// significant digits (a double holds that many). Anything longer stays text, so an id never changes on the way. +function exactNumber(text: string, number: number): boolean { + if (!Number.isFinite(number)) return false; + if (!text.includes(".")) return Number.isSafeInteger(number); + return text.replace(/[-.]/g, "").replace(/^0+/, "").length <= 15; +} + +// The one schema to read a value by: `allOf` merged, and for `anyOf`/`oneOf` (an optional field is often +// `anyOf: [{type: integer}, {type: null}]`) the first member that says what it is, other than null. +function effectiveSchema(schema: JsonSchema | undefined): JsonSchema | undefined { + if (!isRecord(schema)) return schema; + if (Array.isArray(schema.allOf)) return effectiveSchema(mergeAllOf(schema)); + for (const key of ["anyOf", "oneOf"] as const) { + const options = schema[key]; + if (!Array.isArray(options)) continue; + const pick = options.filter(isRecord).find((option) => option.type !== "null" && (typeOf(option as JsonSchema) !== undefined || isRecord(option.properties))); + if (pick) return effectiveSchema({ ...(schema as JsonSchema), [key]: undefined, ...(pick as JsonSchema) }); + } + return schema; +} + // The schema's type, with OpenAPI 3.1's `["integer", "null"]` read as its first non-null entry. function typeOf(schema: JsonSchema | undefined): string | undefined { const type: unknown = schema?.type; return Array.isArray(type) ? type.find((item): item is string => typeof item === "string" && item !== "null") : typeof type === "string" ? type : undefined; } -// `--input` shorthand arrives as text (so `00123`, `1.10` and ids past 2^53 survive); this types it by the -// action's schema: text the schema declares a number becomes one when that is exact, through objects and lists. +// `--input` shorthand arrives as text (so `00123`, `1.10`, ids past 2^53 and a string field's "false" survive); this +// types it by the action's schema: text the schema declares a number becomes one when that is exact, and "true" or +// "false" a boolean, through objects and lists. // With `stringify`, numbers and booleans the schema declares a string are sent as strings. What the schema doesn't // describe is left to the server. -function coerceValue(value: unknown, schema: JsonSchema | undefined, stringify: boolean): unknown { +function coerceValue(value: unknown, declared: JsonSchema | undefined, stringify: boolean): unknown { + const schema = effectiveSchema(declared); if (Array.isArray(value)) return value.map((item) => coerceValue(item, isRecord(schema?.items) ? (schema.items as JsonSchema) : undefined, stringify)); if (isRecord(value)) { const properties = isRecord(schema?.properties) ? (schema.properties as Record) : {}; @@ -256,9 +291,10 @@ function coerceValue(value: unknown, schema: JsonSchema | undefined, stringify: } const type = typeOf(schema); if (stringify && type === "string" && (typeof value === "number" || typeof value === "boolean")) return String(value); + if (type === "boolean" && (value === "true" || value === "false")) return value === "true"; if ((type === "number" || type === "integer") && typeof value === "string" && DECIMAL.test(value.trim())) { const number = Number(value); - if (type === "number" ? Number.isFinite(number) : Number.isSafeInteger(number)) return number; + if (type === "number" ? exactNumber(value.trim(), number) : Number.isSafeInteger(number)) return number; } return value; } @@ -303,7 +339,8 @@ const SENT_UNKNOWN = /^(network\.(timeout|error)|http\.5\d\d|mcp\.response)$/; // A JSON-RPC internal or server error (-32603, -32000..-32099) may come after the action started; invalid params // and an unknown method are answered before it. const RPC_SERVER_ERROR = /\(JSON-RPC -(32603|320\d\d)\)$/; -const sentWithoutAnswer = (error: CliError) => SENT_UNKNOWN.test(error.code) || (error.code === "mcp.rpc" && RPC_SERVER_ERROR.test(error.message)); +const sentWithoutAnswer = (error: CliError) => + !wasNotSent(error) && (SENT_UNKNOWN.test(error.code) || (error.code === "mcp.rpc" && RPC_SERVER_ERROR.test(error.message))); async function send(client: AppClient, call: RunCall): Promise { const write = call.tool === APP_TOOL.runWrite; diff --git a/src/core/errors.ts b/src/core/errors.ts index bda9540..ed70136 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -22,6 +22,17 @@ export class CliError extends Error { } } +// Errors raised before a request left the machine (a failed login refresh, a name that doesn't resolve): whatever +// code they carry, the action behind the request can't have run. +const notSent = new WeakSet(); + +export function markNotSent(error: T): T { + if (error && typeof error === "object") notSent.add(error); + return error; +} + +export const wasNotSent = (error: unknown): boolean => Boolean(error) && typeof error === "object" && notSent.has(error as object); + export type ErrorEnvelope = { code: string; message: string; @@ -32,3 +43,13 @@ export type ErrorEnvelope = { export function toEnvelope(err: CliError): ErrorEnvelope { return { code: err.code, message: err.message, next: err.next, request_id: err.requestId }; } + +// What the top-level handler prints on stderr for anything `run()` rejects with: a CliError as is, a citty +// usage error (bad flag or missing argument) as `usage`, anything else as `unexpected`. +export function failureEnvelope(err: unknown): { error: Pick | ErrorEnvelope } { + if (err instanceof CliError) return { error: toEnvelope(err) }; + const failure = err as { name?: string; code?: string; message?: string } | null | undefined; + const message = failure?.message ?? String(err); + if (failure?.name === "CLIError" || failure?.code === "EARG") return { error: { code: "usage", message } }; + return { error: { code: "unexpected", message } }; +} diff --git a/src/core/http.ts b/src/core/http.ts index f87e310..9dac035 100644 --- a/src/core/http.ts +++ b/src/core/http.ts @@ -2,7 +2,7 @@ // Cross-cutting concerns (auth header, version, request-id, retry, logging) are // middlewares — the executor just builds a request and calls the composed transport. -import { CliError } from "./errors.ts"; +import { CliError, markNotSent } from "./errors.ts"; import { redactHeaders } from "./auth.ts"; import { isCertError, TLS_HINT, installCaTrust } from "./tls.ts"; import type { Logger } from "./logging.ts"; @@ -42,6 +42,9 @@ function headersToObject(headers: Headers): Record { return result; } +// `cause.code` values of a fetch that failed before any byte reached the server. +const NOT_SENT_CAUSES = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED"]); + // Base transport: one real fetch, with a timeout. No retries/headers here. export const fetchTransport: Transport = async (request) => { installCaTrust(); // trust the OS store (once) before the first request @@ -63,7 +66,10 @@ export const fetchTransport: Transport = async (request) => { const failure = error as Error; if (failure.name === "AbortError") throw new CliError("network.timeout", `Request timed out: ${request.method} ${request.url}`); if (isCertError(error)) throw new CliError("network.tls", `TLS verification failed: ${request.url}`, TLS_HINT); - throw new CliError("network.error", `Network error: ${failure.message}`); + const networkError = new CliError("network.error", `Network error: ${failure.message}`); + // The name didn't resolve or the connection was refused: nothing reached the server. + if (NOT_SENT_CAUSES.has(String((failure as { cause?: { code?: unknown } }).cause?.code))) markNotSent(networkError); + throw networkError; } finally { clearTimeout(timer); } diff --git a/src/core/input.ts b/src/core/input.ts index 7b15cd0..066ed47 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -124,10 +124,11 @@ function parseValue(raw: string, exact: boolean): unknown { } // Heuristic scalar coercion for nested values (top-level is re-coerced against the schema). With `exact`, numbers -// stay text (`00123`, `1.10`, ids past 2^53 would not survive a round trip) for the caller to type by its schema. +// and booleans stay text (`00123`, `1.10`, ids past 2^53 would not survive a round trip, and a string field may +// hold "false") for the caller to type by its schema. function parseScalar(text: string, exact: boolean): unknown { - if (text === "true") return true; - if (text === "false") return false; + if (!exact && text === "true") return true; + if (!exact && text === "false") return false; if (!exact && text !== "" && !Number.isNaN(Number(text)) && /^-?\d+(\.\d+)?$/.test(text)) return Number(text); return text; } diff --git a/src/core/mcp.ts b/src/core/mcp.ts index 00b901d..4e60fcc 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -14,7 +14,7 @@ export type ToolResult = { // The error payload the server puts in an `isError` result's first text item. export type ToolFailure = { - statusCode: number; + statusCode?: number; // absent when the server's payload carries none code?: string; message: string; details?: unknown; @@ -95,7 +95,7 @@ export async function callTool(opts: CallToolOpts): Promise { if (message.error) { const text = printable(message.error.message, "JSON-RPC error"); // An unregistered tool: the server has app actions switched off. - if (/not found|unknown tool/i.test(text)) { + if (/-32601|-32602/.test(String(message.error.code)) && /not found|unknown tool/i.test(text)) { throw withRequestId(new CliError("app.unavailable", "Web-app actions are not available on this server.", "They are rolled out per organization."), opts.requestId); } throw withRequestId(new CliError("mcp.rpc", `${text} (JSON-RPC ${String(message.error.code ?? "error")})`), opts.requestId); @@ -127,9 +127,9 @@ export function toolFailure(result: ToolResult): ToolFailure { } const errors = Array.isArray(payload.errors) ? (payload.errors as Array>) : []; const code = errors.find((error) => typeof error?.code === "string" && error.code)?.code as string | undefined; - const statusCode = typeof payload.statusCode === "number" ? payload.statusCode : 500; + const statusCode = typeof payload.statusCode === "number" ? payload.statusCode : undefined; const message = printable(payload.message ?? result.texts[0], "The tool call failed."); - return { statusCode, ...(code ? { code } : {}), message, ...(payload.details !== undefined ? { details: payload.details } : {}) }; + return { ...(statusCode !== undefined ? { statusCode } : {}), ...(code ? { code } : {}), message, ...(payload.details !== undefined ? { details: payload.details } : {}) }; } function withRequestId(error: CliError, requestId: string): CliError { diff --git a/src/main.ts b/src/main.ts index 2ba35a3..6bde052 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,7 @@ // DeelCLI entry point. Runs directly under Node 22 (type-stripping) or Bun. import { run } from "./cli.ts"; -import { CliError, EXIT, toEnvelope } from "./core/errors.ts"; +import { CliError, EXIT, failureEnvelope } from "./core/errors.ts"; import { reexecWithSystemCa } from "./core/tls.ts"; import { exitAfterFlush } from "./core/io.ts"; @@ -11,17 +11,8 @@ import { exitAfterFlush } from "./core/io.ts"; run(process.argv.slice(2)) .then((code) => exitAfterFlush(code)) .catch((err) => { - if (err instanceof CliError) { - // Bun's binary ignores setDefaultCACertificates; retry once trusting the OS store. - if (err.code === "network.tls") reexecWithSystemCa(); // exits on retry; returns if already retried - process.stderr.write(JSON.stringify({ error: toEnvelope(err) }, null, 2) + "\n"); - return exitAfterFlush(EXIT.ERROR); - } - const anyErr = err as { name?: string; code?: string; message?: string }; - if (anyErr?.name === "CLIError" || anyErr?.code === "EARG") { - process.stderr.write(JSON.stringify({ error: { code: "usage", message: anyErr.message } }, null, 2) + "\n"); - return exitAfterFlush(EXIT.ERROR); - } - process.stderr.write(JSON.stringify({ error: { code: "unexpected", message: (err as Error).message } }, null, 2) + "\n"); + // Bun's binary ignores setDefaultCACertificates; retry once trusting the OS store. + if (err instanceof CliError && err.code === "network.tls") reexecWithSystemCa(); // exits on retry; returns if already retried + process.stderr.write(JSON.stringify(failureEnvelope(err), null, 2) + "\n"); exitAfterFlush(EXIT.ERROR); }); diff --git a/test/app-actions.test.ts b/test/app-actions.test.ts index 768fdff..8c3f492 100644 --- a/test/app-actions.test.ts +++ b/test/app-actions.test.ts @@ -6,6 +6,7 @@ import { actionInput, appError, assertEligible, + beforeRequest, coerceInput, createAppClient, getAction, @@ -17,7 +18,7 @@ import { } from "../src/core/app-actions.ts"; import type { ActionDetail, AppClient } from "../src/core/app-actions.ts"; import type { ResolvedToken } from "../src/core/auth.ts"; -import { CliError } from "../src/core/errors.ts"; +import { CliError, markNotSent, wasNotSent } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; import type { ToolResult } from "../src/core/mcp.ts"; import type { OAuthSource } from "../src/core/oauth.ts"; @@ -215,14 +216,13 @@ test("search checks its arguments before calling", async () => { test("search maps an isError result and rejects a result that isn't JSON", async () => { await assert.rejects(() => searchActions(scripted(err(403, "APP_ACTIONS_NOT_ALLOWED")).client, "x"), (error: CliError) => error.code === "app.unavailable"); await assert.rejects(() => searchActions(scripted(ok("not json")).client, "x"), (error: CliError) => error.code === "mcp.response" && error.requestId === "req"); - assert.deepEqual((await searchActions(scripted(ok("{}")).client, "x")).actions, []); + assert.deepEqual((await searchActions(scripted(ok('{"actions":[]}')).client, "x")).actions, []); }); test("a result in an unexpected shape is mcp.response, with the request id", async () => { const bad = (text: string, run: (client: AppClient) => Promise) => assert.rejects(() => run(scripted(ok(text)).client), (error: CliError) => error.code === "mcp.response" && error.requestId === "req", text); - for (const text of ["[]", "7", '{"actions":"x"}', '{"actions":[1]}', '{"actions":[{"title":"no name"}]}']) await bad(text, (c) => searchActions(c, "x")); + for (const text of ["[]", "7", "{}", '{"message":"Service unavailable"}', '{"actions":"x"}', '{"actions":[1]}', '{"actions":[{"title":"no name"}]}']) await bad(text, (c) => searchActions(c, "x")); for (const text of ["[]", '"x"', "{}", '{"name":"a","scopes":"x"}', '{"name":"a","scopes":[1]}', '{"name":"a","run_with":1}', '{"name":"a","input_schema":[]}']) await bad(text, (c) => getAction(c, "a")); - assert.deepEqual((await searchActions(scripted(ok("{}")).client, "x")).actions, []); }); test("getAction returns the action and names it in errors", async () => { @@ -262,6 +262,41 @@ test("shorthand text is typed by the schema through the body, objects and lists; assert.deepEqual(coerceInput({ body: { qty: 3, note: 5 } }, schema), { body: { qty: 3, note: 5 } }); }); +test("text the schema declares boolean becomes one, and text it declares string stays text", () => { + const schema: ActionDetail["input_schema"] = { + type: "object", + properties: { + query: { type: "object", properties: { archived: { type: "boolean" }, flag: { type: ["boolean", "null"] } } }, + body: { type: "object", properties: { status: { type: "string" }, urgent: { type: "boolean" }, mixed: { type: "boolean" } } }, + }, + }; + assert.deepEqual(coerceInput({ query: { archived: "false", flag: "true" }, body: { status: "false", urgent: "true", mixed: "yes" } }, schema), { + query: { archived: false, flag: true }, + body: { status: "false", urgent: true, mixed: "yes" }, + }); +}); + +test("a number is typed only when it reads back as written; allOf, anyOf and oneOf are read through", () => { + const num = (type: string, text: string) => coerceInput({ query: { v: text } }, { type: "object", properties: { query: { type: "object", properties: { v: { type } } } } }).query?.v; + assert.equal(num("number", "9007199254740993"), "9007199254740993"); + assert.equal(num("number", "12345678901234567890"), "12345678901234567890"); + assert.equal(num("number", "0.1234567890123456"), "0.1234567890123456"); + assert.equal(num("number", "123.456"), 123.456); + assert.equal(num("number", "-0.5"), -0.5); + assert.equal(num("number", "9007199254740991"), 9007199254740991); + + const schema: ActionDetail["input_schema"] = { + type: "object", + properties: { + body: { + allOf: [{ type: "object", properties: { n: { type: "integer" } } }, { properties: { flag: { type: "boolean" } } }], + properties: { opt: { anyOf: [{ type: "null" }, { type: "integer" }] }, either: { oneOf: [{ type: "boolean" }, { type: "string" }] }, deep: { anyOf: [{ type: "object", properties: { id: { type: "integer" } } }, { type: "null" }] } }, + }, + }, + }; + assert.deepEqual(coerceInput({ body: { n: "5", flag: "true", opt: "7", either: "false", deep: { id: "3" } } }, schema), { body: { n: 5, flag: true, opt: 7, either: false, deep: { id: 3 } } }); +}); + test("a number-typed field only takes decimal text: hex and exponent forms stay text", () => { const schema: ActionDetail["input_schema"] = { type: "object", properties: { query: { type: "object", properties: { a: { type: "integer" }, b: { type: "number" } } } } }; assert.deepEqual(coerceInput({ query: { a: "0x10", b: "1e3" } }, schema), { query: { a: "0x10", b: "1e3" } }); @@ -318,6 +353,39 @@ test("a write that fails after it was sent has an unknown outcome; a read, and a } }); +test("an error raised before the request left, such as a failed login refresh, is never an unknown outcome", async () => { + const refreshFailure = new CliError("network.timeout", "The token endpoint timed out."); + const tagged = (): AppClient => ({ call: () => beforeRequest(() => Promise.reject(refreshFailure)) }); + await assert.rejects(() => runAction(tagged(), APPROVE, {}), (error: CliError) => error === refreshFailure); + // The same error without the tag, raised by the request itself, is an unknown outcome. + await assert.rejects(() => runAction({ call: async () => { throw new CliError("network.timeout", "timed out"); } }, APPROVE, {}), (error: CliError) => error.code === "app.outcome_unknown"); + assert.equal(await beforeRequest(async () => 7), 7); + await assert.rejects(() => beforeRequest(() => Promise.reject("not an Error")), (error) => error === "not an Error"); +}); + +test("the client tags a failed renewal, whether it came from a 401 or from the server's token check", async () => { + const failingRenew = async () => { + throw new CliError("network.error", "refresh failed"); + }; + for (const first of [{ status: 401, headers: {}, text: "", json: undefined } as HttpResponse, content([failure(401, "AUTHENTICATION_REQUIRED")], true)]) { + const { appClient } = client([first], { renew: failingRenew }); + await assert.rejects(() => runAction(appClient, APPROVE, {}), (error: CliError) => error.code === "network.error"); + } +}); + +test("a failure with no status is not an unknown outcome, and a refused connection is not either", async () => { + const payload = (body: object | string) => ({ isError: true, texts: [typeof body === "string" ? body : JSON.stringify(body)], requestId: "req" }) as ToolResult; + for (const body of ["Invalid arguments: name is required", { message: "Validation failed", errors: [{ code: "X" }] }]) { + await assert.rejects(() => runAction(scripted(payload(body)).client, APPROVE, {}), (error: CliError) => error.code !== "app.outcome_unknown" && error.code.startsWith("app."), String(body)); + } + assert.equal(appError({ message: "Invalid arguments" }, "r", { write: true }).code, "app.tool_failed"); + const refused = markNotSent(new CliError("network.error", "Network error: fetch failed")); + await assert.rejects(() => runAction({ call: async () => { throw refused; } }, APPROVE, {}), (error: CliError) => error === refused); + assert.equal(wasNotSent(new CliError("network.error", "x")), false); + assert.equal(wasNotSent("text"), false); + assert.equal(markNotSent(undefined), undefined); +}); + test("the retry with the other tool is also checked for an unknown outcome", async () => { let calls = 0; const flaky: AppClient = { call: async () => (++calls === 1 ? err(400, "WRONG_ACTION_KIND") : Promise.reject(new CliError("network.timeout", "timed out"))) }; diff --git a/test/app.test.ts b/test/app.test.ts index 58866fc..a1fa9a8 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -6,7 +6,7 @@ import { createAppCommand, positionals, runDescribe, runRun, runSearch } from ". import type { AppDeps } from "../src/commands/app.ts"; import { staticCommands } from "../src/commands/index.ts"; import { RESERVED_COMMANDS } from "../src/core/constants.ts"; -import type { CliError } from "../src/core/errors.ts"; +import { CliError } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; import type { IOStreams } from "../src/core/io.ts"; import type { CredentialStore } from "../src/core/keychain.ts"; @@ -99,12 +99,26 @@ test("search prints the actions with the request id", async (t) => { await runSearch({ ...ARGS, _: ["pending", "widgets"], limit: "5" }, [], deps(transport, loggedIn(), io.io)); assert.deepEqual(tools(), [{ name: "search_actions", arguments: { query: "pending widgets", limit: 5 } }]); const printed = io.json(); - assert.deepEqual(printed.data, { actions: [{ name: "list_widgets", method: "GET" }] }); + assert.deepEqual(printed.data, [{ name: "list_widgets", method: "GET" }]); assert.equal(printed.meta.request_id, requests[0].headers["x-request-id"]); assert.equal(requests[0].url, MCP); assert.equal(requests[0].headers.authorization, `Bearer ${ACCESS}`); }); +test("search and describe take --fields and --quiet like any list", async (t) => { + isolated(t); + const { transport } = server((tool, args) => ({ texts: [tool === "get_action" ? JSON.stringify({ ...LIST, name: args.name }) : JSON.stringify({ actions: [{ name: "list_widgets", title: "List widgets", method: "GET" }, { name: "approve_widget", title: "Approve", method: "POST" }] })] })); + const run = async (fn: typeof runSearch, args: Record) => { + const io = captureIO(); + await fn({ ...ARGS, ...args }, [], deps(transport, loggedIn(), io.io)); + return io; + }; + assert.deepEqual((await run(runSearch, { _: ["x"], fields: "name,title" })).json().data, [{ name: "list_widgets", title: "List widgets" }, { name: "approve_widget", title: "Approve" }]); + assert.equal((await run(runSearch, { _: ["x"], quiet: true })).out(), "list_widgets\napprove_widget\n"); + assert.equal((await run(runDescribe, { _: ["a", "b"], quiet: true })).out(), "a\nb\n"); + assert.deepEqual((await run(runDescribe, { _: ["a"], fields: "name,method" })).json().data, [{ name: "a", method: "GET" }]); +}); + test("search without words is a usage error, before any call", async (t) => { isolated(t); const { transport, requests } = server(() => assert.fail("no call expected")); @@ -125,7 +139,7 @@ test("describe prints each action, and --generate-input prints a skeleton", asyn const { transport, tools } = server((_tool, args) => ({ texts: [JSON.stringify(actions[String(args.name)])] })); const io = captureIO(); await runDescribe({ ...ARGS, _: ["list_widgets", "approve_widget"] }, [], deps(transport, loggedIn(), io.io)); - assert.deepEqual(io.json().data.actions, [LIST, APPROVE]); + assert.deepEqual(io.json().data, [LIST, APPROVE]); assert.deepEqual(tools().map((call) => call.arguments), [{ name: "list_widgets" }, { name: "approve_widget" }]); const skeleton = captureIO(); @@ -203,7 +217,21 @@ test("an HTTP 401 renews the stored login and retries with the new token", async const mcpCalls = requests.filter((request) => request.url === MCP); assert.deepEqual(mcpCalls.map((request) => request.headers.authorization), [`Bearer ${ACCESS}`, `Bearer ${RENEWED}`]); assert.equal(readOAuthEntry(store, ISSUER)?.access_token, RENEWED); - assert.deepEqual(io.json().data, { actions: [] }); + assert.deepEqual(io.json().data, []); +}); + +test("a login refresh that fails during a write is its own error, not an unknown outcome", async (t) => { + isolated(t); + const { transport, tools } = server((tool, _args, request) => (tool === "get_action" ? { texts: [JSON.stringify(APPROVE)] } : { status: 401, headers: {}, text: "", json: undefined, url: request.url })); + const refusing: Transport = async (request) => { + if (request.url === `${ISSUER}/oauth/tokens`) throw new CliError("network.timeout", "The token endpoint timed out."); + return transport(request); + }; + await assert.rejects( + () => runRun({ ...ARGS, _: ["approve_widget"], input: "path_params={widget_id=w1}" }, [], deps(refusing, loggedIn(), captureIO().io)), + (error: CliError) => error.code === "network.timeout", + ); + assert.deepEqual(tools().map((call) => call.name), ["get_action", "run_write_action"]); }); test("DEEL_MCP_URL points a DEEL_TOKEN at another /mcp", async (t) => { @@ -255,7 +283,25 @@ test("flags a command would ignore are refused, before any call", async (t) => { await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--file", "a=@b"], d), usage); await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, ["search", "x", "--input", "a=1"], d), usage); await assert.rejects(() => runDescribe({ ...ARGS, _: ["x"] }, ["describe", "x", "--dry-run"], d), usage); + // Response bodies never reach the log for these commands, so the flag that would turn them on is refused. + await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, ["search", "x", "--log-bodies"], d), (error: CliError) => error.code === "usage.app" && /--log-bodies/.test(error.message)); + assert.equal(requests.length, 0); +}); + +test("a flag the command doesn't have is refused before any call, so a mistyped --dry-run can't run the write", async (t) => { + isolated(t); + const { transport, requests } = server(() => assert.fail("no call expected")); + const d = deps(transport, loggedIn(), captureIO().io); + const unknown = (error: CliError) => error.code === "usage.app" && /Unknown flag/.test(error.message); + for (const flag of ["--dryrun", "--dry_run", "--dry", "--limit=3"]) { + await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--input", "path_params={id=1}", flag], d), unknown, flag); + } + await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, ["search", "--limt", "3", "x"], d), unknown); + await assert.rejects(() => runDescribe({ ...ARGS, _: ["x"] }, ["describe", "x", "--generate_input"], d), unknown); assert.equal(requests.length, 0); + // Declared flags, their --no- forms, --base-url and everything after `--` pass. + const { transport: ok } = server(() => ({ texts: ['{"actions":[]}'] })); + await runSearch({ ...ARGS, _: ["x", "--weird"] }, ["search", "x", "--limit", "2", "--no-log", "--base-url", "https://api.letsdeel.com/rest", "--", "--weird"], deps(ok, loggedIn(), captureIO().io)); }); test("run keeps shorthand numbers exact, typed by the action's schema", async (t) => { diff --git a/test/errors.test.ts b/test/errors.test.ts index 5a0321c..46556f2 100644 --- a/test/errors.test.ts +++ b/test/errors.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { EXIT, CliError, toEnvelope } from "../src/core/errors.ts"; +import { EXIT, CliError, failureEnvelope, toEnvelope } from "../src/core/errors.ts"; test("exit codes are binary: success and error", () => { assert.equal(EXIT.OK, 0); @@ -24,3 +24,17 @@ test("CliError carries code and optional next; detail lives in the envelope", () assert.equal(error.message, "y"); assert.equal(error.next, undefined); }); + +test("failureEnvelope keeps a CliError's detail, and names citty usage errors and anything else", () => { + const error = new CliError("auth.missing", "No API token found.", "Run 'deel auth login'"); + error.requestId = "req-2"; + assert.deepEqual(failureEnvelope(error), { error: { code: "auth.missing", message: "No API token found.", next: "Run 'deel auth login'", request_id: "req-2" } }); + + const cittyUsage = Object.assign(new Error("Missing required argument: ID"), { name: "CLIError", code: "E_MISSING_ARG" }); + assert.deepEqual(failureEnvelope(cittyUsage), { error: { code: "usage", message: "Missing required argument: ID" } }); + assert.deepEqual(failureEnvelope(Object.assign(new Error("bad"), { code: "EARG" })), { error: { code: "usage", message: "bad" } }); + + assert.deepEqual(failureEnvelope(new TypeError("boom")), { error: { code: "unexpected", message: "boom" } }); + assert.deepEqual(failureEnvelope("plain"), { error: { code: "unexpected", message: "plain" } }); + assert.deepEqual(failureEnvelope(undefined), { error: { code: "unexpected", message: "undefined" } }); +}); diff --git a/test/http.test.ts b/test/http.test.ts index d44af02..3c00e3a 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { withAuth, withVersion, withRequestId, withRetry, withBeta } from "../src/core/http.ts"; +import { fetchTransport, withAuth, withVersion, withRequestId, withRetry, withBeta } from "../src/core/http.ts"; +import { wasNotSent } from "../src/core/errors.ts"; import type { HttpRequest, HttpResponse, Transport } from "../src/core/http.ts"; const req = (over: Partial = {}): HttpRequest => ({ method: "GET", url: "https://x", headers: {}, ...over }); @@ -118,3 +119,23 @@ test("withBeta sends X-Beta: true only when enabled", async () => { await withBeta(undefined)(off.next)(req()); assert.equal(off.seen[0].headers["x-beta"], undefined); }); + +test("a fetch that never connected is marked as not sent; a reset after connecting is not", async (t) => { + const realFetch = globalThis.fetch; + t.after(() => { + globalThis.fetch = realFetch; + }); + const failWith = (cause?: { code: string }) => { + globalThis.fetch = (async () => { + throw Object.assign(new TypeError("fetch failed"), { cause }); + }) as typeof fetch; + }; + for (const code of ["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED"]) { + failWith({ code }); + await assert.rejects(() => fetchTransport(req({ method: "POST" })), (error: Error) => (error as { code?: string }).code === "network.error" && wasNotSent(error), code); + } + for (const cause of [{ code: "ECONNRESET" }, undefined]) { + failWith(cause); + await assert.rejects(() => fetchTransport(req({ method: "POST" })), (error: Error) => (error as { code?: string }).code === "network.error" && !wasNotSent(error)); + } +}); diff --git a/test/input.test.ts b/test/input.test.ts index cd1c6ae..95851f3 100644 --- a/test/input.test.ts +++ b/test/input.test.ts @@ -73,11 +73,11 @@ test("a JSON string \"null\" on a nullable field stays text; only shorthand maps assert.deepEqual(parseInput("note=null", props), { note: null }); }); -test("exact shorthand keeps every number as text, nested and in lists; booleans are still parsed", () => { +test("exact shorthand keeps every number and boolean as text, nested and in lists", () => { const exact = { exactScalars: true }; assert.deepEqual(parseInput("path_params={code=00123,id=12345678901234567890},query={v=1.10,n=-0,on=true,ids=[1,2],tags=3 4}", [], exact), { path_params: { code: "00123", id: "12345678901234567890" }, - query: { v: "1.10", n: "-0", on: true, ids: ["1", "2"], tags: ["3", "4"] }, + query: { v: "1.10", n: "-0", on: "true", ids: ["1", "2"], tags: ["3", "4"] }, }); - assert.deepEqual(parseInput("a={n=5}", []), { a: { n: 5 } }); // the default is unchanged + assert.deepEqual(parseInput("a={n=5,on=true}", []), { a: { n: 5, on: true } }); // the default is unchanged }); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 1ae13ea..e3d905c 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -109,6 +109,11 @@ test("an unknown tool means app actions are off on the server", async () => { await assert.rejects(() => call(transport), (error: CliError) => error.code === "app.unavailable"); }); +test("a server error that happens to say \"not found\" is not the unknown-tool answer", async () => { + const { transport } = recording(reply(200, { jsonrpc: "2.0", id: 1, error: { code: -32603, message: "Internal error: record not found" } })); + await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.rpc" && /-32603/.test(error.message)); +}); + test("another JSON-RPC error is mcp.rpc with a printable message", async () => { const { transport } = recording(reply(200, { jsonrpc: "2.0", id: 1, error: { code: -32603, message: "boom\u001b[31m" } })); await assert.rejects(() => call(transport), (error: CliError) => error.code === "mcp.rpc" && error.message === "boom [31m (JSON-RPC -32603)"); @@ -130,7 +135,7 @@ test("toolFailure reads the status, code, message and details of the server's er }); }); -test("toolFailure falls back to the text and a 500 for a plain-text error", () => { - assert.deepEqual(toolFailure({ isError: true, texts: ["something broke"], requestId: "r" }), { statusCode: 500, message: "something broke" }); - assert.deepEqual(toolFailure({ isError: true, texts: [], requestId: "r" }), { statusCode: 500, message: "The tool call failed." }); +test("toolFailure falls back to the text for a plain-text error and invents no status", () => { + assert.deepEqual(toolFailure({ isError: true, texts: ["something broke"], requestId: "r" }), { message: "something broke" }); + assert.deepEqual(toolFailure({ isError: true, texts: [], requestId: "r" }), { message: "The tool call failed." }); }); From 9c20d3ac04bbc61b1ba272e91b364663fdb82400 Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Mon, 9 Nov 2026 21:28:32 -0300 Subject: [PATCH 4/7] fix: close the unknown-flag and refresh gaps in deel app - refuse single-dash options (-dry-run) the way --dryrun is refused - test the token-provider refresh wrapper with a login that expires mid-run - --dry-run prints the call even with --quiet - read an SSE message that spans several data lines; ignore a reply to another call Co-Authored-By: Claude Sonnet 5.5 --- scripts/doctor-hashes.json | 8 ++++---- src/commands/app.ts | 12 +++++++----- src/core/mcp.ts | 33 +++++++++++++++++++++------------ test/app.test.ts | 31 +++++++++++++++++++++++++++---- test/mcp.test.ts | 9 +++++++++ 5 files changed, 68 insertions(+), 25 deletions(-) diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index 820360a..57bdae2 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -36,7 +36,7 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "8d0ef6ddccb68f68233b609ff4159583b30f4c15d88dbd3b7a7ec912120c18aa", "src/commands.map.ts": "f8437737b33ba7597e1dde683929fafba48ee912226895c303c5df54cc866a5e", - "src/commands/app.ts": "fb5bf2163eeda29381f9e3c31d49f9e018c8ade0fb35eb46ab6ed1acecf17ffc", + "src/commands/app.ts": "416956d755670d5e5a428a848b2b90595e5c408691e0b75d2b0eec1301ae783e", "src/commands/auth.ts": "9fca7b582ab961b1a492d24e31b13492eb14e8eab65eb4cf486dd7290a155dcd", "src/commands/index.ts": "c50028d436ff6812394cbe6a64562d09001eaf5080ad7af76b275a7b9058e027", "src/commands/job.ts": "0a3ac3245f3d52867a64c414e8ea87a137030d55952f4121b8199e9660bdf935", @@ -59,7 +59,7 @@ "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "d660e82ee1700b8a9926c83174268b1b4fc650a6ae6848dbf83f63f9bc15d9bc", - "src/core/mcp.ts": "2f26223dad289709671538f2f0611f7fbecfb5248ded73e7d7df30fda6979c60", + "src/core/mcp.ts": "f101221d2f74d1c2141d1fbf640192abbe739be47a777dcc8f9b4ff15cc97e1d", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", "src/core/output.ts": "d1fce35d4d75563ddb7544eca9752d82dc6d2b08c07ecdf60f6a8268083cae82", @@ -71,7 +71,7 @@ "src/types.ts": "0ed148b9bf21c59f455e8d5a79a9bf7d637d1b51003903b02d4c976bd8a66f2d", "src/version.ts": "4428bcfed17f7d5e084e9b3faf40d85ae44fe71cc3a81770ab348774c3dc0d68", "test/app-actions.test.ts": "9ce1e7238a04bff6a164705ca47a93f45be79b616e3fc6e3a9f626d4c68da9b1", - "test/app.test.ts": "a597c74fac9e77addff4053f3ca822c6a29ea3349e322acf6edc8f7536125494", + "test/app.test.ts": "3328017fd6ea69e5f852bf6b343cb87c7d1d885ff1e94e5c6a67f118352b0c0a", "test/auth-command.test.ts": "6efb94a0c3754bc0057ee62249df6c57b558ad82a0a6919d2f5ed695c4769839", "test/auth.test.ts": "f309ecfbdeaa8bcb6ec179410f29efe4923e663485bb1b35d0cec4096313aed4", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", @@ -94,7 +94,7 @@ "test/logging.test.ts": "64fbe3b5ad1e11c0725af41de076af2645f6ca87ddb2f5ebd40e3b339b1b686f", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", "test/main.test.ts": "cbcd8979e1a54d4f269932492d567a3eb9154c59a76d2eb03973ff252fbbce5d", - "test/mcp.test.ts": "d24bc57332e9b16e677572c848b58cbe376564471cb2a8fcd0f0a2be8eaad2d3", + "test/mcp.test.ts": "e9826f6f95942766e93fb885847f76a5d7c9c419d37e57513dc053f9061585ac", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", "test/output.test.ts": "3b898699a31c7da7e5cac5dc973d9eff186bdcff9f0f8f10355d9e02ffebfe65", diff --git a/src/commands/app.ts b/src/commands/app.ts index 2633cd2..ab50c8a 100644 --- a/src/commands/app.ts +++ b/src/commands/app.ts @@ -32,14 +32,14 @@ import { commonArgs, configFrom, outputOpts } from "./shared.ts"; import type { Args } from "./shared.ts"; // Test seams: a fake transport, keychain or IO; the real ones otherwise. -export type AppDeps = { baseTransport?: Transport; store?: CredentialStore; io?: IOStreams; sleep?: (ms: number) => Promise }; +export type AppDeps = { baseTransport?: Transport; store?: CredentialStore; io?: IOStreams; sleep?: (ms: number) => Promise; now?: () => number }; type Session = { ctx: Ctx; client: AppClient }; function prepare(args: Args, rawArgs: string[], deps: AppDeps = {}): Session { setLoggingEnabled(args.log !== false); const config = configFrom(args, rawArgs); - const resolved: ResolvedToken = resolveToken({ tokenStdin: Boolean(args["token-stdin"]), config, store: deps.store, transport: deps.baseTransport }); + const resolved: ResolvedToken = resolveToken({ tokenStdin: Boolean(args["token-stdin"]), config, store: deps.store, transport: deps.baseTransport, now: deps.now }); assertEligible(resolved); const url = resolveMcpUrl(config, { oauth: resolved.source === "oauth" }); // A failed login refresh must not read as "the action may have run": it fails before the request is sent. @@ -79,12 +79,14 @@ function refuseUnsupported(rawArgs: string[], extra: string[]): void { } } -// citty ignores a flag it doesn't know, so a mistyped `--dryrun` would run the write. Every `--flag` must be one this -// command declares, a `--no-` form of one, or the hidden `--base-url`. +// citty ignores a flag it doesn't know, so a mistyped `--dryrun` would run the write, and it reads `-dry-run` as a +// group of short options and sets nothing. Every `--flag` must be one this command declares, a `--no-` form of one, or +// the hidden `--base-url`; the only short option is `-h`, and a bare `-` or a negative number is a value. function refuseUnknownFlags(rawArgs: string[], own: string[]): void { const known = new Set([...HONOURED_FLAGS, ...own, ...HIDDEN_VALUE_FLAGS, "help"]); for (const token of rawArgs) { if (token === "--") return; + if (/^-[A-Za-z]/.test(token) && token !== "-h") throw new CliError("usage.app", `Unknown option ${token}.`, "Flags are written --like-this. Nothing was run."); if (!token.startsWith("--")) continue; const name = token.slice(2).split("=")[0]; if (!known.has(name) && !known.has(name.replace(/^no-/, ""))) { @@ -153,7 +155,7 @@ export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Pro const { action, requestId } = await getAction(client, name); if (args["dry-run"]) { const call = runCall(action, input); - await render(ctx.io, envelope({ method: "tools/call", params: { name: call.tool, arguments: call.arguments } }, { request_id: requestId, dry_run: true }), outputOpts(args)); + await render(ctx.io, envelope({ method: "tools/call", params: { name: call.tool, arguments: call.arguments } }, { request_id: requestId, dry_run: true }), { ...outputOpts(args), quiet: false }); return; } const outcome = await runAction(client, action, input); diff --git a/src/core/mcp.ts b/src/core/mcp.ts index 4e60fcc..cbfefd7 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -37,22 +37,31 @@ type RpcMessage = { jsonrpc?: string; id?: unknown; result?: unknown; error?: { // A Streamable HTTP response is either one JSON body or an SSE stream whose `data:` lines carry the messages. export function parseRpcBody(text: string, contentType: string | undefined, id: number): RpcMessage | null { if (contentType?.includes("text/event-stream")) { - const messages = text - .split(/\r?\n/) - .filter((line) => line.startsWith("data:")) - .map((line) => { - try { - return JSON.parse(line.slice("data:".length).trim()) as RpcMessage; - } catch { - return null; - } - }) - .filter((message): message is RpcMessage => message !== null); + // An event is the `data:` lines up to a blank line, joined by newlines (a long message may span several). A + // server that skips the blank lines is read line by line. + const parse = (data: string) => { + try { + return [JSON.parse(data) as RpcMessage]; + } catch { + return []; + } + }; + const messages = text.split(/\r?\n\r?\n/).flatMap((event) => { + const lines = event + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice("data:".length).replace(/^ /, "")); + const joined = parse(lines.join("\n")); + return joined.length > 0 ? joined : lines.flatMap(parse); + }); return messages.find((message) => message.id === id) ?? null; } try { const message: unknown = JSON.parse(text); - return message && typeof message === "object" && !Array.isArray(message) ? (message as RpcMessage) : null; + if (!message || typeof message !== "object" || Array.isArray(message)) return null; + // A reply to another request is not ours; one without an id is taken as ours. + const replyId = (message as RpcMessage).id; + return replyId === undefined || replyId === id ? (message as RpcMessage) : null; } catch { return null; } diff --git a/test/app.test.ts b/test/app.test.ts index a1fa9a8..8860f41 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -182,6 +182,10 @@ test("run --dry-run prints the call and runs nothing", async (t) => { const printed = io.json(); assert.deepEqual(printed.data, { method: "tools/call", params: { name: "run_write_action", arguments: { name: "approve_widget", path_params: { widget_id: "w1" } } } }); assert.equal(printed.meta.dry_run, true); + + const quiet = captureIO(); + await runRun({ ...ARGS, _: ["approve_widget"], input: '{"path_params":{"widget_id":"w1"}}', "dry-run": true, quiet: true }, [], deps(transport, loggedIn(), quiet.io)); + assert.equal(quiet.json().meta.dry_run, true); // --quiet doesn't blank the preview }); test("run checks its arguments and --input before any call", async (t) => { @@ -234,6 +238,25 @@ test("a login refresh that fails during a write is its own error, not an unknown assert.deepEqual(tools().map((call) => call.name), ["get_action", "run_write_action"]); }); +test("a login that expires between the lookup and the write fails to refresh as its own error, with no write sent", async (t) => { + isolated(t); + let clock = Date.now(); + const { transport, tools } = server((tool) => { + if (tool !== "get_action") return assert.fail("the write must not be sent"); + clock += 2 * 3600_000; // the stored token is now past its life, so the next send refreshes first + return { texts: [JSON.stringify(APPROVE)] }; + }); + const refusing: Transport = async (request) => { + if (request.url === `${ISSUER}/oauth/tokens`) throw new CliError("network.timeout", "The token endpoint timed out."); + return transport(request); + }; + await assert.rejects( + () => runRun({ ...ARGS, _: ["approve_widget"], input: "path_params={widget_id=w1}" }, [], { ...deps(refusing, loggedIn(), captureIO().io), now: () => clock }), + (error: CliError) => error.code === "network.timeout", + ); + assert.deepEqual(tools().map((call) => call.name), ["get_action"]); +}); + test("DEEL_MCP_URL points a DEEL_TOKEN at another /mcp", async (t) => { isolated(t, { DEEL_MCP_URL: "https://mcp.example.test/mcp", DEEL_TOKEN: ACCESS }); const { transport, requests } = server(() => ({ texts: ['{"actions":[]}'] })); @@ -292,16 +315,16 @@ test("a flag the command doesn't have is refused before any call, so a mistyped isolated(t); const { transport, requests } = server(() => assert.fail("no call expected")); const d = deps(transport, loggedIn(), captureIO().io); - const unknown = (error: CliError) => error.code === "usage.app" && /Unknown flag/.test(error.message); - for (const flag of ["--dryrun", "--dry_run", "--dry", "--limit=3"]) { + const unknown = (error: CliError) => error.code === "usage.app" && /Unknown (flag|option)/.test(error.message); + for (const flag of ["--dryrun", "--dry_run", "--dry", "--limit=3", "-dry-run", "-n"]) { await assert.rejects(() => runRun({ ...ARGS, _: ["approve_widget"] }, ["run", "approve_widget", "--input", "path_params={id=1}", flag], d), unknown, flag); } await assert.rejects(() => runSearch({ ...ARGS, _: ["x"] }, ["search", "--limt", "3", "x"], d), unknown); await assert.rejects(() => runDescribe({ ...ARGS, _: ["x"] }, ["describe", "x", "--generate_input"], d), unknown); assert.equal(requests.length, 0); - // Declared flags, their --no- forms, --base-url and everything after `--` pass. + // Declared flags, their --no- forms, --base-url, -h, a bare `-`, a negative number and everything after `--` pass. const { transport: ok } = server(() => ({ texts: ['{"actions":[]}'] })); - await runSearch({ ...ARGS, _: ["x", "--weird"] }, ["search", "x", "--limit", "2", "--no-log", "--base-url", "https://api.letsdeel.com/rest", "--", "--weird"], deps(ok, loggedIn(), captureIO().io)); + await runSearch({ ...ARGS, _: ["x", "--weird"] }, ["search", "x", "--limit", "2", "--no-log", "--base-url", "https://api.letsdeel.com/rest", "-h", "-", "-5", "--", "--weird", "-x"], deps(ok, loggedIn(), captureIO().io)); }); test("run keeps shorthand numbers exact, typed by the action's schema", async (t) => { diff --git a/test/mcp.test.ts b/test/mcp.test.ts index e3d905c..efbd4b5 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -45,6 +45,15 @@ test("an SSE response is read from its data lines", async () => { assert.deepEqual((await call(transport)).texts, ["ok"]); }); +test("an SSE message split over several data lines is joined, and a reply to another call is skipped", () => { + const body = JSON.stringify({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "a" }] } }, null, 1); + const multiline = body.split("\n").map((line) => `data: ${line}`).join("\n"); + assert.deepEqual(parseRpcBody(`event: message\n${multiline}\n\n`, "text/event-stream", 1)?.result, { content: [{ type: "text", text: "a" }] }); + assert.equal(parseRpcBody(JSON.stringify({ jsonrpc: "2.0", id: 2, result: {} }), "application/json", 1), null); + assert.deepEqual(parseRpcBody(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { a: 1 } }), "application/json", 1)?.result, { a: 1 }); + assert.deepEqual(parseRpcBody(JSON.stringify({ result: { a: 2 } }), "application/json", 1)?.result, { a: 2 }); +}); + test("parseRpcBody picks the SSE message with the call's id and skips bad lines", () => { const text = ["data: not json", `data: ${JSON.stringify({ jsonrpc: "2.0", id: 9, result: {} })}`, `data: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { x: 1 } })}`].join("\n"); assert.deepEqual(parseRpcBody(text, "text/event-stream", 1)?.result, { x: 1 }); From 2b31ea5c836b044dd9cdf8d290d70b741e031132 Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Mon, 9 Nov 2026 22:29:21 -0300 Subject: [PATCH 5/7] fix: refuse options written before the command words, harden SSE parsing - an option before the last command word is dropped by citty (`deel --dry-run app run` would write), so it is refused - an SSE `data: null` or a non-object reply is not a message - test --jq on search/describe output, alone and with --quiet Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- scripts/doctor-hashes.json | 12 ++++++------ src/cli.ts | 12 ++++++++++++ src/core/mcp.ts | 14 +++++++++----- test/app.test.ts | 14 ++++++++++++++ test/cli.test.ts | 16 +++++++++++++++- test/mcp.test.ts | 9 +++++++++ 7 files changed, 66 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f2fd5d6..5c22f1f 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ deel app run --input ... --dry-run # print the call, run noth - `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. - `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. A write is never re-sent after a timeout or a server error (reads are retried); it is sent again only after a 401 once the login is renewed, which is answered before the action runs. When a write may have run without an answer, the error says so and asks you to check with a read before running it again. -- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. +- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored, and so is any option written before the command words (`deel --dry-run app run ...`), which would otherwise be dropped. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. - Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much, and stderr has a warning. - A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index 57bdae2..03aceb7 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "1e16934186ca0a16a9ad3631023eed947bebf2ca4a66e12c3c2a122569996dee", "CONTRIBUTING.md": "c3d910ec4cf50a54b483fff388f1e9b226272e28fff44d047fd3293fb3a49794", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "f00c96f6e85895bf8cc5db8e17950aa8b13e29a06260ed6e39288e7db6daac23", + "README.md": "22d1dfc91c3d5a5fcccc4f4ee61ac09f6983c7c3637e55fe4d32a46ed7a60676", "SECURITY.md": "5759dae591c598f64383beb8570e8b7c1302e91b82d4baca019f301d31a01565", "package-lock.json": "d1712a62a91a8de27ed484df07ed2fe23fb9c0b4ffb242f7d7b6a753a8c519f5", "package.json": "82ea75b867ea139e0cb32bde07ed8ecad6713ce557fff8876ac87c7f68fde335", @@ -34,7 +34,7 @@ "scripts/install-rcodesign.sh": "17743410b121e43181463a5f1db8e302aa57cbf4e28d34145f8418e597362584", "scripts/pack-npm.ts": "15eda0800d1075fc58bac564d41bcebe1b950cd145fc36d2d11aee935cb7750f", "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", - "src/cli.ts": "8d0ef6ddccb68f68233b609ff4159583b30f4c15d88dbd3b7a7ec912120c18aa", + "src/cli.ts": "30540df83843525b0eecfa7ea8bf787fbc3ce176bb0c8614990aea9a5a3e86d9", "src/commands.map.ts": "f8437737b33ba7597e1dde683929fafba48ee912226895c303c5df54cc866a5e", "src/commands/app.ts": "416956d755670d5e5a428a848b2b90595e5c408691e0b75d2b0eec1301ae783e", "src/commands/auth.ts": "9fca7b582ab961b1a492d24e31b13492eb14e8eab65eb4cf486dd7290a155dcd", @@ -59,7 +59,7 @@ "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "d660e82ee1700b8a9926c83174268b1b4fc650a6ae6848dbf83f63f9bc15d9bc", - "src/core/mcp.ts": "f101221d2f74d1c2141d1fbf640192abbe739be47a777dcc8f9b4ff15cc97e1d", + "src/core/mcp.ts": "3fdf2ff2b142ba76d7fe9e3d37565a26e109a5e653086828595c413469d9dbc1", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", "src/core/output.ts": "d1fce35d4d75563ddb7544eca9752d82dc6d2b08c07ecdf60f6a8268083cae82", @@ -71,7 +71,7 @@ "src/types.ts": "0ed148b9bf21c59f455e8d5a79a9bf7d637d1b51003903b02d4c976bd8a66f2d", "src/version.ts": "4428bcfed17f7d5e084e9b3faf40d85ae44fe71cc3a81770ab348774c3dc0d68", "test/app-actions.test.ts": "9ce1e7238a04bff6a164705ca47a93f45be79b616e3fc6e3a9f626d4c68da9b1", - "test/app.test.ts": "3328017fd6ea69e5f852bf6b343cb87c7d1d885ff1e94e5c6a67f118352b0c0a", + "test/app.test.ts": "50ce30c622b0e378b16b12948b8ecffaaee06f4f0cf4c46f77ae9ea53096fdc3", "test/auth-command.test.ts": "6efb94a0c3754bc0057ee62249df6c57b558ad82a0a6919d2f5ed695c4769839", "test/auth.test.ts": "f309ecfbdeaa8bcb6ec179410f29efe4923e663485bb1b35d0cec4096313aed4", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", @@ -79,7 +79,7 @@ "test/check-macho-signature.test.ts": "4ef01ed87b052c85aee27270a5738f992d51a80a4c36891f218a491d28e9c0dc", "test/check-pr.test.ts": "b918630bbe74071bebe1348b75fa42ec1f7924e6421f869cb560653f6c5ea53c", "test/check-version.test.ts": "68a7615fd46a9212f6c1e1901f562feb384c75a1302228b7bf752eab1a96927a", - "test/cli.test.ts": "9a3595bb6274d952b85fe92941cfa1d80dc0c0f84364c995800f4fe8ce27cde8", + "test/cli.test.ts": "59e61e00f874fced08d8173580757759183338744cdd2449483043cd3c8b1dba", "test/config.test.ts": "7e96e13dd5de0271682c569370d97af8619e88f5b08f847641ec9bc10816e2e4", "test/errors.test.ts": "f5924c7adf6147313bea226ced286340a0ab8c28a204fc1b2603a1c0ced1271b", "test/executor.test.ts": "cc12dbf2ce6cd673a63bed74b86fea16bda76c361080cf140416b48d406db8f5", @@ -94,7 +94,7 @@ "test/logging.test.ts": "64fbe3b5ad1e11c0725af41de076af2645f6ca87ddb2f5ebd40e3b339b1b686f", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", "test/main.test.ts": "cbcd8979e1a54d4f269932492d567a3eb9154c59a76d2eb03973ff252fbbce5d", - "test/mcp.test.ts": "e9826f6f95942766e93fb885847f76a5d7c9c419d37e57513dc053f9061585ac", + "test/mcp.test.ts": "cb595c66422d9d6b25b8a5bffec2c4636c6c3958c57794ce7518501c95f6269a", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", "test/output.test.ts": "3b898699a31c7da7e5cac5dc973d9eff186bdcff9f0f8f10355d9e02ffebfe65", diff --git a/src/cli.ts b/src/cli.ts index f353c42..daca191 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -244,6 +244,18 @@ export async function run(argv: string[]): Promise { return EXIT.OK; } + // citty hands a command only the tokens after its own name, so an option written before the last command word is + // dropped: `deel --dry-run app run ...` would run the write, `deel --env demo ...` would call prod. + let words = 0; + const lastWordAt = argv.findIndex((token) => !token.startsWith("-") && ++words === matched); + if (argv.slice(0, Math.max(lastWordAt, 0)).some((token) => token.startsWith("-"))) { + throw new CliError( + "usage.command", + "Options go after the command.", + `Write 'deel ${positionals.slice(0, matched).join(" ")} ...' with the options at the end. Nothing was run.`, + ); + } + await runCommand(root, { rawArgs: argv }); return EXIT.OK; } diff --git a/src/core/mcp.ts b/src/core/mcp.ts index cbfefd7..2941419 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -34,6 +34,11 @@ export type CallToolOpts = { type RpcMessage = { jsonrpc?: string; id?: unknown; result?: unknown; error?: { code?: unknown; message?: unknown } }; +// A JSON-RPC message is an object: `null`, a list or a bare value in a reply is not one. +function asMessage(value: unknown): RpcMessage | null { + return value && typeof value === "object" && !Array.isArray(value) ? (value as RpcMessage) : null; +} + // A Streamable HTTP response is either one JSON body or an SSE stream whose `data:` lines carry the messages. export function parseRpcBody(text: string, contentType: string | undefined, id: number): RpcMessage | null { if (contentType?.includes("text/event-stream")) { @@ -41,7 +46,8 @@ export function parseRpcBody(text: string, contentType: string | undefined, id: // server that skips the blank lines is read line by line. const parse = (data: string) => { try { - return [JSON.parse(data) as RpcMessage]; + const message = asMessage(JSON.parse(data)); + return message ? [message] : []; } catch { return []; } @@ -57,11 +63,9 @@ export function parseRpcBody(text: string, contentType: string | undefined, id: return messages.find((message) => message.id === id) ?? null; } try { - const message: unknown = JSON.parse(text); - if (!message || typeof message !== "object" || Array.isArray(message)) return null; + const message = asMessage(JSON.parse(text)); // A reply to another request is not ours; one without an id is taken as ours. - const replyId = (message as RpcMessage).id; - return replyId === undefined || replyId === id ? (message as RpcMessage) : null; + return message && (message.id === undefined || message.id === id) ? message : null; } catch { return null; } diff --git a/test/app.test.ts b/test/app.test.ts index 8860f41..2d65796 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -119,6 +119,20 @@ test("search and describe take --fields and --quiet like any list", async (t) => assert.deepEqual((await run(runDescribe, { _: ["a"], fields: "name,method" })).json().data, [{ name: "a", method: "GET" }]); }); +test("--jq filters search and describe output and wins over --quiet", async (t) => { + isolated(t); + const { transport } = server((tool, args) => ({ texts: [tool === "get_action" ? JSON.stringify({ ...LIST, name: args.name }) : JSON.stringify({ actions: [{ name: "list_widgets", title: "List widgets" }, { name: "approve_widget", title: "Approve" }] })] })); + const run = async (fn: typeof runSearch, args: Record) => { + const io = captureIO(); + await fn({ ...ARGS, ...args }, [], deps(transport, loggedIn(), io.io)); + return io.out(); + }; + assert.equal(await run(runSearch, { _: ["x"], jq: ".[0].name", raw: true }), "list_widgets\n"); + assert.equal(await run(runSearch, { _: ["x"], jq: ".[1].title", raw: true, quiet: true }), "Approve\n"); + assert.equal(await run(runDescribe, { _: ["a", "b"], jq: ".[1].name", raw: true, quiet: true }), "b\n"); + assert.equal(await run(runSearch, { _: ["x"], jq: "length" }), "2\n"); +}); + test("search without words is a usage error, before any call", async (t) => { isolated(t); const { transport, requests } = server(() => assert.fail("no call expected")); diff --git a/test/cli.test.ts b/test/cli.test.ts index 05885c9..93118b6 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { run } from "../src/cli.ts"; -import { EXIT } from "../src/core/errors.ts"; +import { CliError, EXIT } from "../src/core/errors.ts"; import { printContract, printContractJson } from "../src/help.ts"; import type { Descriptor } from "../src/types.ts"; @@ -261,3 +261,17 @@ test("--help --json carries nullable on the fields that have it", () => { assert.equal(fields.find((f: { name: string }) => f.name === "note").nullable, true); assert.equal("nullable" in fields.find((f: { name: string }) => f.name === "title"), false); }); + +test("an option before the last command word is refused, because citty would drop it and run the command without it", async () => { + const refused = (error: unknown) => error instanceof CliError && error.code === "usage.command" && /Options go after the command/.test(error.message); + // `--dry-run` ahead of `run` never reaches it: the write would be sent. + for (const argv of [["--dry-run", "app", "run", "approve_widget"], ["app", "--dry-run", "run", "approve_widget"], ["--env=demo", "app", "search", "x"], ["--json", "adjustments", "create", "--invoice"]]) { + await assert.rejects(() => run(argv), refused, argv.join(" ")); + } + const hint = await run(["--beta", "app", "search", "x"]).catch((error: CliError) => error.next); + assert.match(String(hint), /'deel app search \.\.\.' with the options at the end/); + // Help and version, which run() answers itself, and options after the words are not refused. + assert.equal((await capture(["--help"])).code, EXIT.OK); + assert.equal((await capture(["-h", "adjustments", "create", "--invoice"])).code, EXIT.OK); + assert.equal((await capture(["adjustments", "create", "--invoice", "--generate-input"])).code, EXIT.OK); +}); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index efbd4b5..d7cf52c 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -54,6 +54,15 @@ test("an SSE message split over several data lines is joined, and a reply to ano assert.deepEqual(parseRpcBody(JSON.stringify({ result: { a: 2 } }), "application/json", 1)?.result, { a: 2 }); }); +test("an SSE or JSON body that isn't a message object is not a reply", () => { + for (const data of ["null", "[]", "7", '"x"', "true"]) { + assert.equal(parseRpcBody(`data: ${data}\n\n`, "text/event-stream", 1), null, data); + assert.equal(parseRpcBody(data, "application/json", 1), null, data); + } + // A null event next to the real one doesn't hide it. + assert.deepEqual(parseRpcBody(`data: null\n\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { ok: 1 } })}\n\n`, "text/event-stream", 1)?.result, { ok: 1 }); +}); + test("parseRpcBody picks the SSE message with the call's id and skips bad lines", () => { const text = ["data: not json", `data: ${JSON.stringify({ jsonrpc: "2.0", id: 9, result: {} })}`, `data: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { x: 1 } })}`].join("\n"); assert.deepEqual(parseRpcBody(text, "text/event-stream", 1)?.result, { x: 1 }); From c3b34a89cc6f5b868273cd2afabfaba8fc15095f Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Tue, 24 Nov 2026 07:57:17 -0300 Subject: [PATCH 6/7] fix: report a response the server stopped reading as cut, not whole The server cuts a body in two ways and says so in a second text item: the whole body was read and is over the 100 KB cap, or reading stopped early (a body past the 5 MB read limit, a timeout, a broken connection), where it words the notice differently and the full size is unknown. Only the first form was recognised, so in the second the cut text came back with no meta.truncated and no warning. - meta.truncated carries read_bytes, shown_bytes and the server's reason for the second form; the first form is unchanged - any other notice that starts '[Response truncated:' still counts as cut - README describes both shapes Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- scripts/doctor-hashes.json | 10 +++++----- src/commands/app.ts | 3 ++- src/core/app-actions.ts | 35 +++++++++++++++++++++++++++++++---- test/app-actions.test.ts | 24 ++++++++++++++++++++++++ test/app.test.ts | 12 ++++++++++++ 6 files changed, 75 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f9d8f46..cad0584 100644 --- a/README.md +++ b/README.md @@ -415,7 +415,7 @@ deel app run --input ... --dry-run # print the call, run noth - `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. - `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. A write is never re-sent after a timeout or a server error (reads are retried); it is sent again only after a 401 once the login is renewed, which is answered before the action runs. When a write may have run without an answer, the error says so and asks you to check with a read before running it again. - Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored, and so is any option written before the command words (`deel --dry-run app run ...`), which would otherwise be dropped. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. -- Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much, and stderr has a warning. +- Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much (`total_bytes` and `shown_bytes`; when the server stopped reading a very large or slow response, `read_bytes` and a `reason` in place of the total), and stderr has a warning. - A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). **For agents:** let the agent run `deel app search` and `deel app describe` freely, and keep `deel app run` on "ask" in your agent's permission settings, since the CLI itself never asks before a write. diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index e55b1a3..f0adace 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "b06874c1143c15a838c286d1108588737b45a5405b2b4e18bc36c15c72558aa1", "CONTRIBUTING.md": "bf9d9870d07cf1c27793ff8bc58edbd229b533e9a550007dd89b7fa106759067", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "cbe8060b73420c9da07f5006278b2a4229a25da162e68efe15906935ca68d66b", + "README.md": "7bc56c9950c7f79946d7b24810b45ce77d2b0b1499c1206d3e429a04036c3837", "SECURITY.md": "6ad03fd32443e1dd7270e27180b5dfa6684826311543ae60b1cc6f937f9bcc53", "package-lock.json": "c66ea4ccbeb2a7393cdfa4ed87cee082ee8b9174fff0934a368c874136d1030f", "package.json": "7fa2b65175440d7ac0fd66e1359f3124ad2362a088680a930737ec351a984cc4", @@ -41,7 +41,7 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "40469644d0a0a2b6d38ad407b155b4c9cf3317797d13641d7ffc87ee4e435a8b", "src/commands.map.ts": "71540a126094af88815c46dba823273b75e292edad33f266e82e5be1fb014b2c", - "src/commands/app.ts": "416956d755670d5e5a428a848b2b90595e5c408691e0b75d2b0eec1301ae783e", + "src/commands/app.ts": "fe1eab511b3265ffbb6abdfb65babc033ccd751272ae4de74b82c83af5cc343e", "src/commands/auth.ts": "e9c46ba0de2ef0bbb36b6054151db78f354bf5de1fccd229ecb4f8960c64f54c", "src/commands/commands.ts": "9df650467599e5b0d8fa1594584e0943b9385e4c820938ae9c88d3dde4b67c94", "src/commands/index.ts": "eafeaca796b6810e568c95b0267efdb554eacac7cd2990ea3ed7476b0f3d0f84", @@ -50,7 +50,7 @@ "src/commands/tokens.ts": "__deleted__", "src/commands/webhooks.ts": "__deleted__", "src/core/api-tokens.ts": "__deleted__", - "src/core/app-actions.ts": "2bf718aca45087aff5d861bb8ce557da7e07552a807e054025d66977895e6018", + "src/core/app-actions.ts": "bd8b187d4e047bb54c2d1dadf741e5e8b0dee3ad66fe5ccd2b53dcee150812f6", "src/core/auth.ts": "8f8c28ead8c6d50de222f8447a44daf2e58c25eb2897388fbb79e35bc9616768", "src/core/commands-list.ts": "7a6f7f88df6b79b347d7858de52a8042528f40cfd8089df2088cceeff63299cc", "src/core/config.ts": "876ed6d2507c61e2924ce5dc001bc7486774918ebec963937182765b541c61dc", @@ -84,8 +84,8 @@ "src/public-api/manifest.json": "6e7a2e0ba715148e8cecf2dc7572bdf6a9cb2ce4efec76c6b97018ffe6c12da1", "src/types.ts": "22cd65a6c0e204deec85974fb46ed47570f0d405c041b09f779fc0af6e8b4121", "src/version.ts": "89734abe56c67870b5d3ad77b5703cfbd662697680ded300226308a8ac301d3d", - "test/app-actions.test.ts": "9ce1e7238a04bff6a164705ca47a93f45be79b616e3fc6e3a9f626d4c68da9b1", - "test/app.test.ts": "2d8cc7e4b504774b5138527ac4d15bba4d0f711c7bb9c4d38766ee0df4a924e5", + "test/app-actions.test.ts": "b10fe9a2573231138a0af75f996da2ad9c302d32abdd618eb94513866260fe9d", + "test/app.test.ts": "3e5b93c7a741508affd5defe67c08b95f019dce12c4494498f826e75f83f36d6", "test/apps-listing.test.ts": "7bea22fdc9aaed05706d70b5807151130f382eb2892ad9d0773fee90cfe989f2", "test/apps.test.ts": "__deleted__", "test/auth-command.test.ts": "a424c43fdd705d3853e68698ae691f73166e24a2e37afcd6bd4b4d3b333cad55", diff --git a/src/commands/app.ts b/src/commands/app.ts index ab50c8a..93e0a91 100644 --- a/src/commands/app.ts +++ b/src/commands/app.ts @@ -26,6 +26,7 @@ import { runAction, runCall, searchActions, + truncationWarning, } from "../core/app-actions.ts"; import type { AppClient } from "../core/app-actions.ts"; import { commonArgs, configFrom, outputOpts } from "./shared.ts"; @@ -162,7 +163,7 @@ export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Pro const meta: Record = { request_id: outcome.requestId }; if (outcome.truncated) { meta.truncated = outcome.truncated; - ctx.io.err(`warning: the response was cut at ${outcome.truncated.shown_bytes} of ${outcome.truncated.total_bytes} bytes, so it is returned as text. Narrow the query to get all of it.\n`); + ctx.io.err(`warning: ${truncationWarning(outcome.truncated)}, so it is returned as text. Narrow the query to get all of it.\n`); } await render(ctx.io, envelope(outcome.data, meta), outputOpts(args)); } diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts index fb1f0e8..88e43ce 100644 --- a/src/core/app-actions.ts +++ b/src/core/app-actions.ts @@ -21,7 +21,12 @@ export const APP_TOOL = { export const SEARCH_MAX_LIMIT = 20; const INPUT_KEYS = ["path_params", "query", "body"] as const; -const TRUNCATION_NOTICE = /^\[Response truncated: the action returned (\d+) bytes; only the first (\d+) bytes are shown\.\]$/; +// The notice item the server adds after a body it cut. It has two forms: the whole body was read and is longer than +// the cap, or reading stopped early (a body past the read limit, a timeout, a broken connection), so the full size +// is unknown. Anything else that starts the same way is still a cut body, so a reworded notice can't pass as complete. +const NOTICE_COMPLETE = /^\[Response truncated: the action returned (\d+) bytes; only the first (\d+) bytes are shown\.\]$/; +const NOTICE_STOPPED = /^\[Response truncated: reading stopped after (\d+) bytes \((.+)\); only the first (\d+) bytes are shown\.\]$/; +const NOTICE_START = "[Response truncated:"; // Failures that happen before an action runs, or on a read, so another attempt is safe. const TRANSIENT_CODES = new Set(["UPSTREAM_UNAVAILABLE", "UPSTREAM_TIMEOUT", "UPSTREAM_SERVER_ERROR"]); const NO_RESPONSE_CODES = new Set(["UPSTREAM_TIMEOUT", "UPSTREAM_UNAVAILABLE"]); @@ -317,14 +322,36 @@ export function runCall(action: ActionDetail, input: ActionInput): RunCall { return { tool, arguments: { name: action.name, ...coerceInput(input, action.input_schema) } }; } -export type RunOutcome = { data: unknown; requestId: string; truncated?: { total_bytes: number; shown_bytes: number } }; +// How a cut body is described: the whole size when the server read it all; otherwise only what it read before it stopped, +// and why (the server's own words). +export type Truncation = { total_bytes: number; shown_bytes: number } | { read_bytes: number; shown_bytes: number; reason: string } | { shown_bytes: number; reason: string }; + +export type RunOutcome = { data: unknown; requestId: string; truncated?: Truncation }; + +// The first half of the stderr warning for a cut body (the caller adds what to do about it). +export function truncationWarning(truncated: Truncation): string { + if ("total_bytes" in truncated) return `the response was cut at ${truncated.shown_bytes} of ${truncated.total_bytes} bytes`; + if ("read_bytes" in truncated) return `the response was cut at ${truncated.shown_bytes} bytes (the server stopped reading it after ${truncated.read_bytes} bytes: ${truncated.reason})`; + return `the response was cut at ${truncated.shown_bytes} bytes (${truncated.reason})`; +} + +function truncationOf(body: string, notices: string[]): Truncation | undefined { + for (const text of notices) { + const complete = NOTICE_COMPLETE.exec(text); + if (complete) return { total_bytes: Number(complete[1]), shown_bytes: Number(complete[2]) }; + const stopped = NOTICE_STOPPED.exec(text); + if (stopped) return { read_bytes: Number(stopped[1]), shown_bytes: Number(stopped[3]), reason: stopped[2] }; + if (text.startsWith(NOTICE_START)) return { shown_bytes: Buffer.byteLength(body, "utf8"), reason: text }; + } + return undefined; +} // The backend body as it came: JSON when it parses, otherwise the text. A body over the server's cap is cut and // followed by a notice item; cut JSON doesn't parse, so it stays text. export function runOutcome(result: ToolResult): RunOutcome { const body = result.texts[0] ?? ""; - const notice = result.texts.slice(1).map((text) => TRUNCATION_NOTICE.exec(text)).find(Boolean); - if (notice) return { data: body, requestId: result.requestId, truncated: { total_bytes: Number(notice[1]), shown_bytes: Number(notice[2]) } }; + const truncated = truncationOf(body, result.texts.slice(1)); + if (truncated) return { data: body, requestId: result.requestId, truncated }; let data: unknown = body; try { data = JSON.parse(body); diff --git a/test/app-actions.test.ts b/test/app-actions.test.ts index 8c3f492..4434568 100644 --- a/test/app-actions.test.ts +++ b/test/app-actions.test.ts @@ -15,6 +15,7 @@ import { runCall, runOutcome, searchActions, + truncationWarning, } from "../src/core/app-actions.ts"; import type { ActionDetail, AppClient } from "../src/core/app-actions.ts"; import type { ResolvedToken } from "../src/core/auth.ts"; @@ -403,6 +404,29 @@ test("a cut body stays text and reports how much was shown", () => { assert.deepEqual(runOutcome(ok('{"items":[1,2', notice)), { data: '{"items":[1,2', requestId: "req", truncated: { total_bytes: 162732, shown_bytes: 102400 } }); }); +test("a body the server stopped reading is reported as cut too, with the bytes it read and why", () => { + // The three reasons the server gives when it could not read the whole body, so the full size is unknown. + for (const why of ["the response is larger than the read limit", "the response did not finish in time", "the response was larger or interrupted"]) { + const notice = `[Response truncated: reading stopped after 5242880 bytes (${why}); only the first 102400 bytes are shown.]`; + assert.deepEqual(runOutcome(ok('{"items":[1,2', notice)), { data: '{"items":[1,2', requestId: "req", truncated: { read_bytes: 5242880, shown_bytes: 102400, reason: why } }, why); + } +}); + +test("a notice worded some other way is still a cut body, never a whole one", () => { + const notice = "[Response truncated: something the CLI has not seen before.]"; + const outcome = runOutcome(ok('{"items":[1,2', notice)); + assert.deepEqual(outcome.truncated, { shown_bytes: 13, reason: notice }); + assert.equal(outcome.data, '{"items":[1,2'); + // A second item that is not a notice is not a cut. + assert.equal(runOutcome(ok('{"a":1}', "some other text")).truncated, undefined); +}); + +test("the warning says what was cut and, when the size is unknown, what the server read", () => { + assert.equal(truncationWarning({ total_bytes: 200, shown_bytes: 100 }), "the response was cut at 100 of 200 bytes"); + assert.equal(truncationWarning({ read_bytes: 500, shown_bytes: 100, reason: "the response did not finish in time" }), "the response was cut at 100 bytes (the server stopped reading it after 500 bytes: the response did not finish in time)"); + assert.equal(truncationWarning({ shown_bytes: 100, reason: "odd" }), "the response was cut at 100 bytes (odd)"); +}); + // ---------------- describe --generate-input ---------------- test("the input skeleton follows the schema", () => { diff --git a/test/app.test.ts b/test/app.test.ts index cec376c..55e6eda 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -224,6 +224,18 @@ test("a truncated response is returned as text with meta.truncated and a warning assert.match(io.err(), /cut at 102400 of 200000 bytes/); }); +test("a body the server stopped reading is also returned as text with meta.truncated and a warning", async (t) => { + isolated(t); + const notice = "[Response truncated: reading stopped after 5242880 bytes (the response is larger than the read limit); only the first 102400 bytes are shown.]"; + const { transport } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(LIST)] } : { texts: ['[{"id":', notice] })); + const io = captureIO(); + await runRun({ ...ARGS, _: ["list_widgets"] }, [], deps(transport, loggedIn(), io.io)); + const printed = io.json(); + assert.equal(printed.data, '[{"id":'); + assert.deepEqual(printed.meta.truncated, { read_bytes: 5242880, shown_bytes: 102400, reason: "the response is larger than the read limit" }); + assert.match(io.err(), /cut at 102400 bytes \(the server stopped reading it after 5242880 bytes: the response is larger than the read limit\)/); +}); + test("an HTTP 401 renews the stored login and retries with the new token", async (t) => { isolated(t); const store = loggedIn(); From d0981126c429fd75b4d8cb9edb6bc6e94837323e Mon Sep 17 00:00:00 2001 From: Guilherme Soares Date: Tue, 24 Nov 2026 08:21:40 -0300 Subject: [PATCH 7/7] fix: type shorthand --input by the action's schema in deel app run Found running the commands against a real server. Shorthand reads a value with spaces as a list of words and cannot know a field is a string, so 'body={title=Payroll sync}' sent ["Payroll","sync"] for a string field, and 'query={org=null}' sent the text "null" for a nullable integer, which the server refused. The schema is known only after get_action, so once it arrives the parsed shorthand is typed by it, in place: a string field gets its text as written, and a nullable field written null becomes a real null, at any depth. JSON input is never touched, so a JSON "null" stays a string. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- scripts/doctor-hashes.json | 14 +++++------ src/commands/app.ts | 4 +++- src/core/app-actions.ts | 32 +++++++++++++++++++++++++ src/core/input.ts | 20 ++++++++++++++++ test/app-actions.test.ts | 31 ++++++++++++++++++++++++ test/app.test.ts | 24 +++++++++++++++++++ test/input.test.ts | 48 +++++++++++++++++++++++++++++++++++++- 8 files changed, 165 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index cad0584..cfa4676 100644 --- a/README.md +++ b/README.md @@ -414,7 +414,7 @@ deel app run --input ... --dry-run # print the call, run noth - `--input` is one object with `path_params`, `query` and `body`, in any of the [`--input` forms](#request-input). The server checks it against the action's schema and names each field that's wrong. - `run` asks the server whether the action reads or writes (`run_with` from `describe`) and calls it without a confirmation step. A write is never re-sent after a timeout or a server error (reads are retried); it is sent again only after a 401 once the login is renewed, which is answered before the action runs. When a write may have run without an answer, the error says so and asks you to check with a read before running it again. -- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored, and so is any option written before the command words (`deel --dry-run app run ...`), which would otherwise be dropped. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. +- Shorthand values in `--input` stay text until the action's schema says a field is a number (so `00123`, `1.10` and ids past 2^53 arrive unchanged) and `true`/`false` stay text until it says a field is a boolean. A field the schema says is a string gets its text exactly as written, spaces included (`body={title=Payroll sync}` sends one string, not a list of words), and `null` in a field the schema says is nullable (`query={org=null}`) is sent as a real null, at any depth. JSON input is never rewritten: there `"null"` stays a string. Flags `deel app` doesn't use (`--file`, `--form`, `--idempotency-key`, `--debug`, `--log-bodies`) and any flag it doesn't know (a mistyped `--dryrun`, say) are refused before anything runs, rather than ignored, and so is any option written before the command words (`deel --dry-run app run ...`), which would otherwise be dropped. Large ids are only kept exact in shorthand: JSON input is parsed as JSON, which rounds numbers past 2^53, so write such an id as a string. - Responses over 100 KB are cut by the server. The output then holds the text that came back, `meta.truncated` says how much (`total_bytes` and `shown_bytes`; when the server stopped reading a very large or slow response, `read_bytes` and a `reason` in place of the total), and stderr has a warning. - A login that hides sensitive data, or one without the action's scope, gets an error naming the next step (`deel auth login`, or `deel auth login --scopes ...`). diff --git a/scripts/doctor-hashes.json b/scripts/doctor-hashes.json index f0adace..0429c87 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "b06874c1143c15a838c286d1108588737b45a5405b2b4e18bc36c15c72558aa1", "CONTRIBUTING.md": "bf9d9870d07cf1c27793ff8bc58edbd229b533e9a550007dd89b7fa106759067", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "7bc56c9950c7f79946d7b24810b45ce77d2b0b1499c1206d3e429a04036c3837", + "README.md": "c362e7566b417f113a4af0edb866eb29958a722a27ebb0cce91d07c6c157e6f7", "SECURITY.md": "6ad03fd32443e1dd7270e27180b5dfa6684826311543ae60b1cc6f937f9bcc53", "package-lock.json": "c66ea4ccbeb2a7393cdfa4ed87cee082ee8b9174fff0934a368c874136d1030f", "package.json": "7fa2b65175440d7ac0fd66e1359f3124ad2362a088680a930737ec351a984cc4", @@ -41,7 +41,7 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "40469644d0a0a2b6d38ad407b155b4c9cf3317797d13641d7ffc87ee4e435a8b", "src/commands.map.ts": "71540a126094af88815c46dba823273b75e292edad33f266e82e5be1fb014b2c", - "src/commands/app.ts": "fe1eab511b3265ffbb6abdfb65babc033ccd751272ae4de74b82c83af5cc343e", + "src/commands/app.ts": "41a26c7b4c567d5cb916123adf153b75426e7784cbe8241be2250fa818384c5a", "src/commands/auth.ts": "e9c46ba0de2ef0bbb36b6054151db78f354bf5de1fccd229ecb4f8960c64f54c", "src/commands/commands.ts": "9df650467599e5b0d8fa1594584e0943b9385e4c820938ae9c88d3dde4b67c94", "src/commands/index.ts": "eafeaca796b6810e568c95b0267efdb554eacac7cd2990ea3ed7476b0f3d0f84", @@ -50,7 +50,7 @@ "src/commands/tokens.ts": "__deleted__", "src/commands/webhooks.ts": "__deleted__", "src/core/api-tokens.ts": "__deleted__", - "src/core/app-actions.ts": "bd8b187d4e047bb54c2d1dadf741e5e8b0dee3ad66fe5ccd2b53dcee150812f6", + "src/core/app-actions.ts": "60af4f2c5ab4e46c85a34f2781f78e5bf60f2e18992d57d3492e5197a31339a8", "src/core/auth.ts": "8f8c28ead8c6d50de222f8447a44daf2e58c25eb2897388fbb79e35bc9616768", "src/core/commands-list.ts": "7a6f7f88df6b79b347d7858de52a8042528f40cfd8089df2088cceeff63299cc", "src/core/config.ts": "876ed6d2507c61e2924ce5dc001bc7486774918ebec963937182765b541c61dc", @@ -62,7 +62,7 @@ "src/core/flags.ts": "270d3903ea3bb847e1295281ca1c49e9dd8a4aeade2e748bd8273aff50725559", "src/core/http.ts": "6b2ba42bfcdc236e2ba8df057ae9e43fe94a3e30d959048fd8750c7689a9bb41", "src/core/idempotency.ts": "5f2a36a56d6ea36a4f92689253b2a8ab0c4c29c8b42833253a449f1ec58cb413", - "src/core/input.ts": "ee8b15f643ba715c8392fa682706806457da2fa58228b82f1eec93b1cd435071", + "src/core/input.ts": "47db0b4237623658423c386a909a71db31b181a8034a2b2dce21732cb2ba1d3c", "src/core/io.ts": "7e8aaeebbfd5b6701a80a6e409d8bad19cceb6811092e5db0c811aff22b1474f", "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", @@ -84,8 +84,8 @@ "src/public-api/manifest.json": "6e7a2e0ba715148e8cecf2dc7572bdf6a9cb2ce4efec76c6b97018ffe6c12da1", "src/types.ts": "22cd65a6c0e204deec85974fb46ed47570f0d405c041b09f779fc0af6e8b4121", "src/version.ts": "89734abe56c67870b5d3ad77b5703cfbd662697680ded300226308a8ac301d3d", - "test/app-actions.test.ts": "b10fe9a2573231138a0af75f996da2ad9c302d32abdd618eb94513866260fe9d", - "test/app.test.ts": "3e5b93c7a741508affd5defe67c08b95f019dce12c4494498f826e75f83f36d6", + "test/app-actions.test.ts": "4a43b8b06c048dd091c668c5ff5945f439066ab2c31d20a491cc410116162980", + "test/app.test.ts": "c896f6138f93e20b116e6a0bcf7c260156c04091900bdfc81b73cef0903be037", "test/apps-listing.test.ts": "7bea22fdc9aaed05706d70b5807151130f382eb2892ad9d0773fee90cfe989f2", "test/apps.test.ts": "__deleted__", "test/auth-command.test.ts": "a424c43fdd705d3853e68698ae691f73166e24a2e37afcd6bd4b4d3b333cad55", @@ -118,7 +118,7 @@ "test/help.test.ts": "0da411f2553ff3b8f5f820a52309ac22b13030a510d32f6809800c536cc6fa5f", "test/http.test.ts": "f4f975b0f0c46b867d09711a27683398a9796c754ec30734aa9510d20ae2e2ff", "test/idempotency.test.ts": "bd8acc0105b3b361ba2f43e5622de651628574beab487c14bfc6a0fd91cb1618", - "test/input.test.ts": "04f0664906e1845f1ecdd2c5331a4a2ff06c30c7e42c43c823f2caedc2579bae", + "test/input.test.ts": "0b8449322b04b3f665b4a20af843401f4e15e1a7cb91a861aa491da83181f595", "test/install.test.ts": "f68a3ee5f08eb2172e9c12823ed46e120ea156fc2695abc77626e32dd57b826e", "test/io.test.ts": "88e11df89fcdacdc9bbd3b46eec12125c4c9ea4f0a717d5840582542ad1759a6", "test/jobs.test.ts": "0a37b7204e5c5f9c2ffef3efa062256f6d1e061885189b2809698c3baf36bc13", diff --git a/src/commands/app.ts b/src/commands/app.ts index 93e0a91..a1aa6e0 100644 --- a/src/commands/app.ts +++ b/src/commands/app.ts @@ -10,7 +10,7 @@ import { setLoggingEnabled } from "../core/logging.ts"; import { resolveMcpUrl } from "../core/config.ts"; import { authFor, resolveToken } from "../core/auth.ts"; import type { ResolvedToken } from "../core/auth.ts"; -import { parseInput } from "../core/input.ts"; +import { parseInput, typeShorthandBySchema } from "../core/input.ts"; import { CliError } from "../core/errors.ts"; import type { IOStreams } from "../core/io.ts"; import type { Transport } from "../core/http.ts"; @@ -25,6 +25,7 @@ import { inputSkeleton, runAction, runCall, + schemaParams, searchActions, truncationWarning, } from "../core/app-actions.ts"; @@ -154,6 +155,7 @@ export async function runRun(args: Args, rawArgs: string[], deps?: AppDeps): Pro const input = actionInput(args.input === undefined ? undefined : parseInput(String(args.input), [], { exactScalars: true })); const { ctx, client } = prepare(args, rawArgs, deps); const { action, requestId } = await getAction(client, name); + typeShorthandBySchema(input, schemaParams(action.input_schema)); // shorthand strings and nulls, now the schema is known if (args["dry-run"]) { const call = runCall(action, input); await render(ctx.io, envelope({ method: "tools/call", params: { name: call.tool, arguments: call.arguments } }, { request_id: requestId, dry_run: true }), { ...outputOpts(args), quiet: false }); diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts index 88e43ce..eb47843 100644 --- a/src/core/app-actions.ts +++ b/src/core/app-actions.ts @@ -10,6 +10,7 @@ import type { ResolvedToken } from "./auth.ts"; import { RETRY_BASE_DELAY_MS, RETRY_MAX_ATTEMPTS } from "./constants.ts"; import { callTool, toolFailure } from "./mcp.ts"; import type { ToolFailure, ToolResult } from "./mcp.ts"; +import type { CliParam } from "../types.ts"; import type { Transport } from "./http.ts"; export const APP_TOOL = { @@ -282,6 +283,37 @@ function typeOf(schema: JsonSchema | undefined): string | undefined { return Array.isArray(type) ? type.find((item): item is string => typeof item === "string" && item !== "null") : typeof type === "string" ? type : undefined; } +// Whether the schema accepts null: OpenAPI 3.0 `nullable: true`, 3.1 `type: [.., "null"]`, or a null member of anyOf/oneOf. +function isNullable(schema: JsonSchema | undefined): boolean { + if (!isRecord(schema)) return false; + if (schema.nullable === true) return true; + if (Array.isArray(schema.type) && schema.type.includes("null")) return true; + return (["anyOf", "oneOf"] as const).some((key) => Array.isArray(schema[key]) && (schema[key] as unknown[]).some((option) => isRecord(option) && option.type === "null")); +} + +// The schema's properties as the parameter tree `typeShorthandBySchema` walks: each property's name, whether it is a +// string or nullable, and the properties of an object or of the objects in a list. A type the schema doesn't give is +// left as "object" with no properties, which nothing acts on. +export function schemaParams(schema: JsonSchema | undefined): CliParam[] { + const effective = effectiveSchema(schema); + const properties = isRecord(effective?.properties) ? (effective.properties as Record) : {}; + return Object.entries(properties).map(([name, declared]) => { + const property = effectiveSchema(declared); + const type = typeOf(property); + const items = type === "array" ? effectiveSchema(isRecord(property?.items) ? (property.items as JsonSchema) : undefined) : undefined; + const known = type === "string" || type === "integer" || type === "number" || type === "boolean" || type === "array" ? type : "object"; + const children = known === "array" ? schemaParams(items) : known === "object" ? schemaParams(property) : []; + return { + name, + in: "body" as const, + type: known, + required: false, + ...(isNullable(declared) || isNullable(property) ? { nullable: true as const } : {}), + ...(children.length > 0 ? { properties: children } : {}), + }; + }); +} + // `--input` shorthand arrives as text (so `00123`, `1.10`, ids past 2^53 and a string field's "false" survive); this // types it by the action's schema: text the schema declares a number becomes one when that is exact, and "true" or // "false" a boolean, through objects and lists. diff --git a/src/core/input.ts b/src/core/input.ts index 375125c..ed2de70 100644 --- a/src/core/input.ts +++ b/src/core/input.ts @@ -190,6 +190,26 @@ function coerceTopLevel(value: unknown, bodyProps: CliParam[], nullLiteral: bool return record; } +// For callers that learn the schema only after parsing (`deel app run` reads the action first): types what shorthand +// guessed at, by the schema, in place. A string field gets the text back as written (a b c stays one string, 007 stays +// 007) and a nullable field written `null` becomes a real null, at any depth. Only values that came from shorthand are +// touched, so JSON input, where "null" is a string, is left alone. +export function typeShorthandBySchema(value: unknown, params: CliParam[]): void { + if (value === null || typeof value !== "object" || Array.isArray(value)) return; + const record = value as Record; + const raw = RAW_TEXT.get(record); + for (const param of params) { + if (!(param.name in record)) continue; + const text = raw?.get(param.name); + if (text !== undefined && param.nullable && text === "null") record[param.name] = null; + else if (text !== undefined && param.type === "string") record[param.name] = text; + else if (param.properties?.length) { + const child = record[param.name]; + for (const item of Array.isArray(child) ? child : [child]) typeShorthandBySchema(item, param.properties); + } + } +} + // A string field written in shorthand was read with guesses (reason=007 as a number, reason=a b c as a list), so put the // text back as written. It goes into nested objects and lists of objects too; values from JSON are left alone. function restoreStrings(record: Record, params: CliParam[]): void { diff --git a/test/app-actions.test.ts b/test/app-actions.test.ts index 4434568..4e76e94 100644 --- a/test/app-actions.test.ts +++ b/test/app-actions.test.ts @@ -14,6 +14,7 @@ import { runAction, runCall, runOutcome, + schemaParams, searchActions, truncationWarning, } from "../src/core/app-actions.ts"; @@ -441,6 +442,36 @@ test("the input skeleton follows the schema", () => { assert.deepEqual(inputSkeleton(combined), { path_params: { id: "", tags: [], n: 0 } }); }); +test("schemaParams lists each property with its type, nullability and the properties of objects and lists of objects", () => { + const schema = { + type: "object", + properties: { + path_params: { type: "object", properties: { id: { type: "string" } } }, + query: { type: "object", properties: { org: { type: "integer", nullable: true }, any: {} } }, + body: { + type: "object", + properties: { + title: { type: ["string", "null"] }, + items: { type: "array", items: { type: "object", properties: { label: { type: "string" } } } }, + owner: { allOf: [{ type: "object", properties: { name: { type: "string" } } }] }, + }, + }, + }, + }; + const params = schemaParams(schema); + const byName = (list: typeof params | undefined, name: string) => list?.find((entry) => entry.name === name); + assert.deepEqual(params.map((entry) => entry.name), ["path_params", "query", "body"]); + assert.equal(byName(byName(params, "path_params")?.properties, "id")?.type, "string"); + const org = byName(byName(params, "query")?.properties, "org"); + assert.deepEqual([org?.type, org?.nullable], ["integer", true]); + assert.equal(byName(byName(params, "query")?.properties, "any")?.type, "object"); // no type given: nothing acts on it + const body = byName(params, "body")?.properties; + assert.deepEqual([byName(body, "title")?.type, byName(body, "title")?.nullable], ["string", true]); + assert.equal(byName(byName(body, "items")?.properties, "label")?.type, "string"); + assert.equal(byName(byName(body, "owner")?.properties, "name")?.type, "string"); + assert.deepEqual(schemaParams(undefined), []); +}); + test("allOf parts are merged, with the parent's own keywords, not replaced by the last part", () => { const schema: ActionDetail["input_schema"] = { type: "object", diff --git a/test/app.test.ts b/test/app.test.ts index 55e6eda..2a2a03f 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -175,6 +175,30 @@ test("run reads the action, then calls run_read_action with the parsed input", a assert.deepEqual(io.json().data, [{ id: "w1" }]); }); +test("run types shorthand by the action's schema: a string with spaces stays one string, null in a nullable field is null", async (t) => { + isolated(t); + const NOTE = { + name: "create_note", + method: "POST", + scopes: ["widgets:write"], + run_with: "run_write_action", + input_schema: { + type: "object", + properties: { + query: { type: "object", properties: { org: { type: "integer", nullable: true }, limit: { type: "integer" } } }, + body: { type: "object", properties: { title: { type: "string" }, tags: { type: "array", items: { type: "string" } } } }, + }, + }, + }; + const { transport, tools } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(NOTE)] } : { texts: ['{"id":"n1"}'] })); + await runRun({ ...ARGS, _: ["create_note"], input: "query={org=null,limit=5},body={title=Payroll sync (draft),tags=a b}" }, [], deps(transport, loggedIn(), captureIO().io)); + assert.deepEqual(tools()[1], { name: "run_write_action", arguments: { name: "create_note", query: { org: null, limit: 5 }, body: { title: "Payroll sync (draft)", tags: ["a", "b"] } } }); + // The same text as JSON is not shorthand: its "null" stays a string. + const again = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(NOTE)] } : { texts: ["{}"] })); + await runRun({ ...ARGS, _: ["create_note"], input: '{"body":{"title":"null"},"query":{"org":null}}' }, [], deps(again.transport, loggedIn(), captureIO().io)); + assert.deepEqual(again.tools()[1].arguments, { name: "create_note", query: { org: null }, body: { title: "null" } }); +}); + test("run of a write calls run_write_action without asking, and is sent once", async (t) => { isolated(t); const { transport, tools, requests } = server((tool) => (tool === "get_action" ? { texts: [JSON.stringify(APPROVE)] } : { texts: [failure(504, "UPSTREAM_TIMEOUT", "The action timed out")], isError: true })); diff --git a/test/input.test.ts b/test/input.test.ts index f78e5d2..dc7698d 100644 --- a/test/input.test.ts +++ b/test/input.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { parseInput } from "../src/core/input.ts"; +import { parseInput, typeShorthandBySchema } from "../src/core/input.ts"; import type { CliParam } from "../src/types.ts"; const props: CliParam[] = [ @@ -186,3 +186,49 @@ test("a value whose closing bracket is not the opening one's pair stays a string test("an escaped closing bracket does not close the value", () => { assert.deepEqual(parseInput("reason=[a\\]", props), { reason: "[a]" }); }); + +// ---------------- typeShorthandBySchema (deel app run: the schema is known only after the parse) ---------------- + +const param = (name: string, type: CliParam["type"], extra: Partial = {}): CliParam => ({ name, in: "body", type, required: false, ...extra }); + +test("shorthand typed by a schema gives a string field its text back, at any depth, and leaves the rest", () => { + const exact = { exactScalars: true }; + const params = [param("body", "object", { properties: [param("title", "string"), param("n", "integer"), param("tags", "array"), param("owner", "object", { properties: [param("name", "string")] })] })]; + const input = parseInput("body={title=Payroll sync 007,n=12,tags=a b c,owner={name=Jo Bloggs}}", [], exact) as Record; + assert.deepEqual(input.body.title, ["Payroll", "sync", "007"]); // before: guessed as a list + typeShorthandBySchema(input, params); + assert.equal(input.body.title, "Payroll sync 007"); + assert.equal(input.body.owner.name, "Jo Bloggs"); + assert.equal(input.body.n, "12"); // numbers stay text for the caller's own typing + assert.deepEqual(input.body.tags, ["a", "b", "c"]); // a list field keeps the list +}); + +test("shorthand typed by a schema reaches the objects inside a list of objects", () => { + const params = [param("body", "object", { properties: [param("items", "array", { properties: [param("label", "string")] })] })]; + const input = parseInput("body={items=[{label=a b},{label=c d}]}", [], { exactScalars: true }) as Record; + typeShorthandBySchema(input, params); + assert.deepEqual(input.body.items, [{ label: "a b" }, { label: "c d" }]); +}); + +test("a nullable field written null becomes null, a field that is not nullable keeps the text, and so does a JSON string", () => { + const params = [param("query", "object", { properties: [param("orgId", "integer", { nullable: true }), param("note", "string", { nullable: true }), param("plain", "string")] })]; + const shorthand = parseInput("query={orgId=null,note=null,plain=null}", [], { exactScalars: true }) as Record; + typeShorthandBySchema(shorthand, params); + assert.deepEqual(shorthand.query, { orgId: null, note: null, plain: "null" }); + const json = parseInput('{"query":{"orgId":"null","note":"null"}}', [], { exactScalars: true }) as Record; + typeShorthandBySchema(json, params); + assert.deepEqual(json.query, { orgId: "null", note: "null" }); // from JSON, "null" is a string, as it was written + const real = parseInput('{"query":{"orgId":null}}', [], { exactScalars: true }) as Record; + typeShorthandBySchema(real, params); + assert.equal(real.query.orgId, null); +}); + +test("typeShorthandBySchema ignores a value that is not an object, a field the schema doesn't list, and a bracketed value", () => { + assert.doesNotThrow(() => typeShorthandBySchema(undefined, [])); + assert.doesNotThrow(() => typeShorthandBySchema(["x"], [param("a", "string")])); + const input = parseInput("body={title=a b,extra=c d,list=[x,y]}", [], { exactScalars: true }) as Record; + typeShorthandBySchema(input, [param("body", "object", { properties: [param("title", "string"), param("list", "string")] })]); + assert.equal(input.body.title, "a b"); + assert.deepEqual(input.body.extra, ["c", "d"]); // not in the schema: left as parsed + assert.deepEqual(input.body.list, ["x", "y"]); // written as a list: not a plain string +});