diff --git a/README.md b/README.md index 6691a05..b84a52e 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ deel dev logs list --status_class 4xx --beta # your organization's failed - [Webhooks](#webhooks) - [OAuth2 apps](#oauth2-apps) - [API versions](#api-versions) +- [Web-app actions](#web-app-actions) - [Environments](#environments) - [Beta endpoints](#beta-endpoints) - [Corporate proxies & custom CAs](#corporate-proxies--custom-cas) @@ -322,7 +323,7 @@ Only `y` or `yes` (any case) goes on. `n`, an empty line, Ctrl-D, or no answer w ## Idempotency -Every mutating request (`POST`/`PUT`/`PATCH`/`DELETE`) carries an `Idempotency-Key`. By default each run of a command gets a **new random key** (UUIDv4), and the CLI's own retries of that request (on `429` or `5xx`) reuse it, so a retried request runs at most once. Running the same command again is a new operation: `disable`, `enable`, `disable` ends disabled, and two identical `create` runs create two resources. +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 each run of a command gets a **new random key** (UUIDv4), and the CLI's own retries of that request (on `429` or `5xx`) reuse it, so a retried request runs at most once. Running the same command again is a new operation: `disable`, `enable`, `disable` ends disabled, and two identical `create` runs create two resources. To make a re-run a safe retry of an earlier run, for example after a timeout left you unsure whether it went through, pass the same key both times with `--idempotency-key ` (see the key with `--debug`). Within 24 hours the API then answers a repeated `POST`, `PUT` or `PATCH` with the first response instead of running it again. A key reused for a different request (another method, path or body) is rejected with `409 IDEMPOTENCY_KEY_REUSED`. The exception is a call that must act every time it runs, such as `deel webhooks test`: it is sent once, with no retry and no automatic key (an explicit `--idempotency-key` is still sent). @@ -398,6 +399,27 @@ deel oauth2-apps listings submit --beta `update` saves a draft and changes only the fields you send; each list you send (`highlights`, `support_resources`, `works_with`, `what_it_syncs`, `categories`) replaces the current one. `deel oauth2-apps listings update --help` lists every field. Test account details are accepted and never printed back. A listing in review cannot be changed (409) until the review ends; read `latest_revision.review_notes` after a rejection, edit, and submit again. A draft shows the logo you saved, but the listing goes live in the App Store only once Deel approves it. +## 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; --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}' +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. 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. 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 ...`). + +**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 | @@ -449,7 +471,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, these values are masked as `***`: credentials (keys such as `token`, `password`, `secret`, `signature`), and every response field the API definition marks as personal or employment data. Which fields carry that mark is decided by the owner of each endpoint, and the CLI follows it for that field of that endpoint's response, and the same name elsewhere is logged as it is. A link (a key named `url`, `link`, `href`...) is logged without its query string and fragment, where a pre-signed link keeps its signature. The request's own query string is never written to the log, with or without `--log-bodies`; the URL in `--debug` output and in a timeout or TLS error masks the values of credential query parameters. Whatever its key, a value that is an email address or a JWT (a `?q=` search, a free-text `note`) is masked too. Names of people and companies, record ids, dates and amounts of a contract stay, so the log still says what was called. A field the API definition has not marked is logged as it is, and the responses of the `auth` and `job` commands carry no field marks, so a response body may still contain personal data: 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, these values are masked as `***`: credentials (keys such as `token`, `password`, `secret`, `signature`), and every response field the API definition marks as personal or employment data. Which fields carry that mark is decided by the owner of each endpoint, and the CLI follows it for that field of that endpoint's response, and the same name elsewhere is logged as it is. A link (a key named `url`, `link`, `href`...) is logged without its query string and fragment, where a pre-signed link keeps its signature. The request's own query string is never written to the log, with or without `--log-bodies`; the URL in `--debug` output and in a timeout or TLS error masks the values of credential query parameters. Whatever its key, a value that is an email address or a JWT (a `?q=` search, a free-text `note`) is masked too. Names of people and companies, record ids, dates and amounts of a contract stay, so the log still says what was called. A field the API definition has not marked is logged as it is, and the responses of the `auth` and `job` commands carry no field marks, so a response body may still contain personal data: 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). @@ -463,6 +485,7 @@ Location: `~/Library/Logs/deel/deel.log` (macOS), | `DEEL_CLI_BASE_URL` | Override the API base URL (https only); `--base-url` beats it, it beats `--env`/`DEEL_ENV` | | `DEEL_ONE_TIME_SECRET` | The one-time secret `files status get` and `files update` send as `x-one-time-secret`; `--one-time-secret` beats it | | `DEEL_UPLOAD_METHOD` | `multipart` to ask `files create` for a multipart upload; `--upload-method` beats it | +| `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 | @@ -517,7 +540,7 @@ src/ manifest.generated.ts # hand-picked command descriptors (generated by the deel-cli-extractor skill — never hand-edited) commands.map.ts # hand-picked command ↔ API endpoint mapping public-api/ # generated public API commands: manifest.json (never hand-edited), commands.json (the command map), domains.json (optional: each domain's description for help; its stage orders `deel --help`, and a domain it does not list comes last), loader - commands/ # static commands (auth, job, commands) + commands/ # static commands (app, auth, job, commands) 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 df9fb58..c01c206 100644 --- a/scripts/doctor-hashes.json +++ b/scripts/doctor-hashes.json @@ -18,7 +18,7 @@ "CLAUDE.md": "b06874c1143c15a838c286d1108588737b45a5405b2b4e18bc36c15c72558aa1", "CONTRIBUTING.md": "e0e6149c404729351a3f1db3fbd6ef7206602602c2484ec63a4f89d7297fdf47", "LICENSE": "6b2cb5591852863e1ac403b8fd7ec8c706de863bc1a737888322e9bf604af656", - "README.md": "269552158a972608cf1a8387f040923cac3eda4bd067acfcf5c53130cef7148b", + "README.md": "4800a6b9dcfd093d36332002b4335a19d3f9c49133ebc41511b14bbbad7912f5", "SECURITY.md": "6ad03fd32443e1dd7270e27180b5dfa6684826311543ae60b1cc6f937f9bcc53", "package-lock.json": "c66ea4ccbeb2a7393cdfa4ed87cee082ee8b9174fff0934a368c874136d1030f", "package.json": "7fa2b65175440d7ac0fd66e1359f3124ad2362a088680a930737ec351a984cc4", @@ -41,39 +41,42 @@ "scripts/sign-darwin.sh": "926161b0dcd0706c25c1fb95206f50a7a7fbc7e9ec5d9b46566b80cfd8f8df1a", "src/cli.ts": "40469644d0a0a2b6d38ad407b155b4c9cf3317797d13641d7ffc87ee4e435a8b", "src/commands.map.ts": "71540a126094af88815c46dba823273b75e292edad33f266e82e5be1fb014b2c", + "src/commands/app.ts": "41a26c7b4c567d5cb916123adf153b75426e7784cbe8241be2250fa818384c5a", "src/commands/auth.ts": "e9c46ba0de2ef0bbb36b6054151db78f354bf5de1fccd229ecb4f8960c64f54c", "src/commands/commands.ts": "9df650467599e5b0d8fa1594584e0943b9385e4c820938ae9c88d3dde4b67c94", - "src/commands/index.ts": "04f025f68425362b10e28e3a19e510cf1f10e5caf243d3f932fb35ca68f71c6f", + "src/commands/index.ts": "eafeaca796b6810e568c95b0267efdb554eacac7cd2990ea3ed7476b0f3d0f84", "src/commands/job.ts": "3ee0f3a0c52b4619d78572d663464d9ddca8c461a2f3db6e7f7125c56f866fc8", "src/commands/shared.ts": "448037d2b8717de774e0ce29acb5ba4aa591524ce7b797e1cabfd9464a76ebc0", "src/commands/tokens.ts": "__deleted__", "src/commands/webhooks.ts": "__deleted__", "src/core/api-tokens.ts": "__deleted__", - "src/core/auth.ts": "3faea02ba891867cfe2a65a640f0ea3e96bf091871cd31b68d8d70528c67e872", + "src/core/app-actions.ts": "60af4f2c5ab4e46c85a34f2781f78e5bf60f2e18992d57d3492e5197a31339a8", + "src/core/auth.ts": "8f8c28ead8c6d50de222f8447a44daf2e58c25eb2897388fbb79e35bc9616768", "src/core/commands-list.ts": "7a6f7f88df6b79b347d7858de52a8042528f40cfd8089df2088cceeff63299cc", - "src/core/config.ts": "a575a50063a04047a7e2da121af34c5f94e50002ad6e1543e96bbe7babe46f04", + "src/core/config.ts": "876ed6d2507c61e2924ce5dc001bc7486774918ebec963937182765b541c61dc", "src/core/confirm.ts": "8dcef9eb669bce437192b07341b82ee34b35ec95b6356c1e170fc3803afacd18", - "src/core/constants.ts": "c3cbc372e07693bf16e6ba69ab2d1aa1f2d1f32d0094b6b4f27a82e03166d2f5", + "src/core/constants.ts": "02e5444f596d70ac01b17e11d22856ff63ec7b7bee3b50646926d9165b973d3f", "src/core/context.ts": "51c93a4d1e9cf5d8b8f0bbce4f8cebee26bdc81c441c1acff72aab674df0a4e7", - "src/core/errors.ts": "7a1d4709cc635898875a59f66828fa604ae65801abd1baa98b8c948978f98030", + "src/core/errors.ts": "405420d32720a12dd4460db09ea811ffdfc6090d712b58bc04b5497fe36b69b0", "src/core/executor.ts": "76bdeb60b036fa621e89d84c2301e341ec1f9dd4bdbcd1e9be6b3dae295423d1", "src/core/flags.ts": "270d3903ea3bb847e1295281ca1c49e9dd8a4aeade2e748bd8273aff50725559", - "src/core/http.ts": "2f00e69f03e2a7573cd184f8ab7e8363a33ceef4b057d932ccad964ee467a48e", + "src/core/http.ts": "6b2ba42bfcdc236e2ba8df057ae9e43fe94a3e30d959048fd8750c7689a9bb41", "src/core/idempotency.ts": "5f2a36a56d6ea36a4f92689253b2a8ab0c4c29c8b42833253a449f1ec58cb413", - "src/core/input.ts": "0e70d9b10d2fe2ccf2dc93350a4699007c16c951618a1c95a8909027200239a5", - "src/core/io.ts": "85bd4349a8ccb8f0b36369b98d16396387539790e60f615dfbaded93b1024fa8", + "src/core/input.ts": "47db0b4237623658423c386a909a71db31b181a8034a2b2dce21732cb2ba1d3c", + "src/core/io.ts": "7e8aaeebbfd5b6701a80a6e409d8bad19cceb6811092e5db0c811aff22b1474f", "src/core/jobs.ts": "4e56106ce2d828c3a78012250619be1cb1c397afc3054c5a9d19bd190c8e88d2", "src/core/keychain.ts": "2cadcb12e7524ec706a28c2c9e19378f06ca3c64aec63141f3ba52fa6e4817dc", "src/core/logging.ts": "4d841279a296661715b4f75e2940f8ec65f73a99b2e26ea77b9e5311f8273f56", + "src/core/mcp.ts": "3fdf2ff2b142ba76d7fe9e3d37565a26e109a5e653086828595c413469d9dbc1", "src/core/oauth-login.ts": "e9a7fc426ddae13c5b154ed6d2e659f3ab8f1ca952c058e94685f86eb2977a13", - "src/core/oauth.ts": "1a4938658335b1a2ee6490e2f6c19ecb571c7a9228c5a0d6db087a2ec4bcc0d5", - "src/core/output.ts": "6cbabb060da4c72ca9d7c81870dd75bf6d83c79af35c1c75fecd246b48faa229", + "src/core/oauth.ts": "671aabeae339c80a08d42c796b2014cd4679e95bd05488c7962e077fc87a912c", + "src/core/output.ts": "0aeebcabb4aafe7538b721d22342e7ecea5fe1fdad0ed9d9b98a72e7e705e301", "src/core/prompt.ts": "1a7339a12cc9d09237b096a2d27b89d12f00193dd7829dc23216696e1775a9fe", "src/core/tls.ts": "c06f0d810e91f0a7e959f2363750871d6e5e67edcf00ac3a9a05c2ba7fce9f65", "src/core/versions.ts": "17a2c2a987ad5c94290eae3ef4d14979d8ee997b23142d3a1c6f220d9535f390", "src/core/webhooks.ts": "__deleted__", "src/help.ts": "b77f7b62f19af750a558b9a876c7fecc8e4809e0c4de65013bbba6fc7b93062f", - "src/main.ts": "0c52f2a373becfa4af669692b25c9ae912495a4a5152ac90c46ceedc9de5c243", + "src/main.ts": "7a0354ddd1bf5c73c860e56fbbfb44893fe9fb591cb6bb8c1f6cbac18169236d", "src/manifest.generated.ts": "3125bbdb16ce51dab0d62a8dca881c5b7c49b505ce67e6de3fd88dceb9819851", "src/public-api/commands.json": "375c92f856f958ee43542827c5e14fbfdabb92500843f1f1f852a6285314fea8", "src/public-api/commands.ts": "26c2f4ec039f9bf7f8b693aa7c860c0bcc04267cba2a7df5adf9581d3f933481", @@ -81,10 +84,12 @@ "src/public-api/manifest.json": "6e7a2e0ba715148e8cecf2dc7572bdf6a9cb2ce4efec76c6b97018ffe6c12da1", "src/types.ts": "22cd65a6c0e204deec85974fb46ed47570f0d405c041b09f779fc0af6e8b4121", "src/version.ts": "89734abe56c67870b5d3ad77b5703cfbd662697680ded300226308a8ac301d3d", + "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", - "test/auth.test.ts": "5fe488919641cebbe7859f14e7613e68c1f47ba45c705b76a534fc312b99e6d3", + "test/auth.test.ts": "9c3f8eb5f7fc64755361a1c41f5bce2952c9d6a006da38054a9aacdcaed6a8a3", "test/build-all.test.ts": "9d5cb432468a9b4194e8c583e912162376994439f928b0f376541a738830fbd3", "test/check-command-map.test.ts": "cc64726adcec927afd4c2d16b71e59ea5ea54cde589c9ee77f278a66b1824d1d", "test/check-doctor.test.ts": "4ae966ba51e61ab2d1a11655b344a1ecab0e57a4ea3f8d038c024d63405af145", @@ -95,11 +100,11 @@ "test/cli.test.ts": "89caaa8f3e8e3488cd5c81ef1d6cbd000ccc2aa6eea064068712e7d432bf911d", "test/command-map.test.ts": "2db1245ddb9280d1e8416616c5413383f89b0c2ff69698012b4e713e50dd6d88", "test/commands.test.ts": "f29d454614dcf20746c206c9fb808589fccaf03c1a89c9157f2d33710a769092", - "test/config.test.ts": "502d4432124c00ac52bf7331d9becc99c612342bb01448685641574609454f1a", + "test/config.test.ts": "d4a1b5665954af099fd0287f69ed30d9cf6dcf5dbbc9fe73d26cc857fc651fc6", "test/confirm.test.ts": "450a29341e14b76dbdac19d422fb4e599210c89849cf121099aaa123ddd1dd31", "test/constants.test.ts": "61cb4577e37fb709b39e6b6439a96d82e354b019e14a942396f1cb395e6c72ab", "test/definitions.test.ts": "421099257d3ba9e36770d2e0484317da9c31deb045b00a2c928873dc8de419ab", - "test/errors.test.ts": "b879d2048f46627864312ba2bd31209f6be41be3a2e3babfed3e2b91e26ccd79", + "test/errors.test.ts": "f9335ddac1b94be0c9b1bb8841dd41737fce698712a9382c5a7bbf014b9b6343", "test/executor.test.ts": "262576a9d8cae97001837c4831be5363cb5c70819af8c6a5f94f5551896a9c72", "test/extract.test.ts": "2a42bd4e6eae5bfd3b44f3c737df73bd04512d92443963b4c8c628be6ed83b84", "test/files.test.ts": "cc5f443f4b0967320179c8bab4a3cc166764429938fb8a12659089847af35424", @@ -110,20 +115,21 @@ "test/flags.test.ts": "178ec5c766be52489989b20b4e88c0135440a11423fea0808d0a1e6a7ffaddd4", "test/generate-public-api.test.ts": "e32e8b6313554c55987d1e99b04ee401743e3237bfa305947ce6490ba9a36c7e", "test/help-picking.test.ts": "3530643a943148bbeb2ac0b28a7303fdf9d4f0569c938a13975fba0327714b22", - "test/help.test.ts": "b9583fd4970ba5886aff309a60dae561e49b981a3bd5b7ee22e7a558d56793e2", - "test/http.test.ts": "de440abb96de971194039898371b3a4e6ff71cb8fc3dbef6e96b93780e15188a", + "test/help.test.ts": "0da411f2553ff3b8f5f820a52309ac22b13030a510d32f6809800c536cc6fa5f", + "test/http.test.ts": "f4f975b0f0c46b867d09711a27683398a9796c754ec30734aa9510d20ae2e2ff", "test/idempotency.test.ts": "bd8acc0105b3b361ba2f43e5622de651628574beab487c14bfc6a0fd91cb1618", - "test/input.test.ts": "b18c3c155937a36f83648e2cf83c2848aab17a05490a61135fdd5611ac446a56", + "test/input.test.ts": "0b8449322b04b3f665b4a20af843401f4e15e1a7cb91a861aa491da83181f595", "test/install.test.ts": "f68a3ee5f08eb2172e9c12823ed46e120ea156fc2695abc77626e32dd57b826e", - "test/io.test.ts": "8c443dce45eb6f6c23471ac626e7dad342ced8d22c4a08ae019749b1af9a8498", + "test/io.test.ts": "88e11df89fcdacdc9bbd3b46eec12125c4c9ea4f0a717d5840582542ad1759a6", "test/jobs.test.ts": "0a37b7204e5c5f9c2ffef3efa062256f6d1e061885189b2809698c3baf36bc13", "test/keychain.test.ts": "0f1fad8ae0d351ffecc051e551f0c5ad6e9be263e6ff1246589eae2dbf2f8856", - "test/logging.test.ts": "fc05ece649595332789915afa0f8a58d0558143bb7de57d32bdd2fa9bf0a732c", + "test/logging.test.ts": "5c7e5e5519637227e9dda1373ca2f194d3ac4f988d6ee54b01743396af2472b8", "test/macho-fixture.ts": "051b7218a565afb64d74a9ecb82c25b27ec1755505237da048ec7e9f26fdd9f5", - "test/main.test.ts": "89cd3d3b122ee1b7d27d8cc16045562ccbb4da03ea88394e61563609d435add3", + "test/main.test.ts": "2e65ba018cc232b1fa4615cdfc5103a383359f44aa5e551fff4024d9100d1c3e", + "test/mcp.test.ts": "cb595c66422d9d6b25b8a5bffec2c4636c6c3958c57794ce7518501c95f6269a", "test/oauth-login.test.ts": "79a7a405e30eb76c399361c44363fc1b8e580bf6c8d2f8095c811f4e99cfb78f", - "test/oauth.test.ts": "58837bf6de40f33b643fa988a6be1197cd2346d0415db448099e75042371eb03", - "test/output.test.ts": "5f9608231deca9fd11d6a05a55c39ad009b6e254ca4f88c825dc6f2c937f0584", + "test/oauth.test.ts": "bb8b09a1b557c8b19b6b8567f027a98831b9431ea609dc2a2bb19c20c4add582", + "test/output.test.ts": "93d3529fb971a10cd81627e6ecc3e8e0d7729b67c7957b150048e4ee3c681481", "test/prompt.test.ts": "0cad7ec79c8beb871ce0bed8683fa7acfbcdafc800466f3a75b70d9b5c7ca9d0", "test/public-api-commands.test.ts": "9994502a41e11442ffdfa33d224e20d99ed6d33d7d3d9aba51179e9b5752058d", "test/public-api-generate.test.ts": "02cd6f96ead9dc31de6fbd44bc94228289e070151201f69241e0e33860557571", diff --git a/src/commands/app.ts b/src/commands/app.ts new file mode 100644 index 0000000..a1aa6e0 --- /dev/null +++ b/src/commands/app.ts @@ -0,0 +1,206 @@ +// `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 } 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, 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"; +import type { CredentialStore } from "../core/keychain.ts"; +import { + SEARCH_MAX_LIMIT, + actionInput, + assertEligible, + beforeRequest, + createAppClient, + getAction, + inputSkeleton, + runAction, + runCall, + schemaParams, + searchActions, + truncationWarning, +} 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; 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, 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. + 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, + url, + newRequestId: ctx.newRequestId, + sleep: deps.sleep, + renew: oauth + ? async () => { + await oauth.renew(oauth.current().access_token); + return true; + } + : undefined, + }); + 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"] 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]) { + 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'."); + } + } +} + +// 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-/, ""))) { + 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"]; + +// 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; +} + +// 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 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."); + 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 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 })); + 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 }); + 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: ${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)); +} + +// `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, 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, + }, + run: (cittyCtx) => runRun(cittyCtx.args as Args, cittyCtx.rawArgs, deps), + }), + }, + }); +} + +export const appCommand = createAppCommand(); diff --git a/src/commands/index.ts b/src/commands/index.ts index e3a1258..ebe05b3 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 { createCommandsCommand } from "./commands.ts"; -export { authCommand, jobCommand }; +export { appCommand, authCommand, jobCommand }; // 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, commands: createCommandsCommand(() => staticCommands), diff --git a/src/core/app-actions.ts b/src/core/app-actions.ts new file mode 100644 index 0000000..eb47843 --- /dev/null +++ b/src/core/app-actions.ts @@ -0,0 +1,480 @@ +// 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, 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"; +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 = { + 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; +// 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"]); + +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 }; +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; +}; + +// 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)."); +} + +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; + const renewLogin = opts.renew ? () => beforeRequest(opts.renew!) : undefined; + 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 || !renewLogin) return false; + renewed = true; + 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 && renewLogin) { + renewed = true; + if (await renewLogin()) { + 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 !== 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); +} + +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); +} + +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; + } +} + +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 }> { + 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); + 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 }> { + const result = await client.call(APP_TOOL.get, { name }, { retryable: true }); + if (result.isError) failed(result, { action: name }); + 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 (!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; +} + +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; +} + +// 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. +// 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, 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) : {}; + 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 === "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" ? exactNumber(value.trim(), number) : Number.isSafeInteger(number)) return number; + } + return value; +} + +export function coerceInput(input: ActionInput, schema: JsonSchema | undefined): ActionInput { + 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 as Record } : {}), + ...(query !== undefined ? { query: query as Record } : {}), + ...(input.body !== undefined ? { body: coerceValue(input.body, schema?.properties?.body, false) } : {}), + }; +} + +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) } }; +} + +// 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 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); + } catch { + /* not JSON: keep the text */ + } + 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) => + !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; + 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 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 send(client, call); + } + if (result.isError) failed(result, context(call.tool)); + return runOutcome(result); +} + +// ---------------- 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 (!isRecord(schema)) return ""; + if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0]; + 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(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 187d126..5bd7ff1 100644 --- a/src/core/auth.ts +++ b/src/core/auth.ts @@ -130,15 +130,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 8fb2f3a..9bc5c05 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -104,6 +104,28 @@ 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. 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); + 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 base URL for a command's API. REST uses the configured base as is; SCIM swaps a // trailing /rest for /scim (or appends /scim to a --base-url without one). export function apiBaseUrl(baseUrl: string, api: Api | undefined): string { diff --git a/src/core/constants.ts b/src/core/constants.ts index 9ef977b..3118cdf 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; @@ -72,10 +79,10 @@ export const AGENT_ENV_SIGNALS = ["CI", "CLAUDE_CODE", "CURSOR", "CODEX"] as con // fails when src reads a DEEL_ variable that is not listed here. export const CLI_SETTING_ENV = [ "DEEL_TOKEN", "DEEL_CLI_BASE_URL", "DEEL_ENV", "DEEL_CA_CERT", "DEEL_CERT_STORE", "DEEL_LOG", "DEEL_LOG_BODIES", "DEEL_LOG_DIR", - "DEEL_LOG_MAX_FILES", "DEEL_LOG_MAX_SIZE", "DEEL_OAUTH_CLIENT_ID", "DEEL_OAUTH_ISSUER", "DEEL_TLS_RETRY", + "DEEL_LOG_MAX_FILES", "DEEL_LOG_MAX_SIZE", "DEEL_MCP_URL", "DEEL_OAUTH_CLIENT_ID", "DEEL_OAUTH_ISSUER", "DEEL_TLS_RETRY", ] as const; -export const RESERVED_COMMANDS = new Set(["job", "auth", "commands"]); +export const RESERVED_COMMANDS = new Set(["job", "auth", "commands", "app"]); export const COMMAND_SUFFIX_MODIFIERS = ["-bulk", "-async"]; // --- Header names (lowercase; fetch normalizes) --- diff --git a/src/core/errors.ts b/src/core/errors.ts index b52f2e9..2a9b36c 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; @@ -54,3 +65,12 @@ export function usageEnvelope(err: { message?: string }): ErrorEnvelope { next: "Run the command with --help to see its arguments and flags.", }; } + +// 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) }; + if (isParserError(err)) return { error: usageEnvelope(err as Error) }; + const message = (err as { message?: string } | null | undefined)?.message ?? String(err); + return { error: { code: "unexpected", message } }; +} diff --git a/src/core/http.ts b/src/core/http.ts index d11b37e..f311cb9 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"; @@ -18,6 +18,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; responseFields?: CliParam[]; // the endpoint's response fields, so the log masks the ones the spec marks sensitive }; @@ -42,6 +44,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 +68,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} ${maskUrlQuery(request.url)}`); if (isCertError(error)) throw new CliError("network.tls", `TLS verification failed: ${maskUrlQuery(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); } @@ -152,6 +160,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 ?? {}), @@ -162,7 +171,7 @@ export function withLogging(logger: Logger, clock: () => number): Middleware { duration_ms: clock() - startedAt, headers: redactHeaders(request.headers), }; - if (withBodies) entry.response = maskMarkedFields(response.json, request.responseFields); + if (logBody) entry.response = maskMarkedFields(response.json, request.responseFields); logger(entry); return response; }; diff --git a/src/core/input.ts b/src/core/input.ts index f012c44..ed2de70 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", @@ -82,7 +84,7 @@ function unescape(text: string): string { // (007 stays 007, a b c stays one string). Values written as {..} or [..] have no entry. const RAW_TEXT = new WeakMap>(); -function parseShorthandObject(text: string): Record { +function parseShorthandObject(text: string, exact: boolean): Record { const result: Record = {}; const raw = new Map(); RAW_TEXT.set(result, raw); @@ -94,7 +96,7 @@ function parseShorthandObject(text: string): Record { } const key = unescape(pair.slice(0, equalsIndex).trim()); const valueText = pair.slice(equalsIndex + 1).trim(); - result[key] = parseValue(valueText); + result[key] = parseValue(valueText, exact); // Only a value parseValue turned into an object or list has no raw text; "[x] text" is a plain string. A later // duplicate key replaces the value, so it replaces the raw text too. if (isBracketed(valueText)) raw.delete(key); @@ -138,27 +140,29 @@ function isBracketed(text: string): boolean { return false; } -function parseValue(raw: string): unknown { +function parseValue(raw: string, exact: boolean): unknown { const value = raw.trim(); if (isBracketed(value)) { - if (value.startsWith("{")) return parseShorthandObject(value.slice(1, -1)); + if (value.startsWith("{")) return parseShorthandObject(value.slice(1, -1), exact); 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 parts.map((part) => parseScalar(unescape(part.trim()), exact)); } - return parseScalar(unescape(value)); + return parseScalar(unescape(value), exact); } -// Heuristic scalar coercion for nested values (top-level is re-coerced against the schema). -function parseScalar(text: string): unknown { - if (text === "true") return true; - if (text === "false") return false; - if (text !== "" && !Number.isNaN(Number(text)) && /^-?\d+(\.\d+)?$/.test(text)) return Number(text); +// Heuristic scalar coercion for nested values (top-level is re-coerced against the schema). With `exact`, numbers +// 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 (!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; } @@ -186,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/src/core/io.ts b/src/core/io.ts index a32d78c..8ad3cdd 100644 --- a/src/core/io.ts +++ b/src/core/io.ts @@ -4,7 +4,7 @@ import { readFileSync } from "node:fs"; import { isatty } from "node:tty"; -import { AGENT_ENV_SIGNALS } from "./constants.ts"; +import { AGENT_ENV_SIGNALS, FORCED_EXIT_MS } from "./constants.ts"; export type IOStreams = { out(text: string): void; @@ -42,6 +42,30 @@ export function realIO(): IOStreams { }; } +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; canPrompt?: 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..2941419 --- /dev/null +++ b/src/core/mcp.ts @@ -0,0 +1,151 @@ +// 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, MCP_ACCEPT } from "./constants.ts"; +import type { Transport } from "./http.ts"; + +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; // absent when the server's payload carries none + 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 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")) { + // 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 { + const message = asMessage(JSON.parse(data)); + return message ? [message] : []; + } 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 = asMessage(JSON.parse(text)); + // A reply to another request is not ours; one without an id is taken as ours. + return message && (message.id === undefined || message.id === id) ? 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, + // 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 }, + }); + + 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 (/-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); + } + + // 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); + 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 : undefined; + const message = printable(payload.message ?? result.texts[0], "The tool call failed."); + return { ...(statusCode !== undefined ? { 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 2423341..ea79674 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/inline"); - 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 4a985df..6bde052 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,27 +2,17 @@ // DeelCLI entry point. Runs directly under Node 22 (type-stripping) or Bun. import { run } from "./cli.ts"; -import { CliError, EXIT, isParserError, toEnvelope, usageEnvelope } from "./core/errors.ts"; +import { CliError, EXIT, failureEnvelope } 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) => { - // Not process.exit: it can cut off stdout still queued on a pipe, e.g. a large JSON result piped to jq. - process.exitCode = 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); - } - if (isParserError(err)) { - process.stderr.write(JSON.stringify({ error: usageEnvelope(err as Error) }, null, 2) + "\n"); - process.exit(EXIT.ERROR); - } - process.stderr.write(JSON.stringify({ error: { code: "unexpected", message: (err as Error).message } }, null, 2) + "\n"); - process.exit(EXIT.ERROR); + // 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 new file mode 100644 index 0000000..4e76e94 --- /dev/null +++ b/test/app-actions.test.ts @@ -0,0 +1,499 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { RETRY_MAX_ATTEMPTS } from "../src/core/constants.ts"; +import { + APP_TOOL, + actionInput, + appError, + assertEligible, + beforeRequest, + coerceInput, + createAppClient, + getAction, + inputSkeleton, + runAction, + runCall, + runOutcome, + schemaParams, + 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"; +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"; + +// 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); +}); + +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", () => { + 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"); + // 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."); +}); + +// ---------------- 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('{"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", "{}", '{"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")); +}); + +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"); + 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)); +}); + +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("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("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" } }); +}); + +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); + 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 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("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"))) }; + 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" }); + 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 } }); +}); + +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", () => { + 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 } }); +}); + +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", + 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 new file mode 100644 index 0000000..2a2a03f --- /dev/null +++ b/test/app.test.ts @@ -0,0 +1,393 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { TestContext } from "node:test"; +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 { 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, canPrompt: 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("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, [{ 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("--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")); + 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, [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 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 })); + 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); + + 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) => { + 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("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(); + 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, []); +}); + +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("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":[]}'] })); + 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); + // 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|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, -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", "-h", "-", "-5", "--", "--weird", "-x"], deps(ok, loggedIn(), captureIO().io)); +}); + +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", () => { + 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 98f039c..f4b60a4 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"; @@ -260,6 +260,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/config.test.ts b/test/config.test.ts index 781e479..85bca99 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,6 +1,6 @@ import { test, before, after } from "node:test"; import assert from "node:assert/strict"; -import { apiBaseUrl, resolveConfig, requireIssuer, ENVIRONMENTS } from "../src/core/config.ts"; +import { apiBaseUrl, resolveConfig, resolveMcpUrl, requireIssuer, ENVIRONMENTS } from "../src/core/config.ts"; import { configFrom } from "../src/commands/shared.ts"; import type { CliError } from "../src/core/errors.ts"; @@ -155,6 +155,36 @@ test("configFrom wires the --beta flag into the config", () => { 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"); + }); +}); + test("SCIM commands call the sibling /scim base path", () => { assert.equal(apiBaseUrl(ENVIRONMENTS.prod.baseUrl, "scim"), "https://api.letsdeel.com/scim"); assert.equal(apiBaseUrl(ENVIRONMENTS.demo.baseUrl, "scim"), "https://api-staging.letsdeel.com/scim"); diff --git a/test/errors.test.ts b/test/errors.test.ts index b066f63..3107f15 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, isParserError, stripAnsi, toEnvelope, usageEnvelope } from "../src/core/errors.ts"; +import { EXIT, CliError, failureEnvelope, isParserError, stripAnsi, toEnvelope, usageEnvelope } from "../src/core/errors.ts"; test("exit codes are binary: success and error", () => { assert.equal(EXIT.OK, 0); @@ -25,6 +25,21 @@ test("CliError carries code and optional next; detail lives in the envelope", () 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" }); + const next = "Run the command with --help to see its arguments and flags."; + assert.deepEqual(failureEnvelope(cittyUsage), { error: { code: "usage", message: "Missing required argument: ID", next } }); + assert.deepEqual(failureEnvelope(Object.assign(new Error("bad"), { code: "EARG" })), { error: { code: "usage", message: "bad", next } }); + + 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" } }); +}); + test("stripAnsi removes colour codes and leaves plain text alone", () => { assert.equal(stripAnsi("\u001b[36m--limit\u001b[39m (\u001b[36mx\u001b[39m)"), "--limit (x)"); assert.equal(stripAnsi("\u001b[1;31mbold red\u001b[0m"), "bold red"); diff --git a/test/help.test.ts b/test/help.test.ts index d40b5c5..914d627 100644 --- a/test/help.test.ts +++ b/test/help.test.ts @@ -67,7 +67,7 @@ test("root help lists one line per top-level word, the word first, with no stage assert.doesNotMatch(out, /^ {2}(CLI|People|Hiring|Platform|Other)\b {2,}/m, "no stage column"); // The static commands first, then the lifecycle order of domains.json (People, Hiring, Pay, Platform), by name within a stage. // Alphabetical order of the words alone would put `contracts` before `people`. - assert.deepEqual(rootWords(out), ["auth", "commands", "job", "people", "contracts", "adjustments", "jobs", "scim"]); + assert.deepEqual(rootWords(out), ["app", "auth", "commands", "job", "people", "contracts", "adjustments", "jobs", "scim"]); assert.match(out, /^GLOBAL OPTIONS/m); } }); diff --git a/test/http.test.ts b/test/http.test.ts index 87f064c..e1b44fc 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 { 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 }); @@ -144,3 +145,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 4df2d81..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[] = [ @@ -121,6 +121,15 @@ 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 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"] }, + }); + assert.deepEqual(parseInput("a={n=5,on=true}", []), { a: { n: 5, on: true } }); // the default is unchanged +}); + test("a backslash escape in a string field is applied once to the text", () => { assert.deepEqual(parseInput("reason=a\\,b c", props), { reason: "a,b c" }); }); @@ -177,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 +}); diff --git a/test/io.test.ts b/test/io.test.ts index f2a120d..cef9c5d 100644 --- a/test/io.test.ts +++ b/test/io.test.ts @@ -1,7 +1,62 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; import { isatty } from "node:tty"; -import { canPromptFrom, captureIO, isAgentEnv, realIO } from "../src/core/io.ts"; +import { fileURLToPath } from "node:url"; +import { FORCED_EXIT_MS } from "../src/core/constants.ts"; +import { canPromptFrom, captureIO, exitAfterFlush, isAgentEnv, realIO } 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 nobody is reading yet still arrives whole", { timeout: 30_000 }, async () => { + const size = 300_000; // well past the 64 KB a pipe holds + // 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); +}); test("canPromptFrom: a person can answer only when stdin and stderr are both terminals", () => { assert.equal(canPromptFrom(true, true, {}), true); diff --git a/test/logging.test.ts b/test/logging.test.ts index 66231fb..d59a7ea 100644 --- a/test/logging.test.ts +++ b/test/logging.test.ts @@ -39,6 +39,15 @@ test("withLogging includes the response body when body logging is opted in, and 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 credential keys by substring (access_token, password, refresh_token) and leaves other names to the spec's marks", () => { 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 index 34cf889..fb30642 100644 --- a/test/main.test.ts +++ b/test/main.test.ts @@ -2,16 +2,43 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn, 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]" } }); +}); + const FLOOD = fileURLToPath(new URL("./fixtures/flood-stdout.mjs", import.meta.url)); const FLOOD_BYTES = 300_000; // well past the 64 KB a pipe buffers // Runs the real entry point; argument errors are refused before any request, so no network is touched. function runMain(args: string[], env: Record = {}) { + // NO_COLOR is dropped, not set empty: Node prints a warning on stderr when both it and FORCE_COLOR are set, and the + // process now ends on its own (it no longer calls process.exit), so that warning would land beside the envelope. + const { NO_COLOR: _noColor, ...inherited } = process.env; return spawnSync(process.execPath, [MAIN, ...args], { encoding: "utf8", - env: { ...process.env, ...env, NO_COLOR: "", FORCE_COLOR: "1" }, + env: { ...inherited, ...env, FORCE_COLOR: "1" }, }); } diff --git a/test/mcp.test.ts b/test/mcp.test.ts new file mode 100644 index 0000000..d7cf52c --- /dev/null +++ b/test/mcp.test.ts @@ -0,0 +1,159 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +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"; + +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("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("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 }); + 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("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"); +}); + +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)"); +}); + +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 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." }); +}); 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 868911b..1ebca4b 100644 --- a/test/output.test.ts +++ b/test/output.test.ts @@ -99,6 +99,12 @@ test("render --jq and --quiet keep operating on data only (page is not printed)" 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"); +}); + test("jq is loaded from the inline build so a compiled binary carries the wasm", () => { const source = readFileSync(new URL("../src/core/output.ts", import.meta.url), "utf8"); assert.match(source, /import\("jq-wasm\/inline"\)/);