@the-staq/tradestaq-mcp 0.3.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/README.md +16 -4
- package/VERSION +1 -1
- package/dist/api.d.ts +19 -3
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +140 -15
- package/dist/api.js.map +1 -1
- package/dist/config.d.ts +4 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +24 -14
- package/dist/config.js.map +1 -1
- package/dist/helpers.d.ts +23 -0
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +48 -8
- package/dist/helpers.js.map +1 -1
- package/dist/index.js +54 -34
- package/dist/index.js.map +1 -1
- package/dist/request-context.d.ts +25 -0
- package/dist/request-context.d.ts.map +1 -0
- package/dist/request-context.js +7 -0
- package/dist/request-context.js.map +1 -0
- package/dist/tools/auth.d.ts +1 -1
- package/dist/tools/auth.d.ts.map +1 -1
- package/dist/tools/auth.js +99 -13
- package/dist/tools/auth.js.map +1 -1
- package/dist/tools/backtest.d.ts.map +1 -1
- package/dist/tools/backtest.js +34 -15
- package/dist/tools/backtest.js.map +1 -1
- package/dist/tools/bot.d.ts.map +1 -1
- package/dist/tools/bot.js +816 -56
- package/dist/tools/bot.js.map +1 -1
- package/dist/tools/copy-trading.d.ts.map +1 -1
- package/dist/tools/copy-trading.js +22 -13
- package/dist/tools/copy-trading.js.map +1 -1
- package/dist/tools/market.d.ts.map +1 -1
- package/dist/tools/market.js +56 -12
- package/dist/tools/market.js.map +1 -1
- package/dist/tools/portfolio.d.ts.map +1 -1
- package/dist/tools/portfolio.js +23 -12
- package/dist/tools/portfolio.js.map +1 -1
- package/dist/tools/strategy-lab.d.ts +28 -0
- package/dist/tools/strategy-lab.d.ts.map +1 -0
- package/dist/tools/strategy-lab.js +264 -0
- package/dist/tools/strategy-lab.js.map +1 -0
- package/dist/tools/strategy.d.ts.map +1 -1
- package/dist/tools/strategy.js +168 -15
- package/dist/tools/strategy.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,103 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **`update_bot` edits the whole bot.** New fields: `name`; `strategyId` (ID or slug, resolved through the strategy route); `presetId` (ID or slug, applied by the server: the preset's strategy, parameter overrides, timeframe, execution mode / interval and version, with explicit fields on top); `versionChannel` and `pinnedVersionId`; `timeframe`; `executionMode` and `spinIntervalSeconds`; `parameterOverrides` (merged into the current ones, `null` removes a key) and `resetParameterOverrides`. Everything goes in one PATCH, so a strategy switch is never half-applied.
|
|
7
|
+
- **Merge rules.** `spinConfig` is fetched and merged like `positionSizing` (only the explicit keys go with a preset, so the preset's fill the rest). Parameter overrides merge onto the bot's current ones on the same strategy; a strategy switch starts from none and also clears the old preset and pin (stable channel unless given). Size and leverage are only sent when `positionSizePercent` / `leverage` are given.
|
|
8
|
+
- **Flat-only changes.** A strategy or timeframe change on a bot that holds a position (GET's `openTradesCount` / `openPosition`) is refused with `OPEN_POSITION` before anything is sent; the server's own 409 `OPEN_POSITION` (it also counts working orders) comes back with the same advice: pause with `stopAfterClose: true`, wait until flat, retry.
|
|
9
|
+
- **Result.** Every edit except a `stopAfterClose`-only call now returns JSON: `message`, the resulting `bot` config read back from GET /api/bots/:id (strategy id and name, version channel and the version it runs, preset, timeframe, mode, interval, up to 40 parameter overrides, sizing, status, paper/live, open position) and the server's `warnings` (e.g. candle history supply), plus a note to `start_bot` a paused bot after a switch.
|
|
10
|
+
- **Scope.** Unchanged and server-enforced: a paper bot needs `mcp:paper`, any change to a live bot `mcp:live`. An `INSUFFICIENT_SCOPE` on a live bot says so.
|
|
11
|
+
- README lists `start_bot` and `delete_bot`.
|
|
12
|
+
- Ship this only after the TradeStaq web release with PATCH `applyPreset` and the strategy-switch guard is live. Against an older server a `presetId` call fails with `PRESET_UNSUPPORTED` (the server ignores the field) instead of reporting success, and the client-side open-position check still blocks a switch on a holding bot.
|
|
13
|
+
|
|
14
|
+
## [0.5.0] - 2026-10-14
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- **`get_bot_logs`.** Explains what a strategy bot has been doing run by run. Sections (`include`, default `runs` + `spinLogs`): `runs` from the new GET /api/bots/:id/runs (outcome kind `k` = skipped_bar / skipped_other / no_signal / signal_queued / signal_dropped / error, reason code, bar, price, emitted / queued / dropped counts, `why` codes, folded skip count, executor result, spin number and run duration, plus pending skips, last spin (`at`, `status`, `nextAt`, `lastProcessedCandle`) and early-exit counts by UTC day and reason code for today and yesterday), `spinLogs` (stored per-run records) and `live` (recent in-memory runs with each run's outcome in the same format, and today's summary). `limit` 1-100 (default 25) and an optional `kind` filter for runs. The three requests run in parallel and each section reports its own error, so one failing route does not hide the others. Output fields are allowlisted: raw worker log text, state tokens, job ids, balances and stack traces are never returned, and `err` / error messages are cut at 300 characters. An unknown outcome kind is dropped.
|
|
18
|
+
- **`update_bot` `stopAfterClose`.** `true`: the bot keeps managing its open position (SL/TP, DCA exits, strategy exits, close signals), opens no new entries, and pauses itself once flat (immediately if already flat), notifying the owner once; `false`: cancel. Only an active bot can be set, and any status change (start_bot / stop_bot) cancels it. It is sent as-is in the PATCH body, so a `stopAfterClose`-only call no longer does the fetch-and-merge GET first. The reply says whether the bot is waiting for its position to close or was already flat and is now in its resting status (`paused` for strategy bots, `stopped` for signal bots).
|
|
19
|
+
- **`deploy_bot` `timeframe`.** Optional. Leave it out and the bot trades on the strategy's own timeframe (nothing is sent, so the server picks it); pass one (e.g. `4h`) only to override that. Your plan may limit which timeframes you can use.
|
|
20
|
+
- **`get_bot_status` shows `stopAfterClose`** (`enabled`, `requestedAt`, `completedAt`) when the bot has it.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- **`deploy_bot` `name` is optional in practice.** Leave it out (or pass an empty one) and nothing is sent, so the server names the bot. Ship this only after the TradeStaq web release that gives unnamed bots a default name is live.
|
|
24
|
+
- **`stop_bot` text corrected.** It said the bot "stops opening new positions"; it actually stops the bot entirely and leaves its open positions unmanaged. It now points to `update_bot stopAfterClose` for a graceful stop.
|
|
25
|
+
- Ship `stopAfterClose` only after the TradeStaq web release with stop-after-close is live (older servers reject the field with `Field "stopAfterClose" is not allowed`).
|
|
26
|
+
- Ship `get_bot_logs` only after the TradeStaq web release with /api/bots/[id]/runs and the log-route auth fix is live (older servers have no /runs route, and the spin-logs / live-spins routes reject MCP tokens).
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- **Preset search on multi-pair runs (text only, no request changes).** `symbols` no longer says it is not combinable with `searchPresets`: once an admin prices the multi-pair preset search, every preset candidate is tested on every pair, each searched profile costs the per-profile price plus an extra charge per extra pair (under `presetSearch` / `costBreakdown.presetSearch` in the quoteId estimate, which already pass through), and it is billed only if the search finishes. Until then the server refuses it with `preset_search_single_pair_only`, as today.
|
|
30
|
+
- **`profilesThatFit` on `basket_too_slow`.** When a multi-pair run with `searchPresets` is too slow, the server now also says how many risk profiles still fit at the same pairs and window (`0` = drop `searchPresets`), and its message suggests searching fewer profiles. It is added to the allowlisted basket error details, so an agent is no longer steered only toward fewer pairs.
|
|
31
|
+
- Ship this only after the TradeStaq web release with the basket preset search is live.
|
|
32
|
+
|
|
33
|
+
### Fixed
|
|
34
|
+
- **`get_candles` returned nothing.** It sent `exchange` (the route only reads `exchangeId`, so every call was a 400) and read `data.candles` (the route returns `{ success, data: { candles } }`). It now always sends `exchangeId`; with no `exchange` given it uses your first active exchange account from /api/exchanges and falls back to the public `binance` feed only when you have none (a bare platform name makes the route pick any user's account of that name). It returns the `exchangeId` used, the latest candle's OHLCV fields only, and `usingFallback` / `fallbackExchange` (cut at 40 characters) when the server served public data instead.
|
|
35
|
+
- Tool count in README / package.json corrected to 46 (it still said 31).
|
|
36
|
+
- **Basket quote fields are shape-checked, not just allowlisted.** `quoteId` must be the server's UUID, `assets` 1-8 pair symbols (no whitespace, max 64 chars), `resolved` two ISO dates, `costBreakdown` only its numeric `experiments` / `perExperiment` / `presetSearch` and `perExtraAsset` (number or null), the counts finite numbers, and `presetSearch` only `requested` / `cost` / known `profiles`. Anything else is dropped, so server text can no longer reach the agent through these fields.
|
|
37
|
+
- **Basket 400 codes are allowlisted.** Only the codes the server's POST /api/strategy-lab documents (`invalid_symbols_param`, `baskets_unavailable`, `too_many_assets`, `preset_search_single_pair_only`, `invalid_symbols`, `mixed_basket`, `invalid_run_window`, `basket_window_too_long`, `basket_too_slow`, `basket_preset_search_unavailable`) are returned; any other 400 is `HTTP_400` without details. `mixed_basket` also returns its `symbol` when it is a pair symbol.
|
|
38
|
+
- **Error codes for every tool.** `api()` now also reads a top-level `code` when there is no `error.code`, and accepts either only when it matches `^[a-z0-9_]{1,64}$` (otherwise `HTTP_<status>`). Strategy Lab errors go through the shared error format (`ApiError.fields` + `errorResult`) instead of a second copy of it.
|
|
39
|
+
- **`symbol` with `symbols` is checked.** A `symbol` that is not one of `symbols` is now refused with `symbol_not_in_symbols` before anything is quoted, instead of being silently ignored.
|
|
40
|
+
- **`symbols` cleanup.** Entries are trimmed, empty ones dropped and duplicates removed case-insensitively after trimming; a list that comes down to one pair is a single-pair run, and one with no pairs left is refused with `no_symbols`.
|
|
41
|
+
- The estimate message is chosen by the number of pairs sent, not by whether a `quoteId` came back. The `symbols` cap stays 8, the server's hard maximum (the plan cap and the admin-set system cap, 5 by default, are enforced server side), and its text now says so.
|
|
42
|
+
|
|
43
|
+
## [0.4.0] - 2026-10-09
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
- **Multi-pair (basket) Strategy Lab runs.** `start_optimization_run` takes `symbols` (1-8 pairs, primary first, same exchange account and market type), so every candidate is tested on every pair instead of being tuned to one chart. Pairs are deduped case-insensitively; `symbol` only picks the primary when it is one of `symbols` (in `symbol`'s spelling, as the server does) and is otherwise ignored, so no unlisted pair is ever added; more than one pair sends `symbols` only, one pair sends a plain scalar `symbol`. The tool text covers the per-plan cap (Free 1 / Pro 3 / Trader 4 / Whale 5, system cap 5), the pricing (base per experiment plus an extra charge per extra pair per experiment, billed per pair actually evaluated), and the pass bar (beat the original on most pairs, wreck no pair, lose money out of sample on no pair; otherwise held).
|
|
47
|
+
- **Quote consent.** New `quoteId` and `acknowledgedCost` params are forwarded only when given. A multi-pair request always returns a `cost_estimate` first; the agent shows the pairs, the maximum cost and the time estimate, then re-sends the same arguments with `acknowledgeCost: true` and the `quoteId`. The bill is never above the quote.
|
|
48
|
+
- **Quote fields on `cost_estimate`:** `quoteId`, `resolved`, `assets`, `assetCount`, `experimentsQuoted`, `clampedFrom`, `estimatedMinutes`, `expectedExperimentsWithinBudget` and `costBreakdown`, each only when the server sends it. Every 0.3.9 field is kept; other server keys are not passed through.
|
|
49
|
+
- **`quote_changed` handling.** A 409 `quote_changed` now comes back as a normal `cost_estimate` result with `quoteChanged: true`, the new `quoteId` and `reason` (only `params_changed`, `price_increased`, `quote_expired` or `foreign_quote`), to show the user and confirm again.
|
|
50
|
+
- **Basket error details.** A 400 with a server `code` (e.g. `too_many_assets`, `baskets_unavailable`, `invalid_symbols`, `basket_too_slow`) returns that code plus only the allowlisted `maxAssets`, `upgrade {tierName, maxAssets}`, `invalidSymbols`, `maxDaysAtTimeframe`, `maxAssetsThatFit` and `maxDaysThatFit`. `ApiError` gained an optional `details` (the parsed JSON error body; never set on the sanitised `insufficient_scope` path, and never added to the generic error text).
|
|
51
|
+
- **Per-pair status.** `get_optimization_status` requests `detail=summary` (`experiments[].perAsset` kept only on the best and latest experiment) and its text explains `progress.basket`, `baselinePerAsset` / `bestPerAsset` (W/T/L/cured), `validation.perAsset` / `validation.breadth`, `autoPromote.untestedPairs` and the `queue {position, etaMinutes}` of a waiting run. `start_optimization_run` also passes `queue` through when the server returns it.
|
|
52
|
+
|
|
53
|
+
### Changed
|
|
54
|
+
- The `symbol` default (`BTC/USDT`) moved from the zod schema into the handler. Omitting `symbols` sends exactly the 0.3.9 request body.
|
|
55
|
+
- `server.json` versions brought up to date (they were stale at 0.3.1).
|
|
56
|
+
|
|
57
|
+
Ship this only after the TradeStaq web release with basket runs is live. Multi-pair runs stay unavailable (400 `baskets_unavailable`) until the server enables them; single-pair runs are unchanged.
|
|
58
|
+
|
|
59
|
+
## [0.3.9] - 2026-10-08
|
|
60
|
+
|
|
61
|
+
### Changed
|
|
62
|
+
- **Strategy Lab tool descriptions now match how runs finish (text only, no request or response changes).** The server now checks a run's best version out of sample before moving the strategy's `latestVersion`, and the old text promised that "improvements are saved to the strategy's latestVersion as they're found", which is no longer true.
|
|
63
|
+
- `start_optimization_run`: the best version becomes `latestVersion` only if it passes the out-of-sample check (single-pair runs: also when the check is inconclusive). Otherwise the version is held, `latestVersion` and the bots following it stay as they were, and `get_optimization_status` shows `progress.verdict`, `progress.heldBecause` and `progress.heldVersionId` (with no `savedVersionId`). The strategy author can accept a held version in the web app ("Use this version anyway").
|
|
64
|
+
- `autoPromote`: requires a passing verdict, profitable out-of-sample results and no regression against the current stable version. An inconclusive check never auto-promotes.
|
|
65
|
+
- `get_optimization_status`: explains `verdict`, `heldVersionId` / `heldBecause`, `cancelled` and `stopReason`, and that `savedVersionId` during a run is not yet `latestVersion`.
|
|
66
|
+
- `cancel_optimization_run`: a cancelled run's best version is kept but held, not saved to `latestVersion`.
|
|
67
|
+
- Ship this only after the matching TradeStaq web release (held runs and the out-of-sample verdict) is live.
|
|
68
|
+
|
|
69
|
+
## [0.3.8] - 2026-07-10
|
|
70
|
+
|
|
71
|
+
### Fixed
|
|
72
|
+
- **Protected-resource metadata advertises the real scopes.** The `/.well-known/oauth-protected-resource` document served by the hosted (`--http`) transport advertised `scopes_supported: ['mcp']`, a stale vocabulary the server no longer issues or enforces — every token is now `mcp:read` / `mcp:paper` / `mcp:live`. A spec-strict MCP client reading this metadata to discover valid scopes could request the wrong one. Now advertises `['mcp:read', 'mcp:paper', 'mcp:live']`, matching the site's `.well-known/oauth-*` routes and the actual scope enforcement.
|
|
73
|
+
|
|
74
|
+
## [0.3.7] - 2026-07-09
|
|
75
|
+
|
|
76
|
+
### Added
|
|
77
|
+
- **OAuth 2.1 refresh tokens — silent renewal, no weekly re-consent.** `authenticate` now registers its client for the `refresh_token` grant and stores the `refresh_token` from the token endpoint. `api()` proactively rotates an access token within 5 minutes of expiry, and recovers from a 401 by rotating once and retrying — so the now-short-lived (~60 min) access tokens renew transparently. On `invalid_grant` (expired/revoked/reuse-detected refresh token) the stored credentials are cleared so the next call cleanly prompts re-authentication. Hosted (per-request bearer) sessions are unaffected — the client connector owns their refresh. A cached client_id registered by an older version (no refresh grant) is re-registered automatically. +5 tests.
|
|
78
|
+
|
|
79
|
+
### Changed
|
|
80
|
+
- **Hosted (`--http`) transport is now stateless.** A throwaway server+transport is created per request instead of tracking sessions in memory, so a restart or deploy no longer drops live agent sessions. `GET`/`DELETE /mcp` return 405 (no long-lived stream in stateless mode).
|
|
81
|
+
- **Unauthenticated `/mcp` requests return `401` with `WWW-Authenticate: Bearer resource_metadata=…` (RFC 9728).** MCP clients now surface a proper Connect affordance and can discover the OAuth flow, instead of the previous phantom "Connected" state on a connection with no bearer. `Authorization` is added to the CORS allow/expose lists for browser clients.
|
|
82
|
+
|
|
83
|
+
## [0.3.6] - 2026-07-09
|
|
84
|
+
|
|
85
|
+
### Fixed
|
|
86
|
+
- **Authenticated tool calls no longer 401 when the base URL is the apex host.** The apex `https://tradestaq.com` 301-redirects to `https://www.tradestaq.com`, and `fetch`/undici strips the `Authorization` header on that cross-origin redirect — so OAuth login succeeded but every subsequent API call reached the upstream with no bearer and returned 401 ("authenticated, but every tool fails"). `loadConfig()` now normalizes an apex `baseUrl` to `www` from **any** source (stale config file, `TRADESTAQ_BASE_URL` env, user override) via the new exported `normalizeBaseUrl()`, keeping API calls same-origin so the bearer survives. Non-apex hosts (staging, self-hosted, custom) are untouched. Mirrors the www-forcing already applied to the site's `.well-known/oauth-*` routes.
|
|
87
|
+
|
|
88
|
+
## [0.3.5] - 2026-07-08
|
|
89
|
+
|
|
90
|
+
### Fixed
|
|
91
|
+
- **`authenticate` no longer fails with "Unexpected end of JSON input".** The OAuth flow parsed response bodies (dynamic client registration, token exchange) and the `login` response with a bare `res.json()`, so any empty or non-JSON body from a proxy/CDN (a Cloudflare 5xx, gateway timeout, or 204) threw an opaque parse error surfaced as `Failed to start auth: Unexpected end of JSON input`. Bodies are now read defensively and the failure reports the HTTP status plus whether the body was empty or non-JSON.
|
|
92
|
+
- **`authenticate` fails fast on hosted (HTTP) transport instead of attempting an unreachable browser login.** The tool's loopback callback server and browser launch only work when the server runs on the user's own machine (stdio). On a hosted server (`--http`, e.g. `mcp.tradestaq.com`) those run server-side and never reach a remote user. The tool now detects HTTP transport and returns guidance to authenticate at the connector level via the advertised `/.well-known/oauth-protected-resource` metadata.
|
|
93
|
+
- **Hosted (HTTP) sessions no longer share one process-global token.** `api()` now resolves the token from each request's `Authorization` bearer in HTTP mode and never falls back to the shared config-file token, so concurrent sessions in one hosted process can't borrow each other's authentication. `login`, `set_token`, `logout`, and `connect_exchange` refuse in HTTP mode (they manage a local machine-wide credential or open a server-side browser) and point to connector-level bearer auth; `check_auth` reflects the per-request token. Stdio (local) installs are unchanged — they still use the local config token.
|
|
94
|
+
|
|
95
|
+
### Changed
|
|
96
|
+
- OAuth/login error messages no longer echo the raw response body into agent-visible text (avoids surfacing untrusted proxy content into model context); the HTTP status and empty-vs-non-JSON distinction are reported instead.
|
|
97
|
+
|
|
98
|
+
### Security
|
|
99
|
+
- **Dependency advisories patched** via non-breaking updates (`npm audit fix`, no `package.json` range changes): resolved the critical vitest UI file-read/exec advisory, the high-severity vite path-traversal and express-rate-limit/ip-address advisories, and the qs DoS. One low-severity dev-only esbuild advisory remains (requires a major bump; deferred).
|
|
100
|
+
|
|
3
101
|
## [0.3.4] - 2026-07-04
|
|
4
102
|
|
|
5
103
|
### Added
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
**[Website](https://tradestaq.com)** · **[Docs](https://tradestaq.com/docs)** · **[MCP / AI Tools](https://tradestaq.com/mcp)** · **[Pricing](https://tradestaq.com/pricing)**
|
|
7
7
|
|
|
8
|
-
**
|
|
8
|
+
**46 AI-powered trading tools for Claude, Cursor, and any MCP client.**
|
|
9
9
|
|
|
10
10
|
Create strategies, backtest them, deploy trading bots, copy top traders, monitor positions, and manage your crypto portfolio, all from conversation. Supports Binance, Bybit, OKX, Bitget, Hyperliquid, dYdX, and more.
|
|
11
11
|
|
|
@@ -142,11 +142,23 @@ Credentials never enter the chat when using the browser flow. Token is stored lo
|
|
|
142
142
|
|------|-------------|
|
|
143
143
|
| `list_bots` | All bots with status and performance |
|
|
144
144
|
| `get_bot_status` | Detailed bot metrics and config |
|
|
145
|
+
| `get_bot_logs` | Run-by-run history: why a bot did or did not trade, dropped signals, errors |
|
|
145
146
|
| `deploy_bot` | Deploy a strategy as a trading bot |
|
|
146
|
-
| `
|
|
147
|
+
| `update_bot` | Edit a bot: rename, switch strategy or apply a preset, timeframe, execution mode, strategy parameters, version channel, risk settings, notifications, `stopAfterClose` |
|
|
148
|
+
| `start_bot` | Start a paused or stopped bot |
|
|
149
|
+
| `stop_bot` | Stop a running bot now (open positions are left unmanaged) |
|
|
150
|
+
| `delete_bot` | Delete a bot (refused while it has an open trade) |
|
|
147
151
|
| `close_position` | Close an open position (full or partial) |
|
|
148
152
|
|
|
149
|
-
`deploy_bot` defaults to paper trading. Pass `live: true` for real money.
|
|
153
|
+
`deploy_bot` defaults to paper trading. Pass `live: true` for real money. The bot trades on the strategy's own timeframe; pass `timeframe` (e.g. `4h`) only to override it. Leave out `name` and the server names the bot.
|
|
154
|
+
|
|
155
|
+
`update_bot` sends everything you pass in one update, after merging it onto the bot's current settings (position sizing, spin settings and parameter overrides are never wiped by a partial change). Size and leverage change only when you pass them. `strategyId` and `presetId` take an ID or a slug (`trade-wind`, `trade-wind-long-short`). A strategy or timeframe change needs the bot to be flat: pause it with `stopAfterClose: true` first, wait until `get_bot_status` shows no open position, then switch, then `start_bot`. A live bot needs the `mcp:live` scope for any change; a paper bot `mcp:paper`. The reply is the resulting config (strategy, version, timeframe, mode, overrides, size, leverage, status) plus server warnings.
|
|
156
|
+
|
|
157
|
+
For example, switching a paused 15m GhostRider bot to Trade Wind on 4h with its Long & Short preset, and renaming it:
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{ "id": "6ab7c2d60014ba19b0c54258", "presetId": "trade-wind-long-short", "timeframe": "4h", "name": "Trade Wind · SUI · 4h" }
|
|
161
|
+
```
|
|
150
162
|
|
|
151
163
|
### Trade History
|
|
152
164
|
|
|
@@ -194,7 +206,7 @@ MCP resources provide browsable data that AI clients can read directly:
|
|
|
194
206
|
┌──────────────┐◄──────────►┐ ┌────────────────►┌──────────────┐
|
|
195
207
|
│Claude Desktop│ │ │ │ │
|
|
196
208
|
│Cursor / CLI │ │ tradestaq-mcp │ Bearer JWT │ TradeStaq │
|
|
197
|
-
└──────────────┘ │
|
|
209
|
+
└──────────────┘ │ 46 tools │◄────────────────│ API │
|
|
198
210
|
│ 3 prompts │ │ │
|
|
199
211
|
┌──────────────┐ HTTP+SSE │ 3 resources │ └──────────────┘
|
|
200
212
|
│ Any MCP │◄──────────►│ │
|
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.
|
|
1
|
+
0.6.0
|
package/dist/api.d.ts
CHANGED
|
@@ -3,11 +3,27 @@ export declare class ApiError extends Error {
|
|
|
3
3
|
code: string;
|
|
4
4
|
retryable: boolean;
|
|
5
5
|
retryAfterMs?: number | undefined;
|
|
6
|
-
|
|
6
|
+
details?: Record<string, unknown> | undefined;
|
|
7
|
+
fields?: Record<string, unknown> | undefined;
|
|
8
|
+
constructor(status: number, code: string, message: string, retryable?: boolean, retryAfterMs?: number | undefined, details?: Record<string, unknown> | undefined, fields?: Record<string, unknown> | undefined);
|
|
7
9
|
}
|
|
8
|
-
|
|
10
|
+
/** A server-provided error code safe to put in front of the agent: a short identifier, nothing else. */
|
|
11
|
+
export declare function isSafeErrorCode(code: unknown): code is string;
|
|
12
|
+
export interface ApiOptions {
|
|
9
13
|
method?: string;
|
|
10
14
|
body?: unknown;
|
|
15
|
+
/** Abort after this many ms (default 30s). */
|
|
11
16
|
timeout?: number;
|
|
12
|
-
|
|
17
|
+
/**
|
|
18
|
+
* false: send the request exactly ONCE. No retry on a timeout, 429, 5xx or network error,
|
|
19
|
+
* and every error it throws has retryable: false, so the agent is never told to retry
|
|
20
|
+
* either. For non-idempotent writes (closing a position, creating a bot), where a resend
|
|
21
|
+
* after a timeout or a gateway 5xx can repeat an action the server already carried out.
|
|
22
|
+
* The one 401 -> token refresh -> resend still happens: a 401 means the server did nothing.
|
|
23
|
+
*/
|
|
24
|
+
retry?: boolean;
|
|
25
|
+
/** Extra request headers. They never replace Authorization, Content-Type or X-MCP-Source. */
|
|
26
|
+
headers?: Record<string, string>;
|
|
27
|
+
}
|
|
28
|
+
export declare function api<T = unknown>(path: string, options?: ApiOptions): Promise<T>;
|
|
13
29
|
//# sourceMappingURL=api.d.ts.map
|
package/dist/api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAGA,qBAAa,QAAS,SAAQ,KAAK;IAExB,MAAM,EAAE,MAAM;IACd,IAAI,EAAE,MAAM;IAEZ,SAAS,EAAE,OAAO;IAClB,YAAY,CAAC,EAAE,MAAM;IAGrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIjC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;gBAXhC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,EACR,SAAS,GAAE,OAAe,EAC1B,YAAY,CAAC,EAAE,MAAM,YAAA,EAGrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,YAAA,EAIjC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,YAAA;CAK1C;AAMD,wGAAwG;AACxG,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,IAAI,MAAM,CAE7D;AAkHD,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,8CAA8C;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,6FAA6F;IAC7F,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC;AAaD,wBAAsB,GAAG,CAAC,CAAC,GAAG,OAAO,EACnC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,UAAe,GACvB,OAAO,CAAC,CAAC,CAAC,CAoIZ"}
|
package/dist/api.js
CHANGED
|
@@ -1,19 +1,36 @@
|
|
|
1
1
|
import { loadConfig, saveConfig } from './config.js';
|
|
2
|
+
import { requestContext } from './request-context.js';
|
|
2
3
|
export class ApiError extends Error {
|
|
3
4
|
status;
|
|
4
5
|
code;
|
|
5
6
|
retryable;
|
|
6
7
|
retryAfterMs;
|
|
7
|
-
|
|
8
|
+
details;
|
|
9
|
+
fields;
|
|
10
|
+
constructor(status, code, message, retryable = false, retryAfterMs,
|
|
11
|
+
// The parsed JSON error body, for callers that read structured fields (e.g. the
|
|
12
|
+
// Strategy Lab quote_changed envelope). Never dumped into the generic error text.
|
|
13
|
+
details,
|
|
14
|
+
// Extra structured fields to show the agent next to code/message (withErrorHandling
|
|
15
|
+
// adds them to the error object). Callers put only allowlisted, shape-checked values
|
|
16
|
+
// here; never a raw server body.
|
|
17
|
+
fields) {
|
|
8
18
|
super(message);
|
|
9
19
|
this.status = status;
|
|
10
20
|
this.code = code;
|
|
11
21
|
this.retryable = retryable;
|
|
12
22
|
this.retryAfterMs = retryAfterMs;
|
|
23
|
+
this.details = details;
|
|
24
|
+
this.fields = fields;
|
|
13
25
|
this.name = 'ApiError';
|
|
14
26
|
}
|
|
15
27
|
}
|
|
16
28
|
const MAX_RETRIES = 2;
|
|
29
|
+
const SAFE_ERROR_CODE = /^[a-z0-9_]{1,64}$/i;
|
|
30
|
+
/** A server-provided error code safe to put in front of the agent: a short identifier, nothing else. */
|
|
31
|
+
export function isSafeErrorCode(code) {
|
|
32
|
+
return typeof code === 'string' && SAFE_ERROR_CODE.test(code);
|
|
33
|
+
}
|
|
17
34
|
// Backoff between retries. Skipped under Vitest so the test suite stays fast
|
|
18
35
|
// while production still waits out rate limits / transient 5xx.
|
|
19
36
|
function sleep(ms) {
|
|
@@ -21,16 +38,79 @@ function sleep(ms) {
|
|
|
21
38
|
return Promise.resolve();
|
|
22
39
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
23
40
|
}
|
|
41
|
+
// Exchange the stored refresh token for a fresh access+refresh pair (OAuth 2.1
|
|
42
|
+
// rotation, RFC 9700). stdio-only — hosted sessions never touch the shared file
|
|
43
|
+
// token. Returns true when the config was updated with a new access token.
|
|
44
|
+
async function oauthRefresh() {
|
|
45
|
+
const config = loadConfig();
|
|
46
|
+
if (!config.refreshToken || !config.oauthClientId)
|
|
47
|
+
return false;
|
|
48
|
+
try {
|
|
49
|
+
const body = new URLSearchParams({
|
|
50
|
+
grant_type: 'refresh_token',
|
|
51
|
+
refresh_token: config.refreshToken,
|
|
52
|
+
client_id: config.oauthClientId,
|
|
53
|
+
});
|
|
54
|
+
const res = await fetch(`${config.baseUrl}/api/oauth/token`, {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
57
|
+
body: body.toString(),
|
|
58
|
+
});
|
|
59
|
+
if (!res.ok) {
|
|
60
|
+
// invalid_grant → the refresh token is expired, revoked, or reuse-detected.
|
|
61
|
+
// Clear stored tokens so the next call cleanly prompts re-authentication
|
|
62
|
+
// instead of retrying a dead token forever.
|
|
63
|
+
if (res.status === 400 || res.status === 401) {
|
|
64
|
+
const c = loadConfig();
|
|
65
|
+
saveConfig({ ...c, token: undefined, tokenExpiresAt: undefined, refreshToken: undefined, refreshExpiresAt: undefined });
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
const data = (await res.json().catch(() => ({})));
|
|
70
|
+
if (!data.access_token)
|
|
71
|
+
return false;
|
|
72
|
+
const c = loadConfig();
|
|
73
|
+
saveConfig({
|
|
74
|
+
...c,
|
|
75
|
+
token: data.access_token,
|
|
76
|
+
tokenExpiresAt: Date.now() + (data.expires_in || 3600) * 1000,
|
|
77
|
+
// Rotation: store the NEW refresh token; fall back to the old one only if
|
|
78
|
+
// the server didn't rotate (shouldn't happen, but don't lose the session).
|
|
79
|
+
refreshToken: data.refresh_token || c.refreshToken,
|
|
80
|
+
refreshExpiresAt: Date.now() + 30 * 24 * 3600 * 1000,
|
|
81
|
+
});
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
24
88
|
async function refreshTokenIfNeeded() {
|
|
89
|
+
// Hosted (per-request bearer) sessions never refresh or write the shared file
|
|
90
|
+
// token — that bearer is owned by the client connector's OAuth flow, and
|
|
91
|
+
// writing it to the shared config would leak it across sessions.
|
|
92
|
+
if (requestContext.getStore())
|
|
93
|
+
return;
|
|
25
94
|
const config = loadConfig();
|
|
26
|
-
if (!config.token
|
|
95
|
+
if (!config.token)
|
|
96
|
+
return;
|
|
97
|
+
// OAuth path: rotate via the refresh token when the (short-lived, ~60min)
|
|
98
|
+
// access token is within 5 minutes of expiry or already expired.
|
|
99
|
+
if (config.refreshToken) {
|
|
100
|
+
const skew = 5 * 60 * 1000;
|
|
101
|
+
if (config.tokenExpiresAt && config.tokenExpiresAt - Date.now() > skew)
|
|
102
|
+
return;
|
|
103
|
+
await oauthRefresh();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
// Legacy path: Payload session tokens (email/password login), no OAuth refresh
|
|
107
|
+
// token. Refresh via Payload's endpoint when expiring within 1 hour.
|
|
108
|
+
if (!config.tokenExpiresAt)
|
|
27
109
|
return;
|
|
28
|
-
// Only refresh if expiring within 1 hour
|
|
29
110
|
const oneHour = 60 * 60 * 1000;
|
|
30
111
|
if (config.tokenExpiresAt - Date.now() > oneHour)
|
|
31
112
|
return;
|
|
32
113
|
try {
|
|
33
|
-
// Use Payload's built-in refresh endpoint
|
|
34
114
|
const res = await fetch(`${config.baseUrl}/api/users/refresh-token`, {
|
|
35
115
|
method: 'POST',
|
|
36
116
|
headers: {
|
|
@@ -67,14 +147,39 @@ function parseRetryAfter(res) {
|
|
|
67
147
|
const secs = Number(raw);
|
|
68
148
|
return Number.isFinite(secs) && secs >= 0 ? Math.min(secs * 1000, 30_000) : undefined;
|
|
69
149
|
}
|
|
150
|
+
// Headers api() always sets itself; a caller's `headers` cannot replace them.
|
|
151
|
+
const FIXED_HEADERS = new Set(['authorization', 'content-type', 'x-mcp-source']);
|
|
152
|
+
function extraHeaders(headers) {
|
|
153
|
+
const out = {};
|
|
154
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
155
|
+
if (!FIXED_HEADERS.has(name.toLowerCase()))
|
|
156
|
+
out[name] = value;
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
70
160
|
export async function api(path, options = {}) {
|
|
161
|
+
const store = requestContext.getStore();
|
|
162
|
+
// Stdio mode: proactively rotate BEFORE reading the token, so an expired
|
|
163
|
+
// access token is refreshed rather than sent stale. No-op when a per-request
|
|
164
|
+
// store is present (hosted connectors own their own refresh).
|
|
165
|
+
if (!store)
|
|
166
|
+
await refreshTokenIfNeeded();
|
|
71
167
|
const config = loadConfig();
|
|
72
|
-
|
|
73
|
-
|
|
168
|
+
// Hosted mode (store present): use THIS request's bearer only — never fall
|
|
169
|
+
// back to the shared file token, or one session would borrow another's auth.
|
|
170
|
+
// Stdio mode (no store): the file token, exactly as before.
|
|
171
|
+
let token = store ? store.token : config.token;
|
|
172
|
+
if (!token) {
|
|
173
|
+
throw new ApiError(401, 'AUTH_EXPIRED', store
|
|
174
|
+
? 'Not authenticated. This hosted TradeStaq MCP server expects a bearer token from your client connector — authorize the TradeStaq connector (OAuth) so it attaches one per request.'
|
|
175
|
+
: 'Not authenticated. Run the authenticate tool first.');
|
|
74
176
|
}
|
|
75
|
-
await refreshTokenIfNeeded();
|
|
76
177
|
const url = `${config.baseUrl}${path}`;
|
|
178
|
+
// retry: false → one send. Its errors are never retryable (below), so the loop only goes
|
|
179
|
+
// round again for the 401 refresh resend.
|
|
180
|
+
const retry = options.retry !== false;
|
|
77
181
|
let lastErr;
|
|
182
|
+
let recovered401 = false;
|
|
78
183
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
79
184
|
if (attempt > 0 && lastErr) {
|
|
80
185
|
// Honor server Retry-After when present, else exponential backoff (1s, 2s) capped at 8s.
|
|
@@ -87,7 +192,8 @@ export async function api(path, options = {}) {
|
|
|
87
192
|
const res = await fetch(url, {
|
|
88
193
|
method: options.method ?? 'GET',
|
|
89
194
|
headers: {
|
|
90
|
-
|
|
195
|
+
...extraHeaders(options.headers),
|
|
196
|
+
Authorization: `Bearer ${token}`,
|
|
91
197
|
'Content-Type': 'application/json',
|
|
92
198
|
'X-MCP-Source': 'tradestaq-mcp',
|
|
93
199
|
},
|
|
@@ -106,7 +212,7 @@ export async function api(path, options = {}) {
|
|
|
106
212
|
parseOk = false;
|
|
107
213
|
}
|
|
108
214
|
if (!res.ok) {
|
|
109
|
-
const retryable = res.status === 429 || res.status >= 500;
|
|
215
|
+
const retryable = retry && (res.status === 429 || res.status >= 500);
|
|
110
216
|
const retryAfterMs = retryable ? parseRetryAfter(res) : undefined;
|
|
111
217
|
// OAuth insufficient_scope (RFC 6749 §5.2). The server-provided
|
|
112
218
|
// `scope` and `error_description` fields end up in LLM context
|
|
@@ -120,11 +226,17 @@ export async function api(path, options = {}) {
|
|
|
120
226
|
const safeScope = rawScope.find((s) => KNOWN.has(s)) || 'a broader scope';
|
|
121
227
|
throw new ApiError(403, 'INSUFFICIENT_SCOPE', `This action requires ${safeScope === 'a broader scope' ? safeScope : `the '${safeScope}' OAuth scope`}. The current token does not grant it. Surface this to the user — do not re-authenticate without explicit user approval, since broader scopes expand what automated tools can do on their account.`, false);
|
|
122
228
|
}
|
|
123
|
-
|
|
229
|
+
// The machine-readable code: `error.code` (nested envelope) or a top-level `code`
|
|
230
|
+
// (e.g. the Strategy Lab basket 400s). It reaches the agent's context, so only a
|
|
231
|
+
// short identifier is accepted; anything else falls back to HTTP_<status>.
|
|
232
|
+
const code = (parseOk ? [data?.error?.code, data?.code].find(isSafeErrorCode) : undefined) ?? `HTTP_${res.status}`;
|
|
124
233
|
const message = parseOk
|
|
125
234
|
? (data?.error?.message ?? data?.error ?? data?.message ?? `API returned ${res.status}`)
|
|
126
235
|
: `API returned ${res.status} with a non-JSON response`;
|
|
127
|
-
|
|
236
|
+
const details = parseOk && data && typeof data === 'object' && !Array.isArray(data)
|
|
237
|
+
? data
|
|
238
|
+
: undefined;
|
|
239
|
+
throw new ApiError(res.status, code, message, retryable, retryAfterMs, details);
|
|
128
240
|
}
|
|
129
241
|
// 2xx with an unparseable body: treat empty/no-content as an empty
|
|
130
242
|
// object (common for write endpoints); the caller reads fields defensively.
|
|
@@ -134,10 +246,23 @@ export async function api(path, options = {}) {
|
|
|
134
246
|
const apiErr = err instanceof ApiError
|
|
135
247
|
? err
|
|
136
248
|
: err.name === 'AbortError'
|
|
137
|
-
? new ApiError(408, 'TIMEOUT', 'Request timed out',
|
|
138
|
-
: new ApiError(0, 'NETWORK_ERROR', `Failed to reach TradeStaq API: ${err.message}`,
|
|
249
|
+
? new ApiError(408, 'TIMEOUT', 'Request timed out', retry)
|
|
250
|
+
: new ApiError(0, 'NETWORK_ERROR', `Failed to reach TradeStaq API: ${err.message}`, retry);
|
|
251
|
+
// stdio: a 401 despite the proactive refresh (token revoked, clock skew,
|
|
252
|
+
// or an expiry we missed) — try ONE rotation, then retry with the new
|
|
253
|
+
// token. Bounded by recovered401 so a persistently-rejected token can't loop.
|
|
254
|
+
if (apiErr.status === 401 && !store && !recovered401 && loadConfig().refreshToken) {
|
|
255
|
+
recovered401 = true;
|
|
256
|
+
if (await oauthRefresh()) {
|
|
257
|
+
const rotated = loadConfig().token;
|
|
258
|
+
if (rotated) {
|
|
259
|
+
token = rotated;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
139
264
|
// Retry transient failures (429 / 5xx / timeout / network) with backoff.
|
|
140
|
-
if (apiErr.retryable && attempt < MAX_RETRIES) {
|
|
265
|
+
if (retry && apiErr.retryable && attempt < MAX_RETRIES) {
|
|
141
266
|
lastErr = apiErr;
|
|
142
267
|
continue;
|
|
143
268
|
}
|
|
@@ -148,6 +273,6 @@ export async function api(path, options = {}) {
|
|
|
148
273
|
}
|
|
149
274
|
}
|
|
150
275
|
// Retries exhausted.
|
|
151
|
-
throw lastErr ?? new ApiError(0, 'NETWORK_ERROR', 'Request failed after retries',
|
|
276
|
+
throw lastErr ?? new ApiError(0, 'NETWORK_ERROR', 'Request failed after retries', retry);
|
|
152
277
|
}
|
|
153
278
|
//# sourceMappingURL=api.js.map
|
package/dist/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,U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AAE,EAAE,KAAK,CAAC,CAAA;YAE3G,yEAAyE;YACzE,sEAAsE;YACtE,8EAA8E;YAC9E,IAAI,MAAM,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,YAAY,IAAI,UAAU,EAAE,CAAC,YAAY,EAAE,CAAC;gBAClF,YAAY,GAAG,IAAI,CAAA;gBACnB,IAAI,MAAM,YAAY,EAAE,EAAE,CAAC;oBACzB,MAAM,OAAO,GAAG,UAAU,EAAE,CAAC,KAAK,CAAA;oBAClC,IAAI,OAAO,EAAE,CAAC;wBACZ,KAAK,GAAG,OAAO,CAAA;wBACf,SAAQ;oBACV,CAAC;gBACH,CAAC;YACH,CAAC;YAED,yEAAyE;YACzE,IAAI,KAAK,IAAI,MAAM,CAAC,SAAS,IAAI,OAAO,GAAG,WAAW,EAAE,CAAC;gBACvD,OAAO,GAAG,MAAM,CAAA;gBAChB,SAAQ;YACV,CAAC;YACD,MAAM,MAAM,CAAA;QACd,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAA;QACrB,CAAC;IACH,CAAC;IAED,qBAAqB;IACrB,MAAM,OAAO,IAAI,IAAI,QAAQ,CAAC,CAAC,EAAE,eAAe,EAAE,8BAA8B,EAAE,KAAK,CAAC,CAAA;AAC1F,CAAC"}
|
package/dist/config.d.ts
CHANGED
|
@@ -2,9 +2,13 @@ export interface McpConfig {
|
|
|
2
2
|
token?: string;
|
|
3
3
|
baseUrl: string;
|
|
4
4
|
tokenExpiresAt?: number;
|
|
5
|
+
refreshToken?: string;
|
|
6
|
+
refreshExpiresAt?: number;
|
|
5
7
|
oauthClientId?: string;
|
|
6
8
|
oauthClientIdForBaseUrl?: string;
|
|
9
|
+
oauthClientRefreshCapable?: boolean;
|
|
7
10
|
}
|
|
11
|
+
export declare function normalizeBaseUrl(url: string): string;
|
|
8
12
|
export declare function loadConfig(): McpConfig;
|
|
9
13
|
export declare function saveConfig(config: McpConfig): void;
|
|
10
14
|
export declare function clearToken(): void;
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,SAAS;IACxB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;IACf,cAAc,CAAC,EAAE,MAAM,CAAA;IAGvB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,uBAAuB,CAAC,EAAE,MAAM,CAAA;
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,SAAS;IACxB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;IACf,cAAc,CAAC,EAAE,MAAM,CAAA;IAGvB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAGzB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAIhC,yBAAyB,CAAC,EAAE,OAAO,CAAA;CACpC;AAeD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED,wBAAgB,UAAU,IAAI,SAAS,CAoBtC;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI,CAIlD;AAED,wBAAgB,UAAU,IAAI,IAAI,CAgBjC;AAED,wBAAgB,eAAe,IAAI,OAAO,CAKzC"}
|
package/dist/config.js
CHANGED
|
@@ -4,6 +4,17 @@ import os from 'node:os';
|
|
|
4
4
|
const CONFIG_DIR = path.join(os.homedir(), '.tradestaq');
|
|
5
5
|
const CONFIG_FILE = path.join(CONFIG_DIR, 'mcp-config.json');
|
|
6
6
|
let _cache = null;
|
|
7
|
+
// The apex host (tradestaq.com) 301-redirects to www, and fetch/undici strips
|
|
8
|
+
// the Authorization header on that cross-origin redirect — so an apex baseUrl
|
|
9
|
+
// authenticates fine at the OAuth layer but every subsequent API call reaches
|
|
10
|
+
// the upstream with no bearer and 401s ("authenticated, but every tool fails").
|
|
11
|
+
// Force www so API calls stay same-origin and the bearer survives. Mirrors the
|
|
12
|
+
// www-forcing in the site's .well-known/oauth-* routes; a stray apex value from
|
|
13
|
+
// ANY source (stale config file, env override, user input) can no longer strip
|
|
14
|
+
// auth. Non-apex hosts (staging, self-hosted, custom) are left untouched.
|
|
15
|
+
export function normalizeBaseUrl(url) {
|
|
16
|
+
return url.replace(/^https:\/\/tradestaq\.com/, 'https://www.tradestaq.com');
|
|
17
|
+
}
|
|
7
18
|
export function loadConfig() {
|
|
8
19
|
if (_cache)
|
|
9
20
|
return _cache;
|
|
@@ -11,25 +22,21 @@ export function loadConfig() {
|
|
|
11
22
|
// Environment variables override file config (useful for CI, Claude Code, etc.)
|
|
12
23
|
const envToken = process.env.TRADESTAQ_TOKEN;
|
|
13
24
|
const envBaseUrl = process.env.TRADESTAQ_BASE_URL;
|
|
25
|
+
let config;
|
|
14
26
|
try {
|
|
15
27
|
const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
|
|
16
|
-
|
|
17
|
-
if (envToken)
|
|
18
|
-
config.token = envToken;
|
|
19
|
-
if (envBaseUrl)
|
|
20
|
-
config.baseUrl = envBaseUrl;
|
|
21
|
-
_cache = config;
|
|
22
|
-
return config;
|
|
28
|
+
config = { ...defaults, ...JSON.parse(raw) };
|
|
23
29
|
}
|
|
24
30
|
catch {
|
|
25
|
-
|
|
26
|
-
if (envToken)
|
|
27
|
-
config.token = envToken;
|
|
28
|
-
if (envBaseUrl)
|
|
29
|
-
config.baseUrl = envBaseUrl;
|
|
30
|
-
_cache = config;
|
|
31
|
-
return config;
|
|
31
|
+
config = { ...defaults };
|
|
32
32
|
}
|
|
33
|
+
if (envToken)
|
|
34
|
+
config.token = envToken;
|
|
35
|
+
if (envBaseUrl)
|
|
36
|
+
config.baseUrl = envBaseUrl;
|
|
37
|
+
config.baseUrl = normalizeBaseUrl(config.baseUrl);
|
|
38
|
+
_cache = config;
|
|
39
|
+
return config;
|
|
33
40
|
}
|
|
34
41
|
export function saveConfig(config) {
|
|
35
42
|
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
@@ -41,6 +48,8 @@ export function clearToken() {
|
|
|
41
48
|
const config = loadConfig();
|
|
42
49
|
delete config.token;
|
|
43
50
|
delete config.tokenExpiresAt;
|
|
51
|
+
delete config.refreshToken;
|
|
52
|
+
delete config.refreshExpiresAt;
|
|
44
53
|
// Also drop the cached OAuth client_id. It was registered with whatever
|
|
45
54
|
// scope the last authenticate call used; a subsequent authenticate with
|
|
46
55
|
// a different scope should re-register cleanly rather than reuse a
|
|
@@ -48,6 +57,7 @@ export function clearToken() {
|
|
|
48
57
|
// registered scope as an upper bound on authorize-time scope requests).
|
|
49
58
|
delete config.oauthClientId;
|
|
50
59
|
delete config.oauthClientIdForBaseUrl;
|
|
60
|
+
delete config.oauthClientRefreshCapable;
|
|
51
61
|
saveConfig(config);
|
|
52
62
|
}
|
|
53
63
|
export function isAuthenticated() {
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,MAAM,SAAS,CAAA;AAoBxB,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,YAAY,CAAC,CAAA;AACxD,MAAM,WAAW,GAA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
|
|
5
5
|
}[];
|
|
6
6
|
};
|
|
7
|
+
/**
|
|
8
|
+
* Best-effort strategy name lookup, owner-authoritative first with a
|
|
9
|
+
* marketplace fallback (same pattern get_strategy uses in strategy.ts).
|
|
10
|
+
* Never throws -- callers that just want a human-readable label for
|
|
11
|
+
* something else (e.g. naming a backtest) shouldn't fail the whole
|
|
12
|
+
* operation because a name lookup 403'd or 404'd. Falls back to the raw ID.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveStrategyName(id: string): Promise<string>;
|
|
15
|
+
/**
|
|
16
|
+
* The one error result shape every tool returns: `{ error: { code, message, retryable,
|
|
17
|
+
* retryAfterMs?, ...fields } }`. `fields` must already be allowlisted by the caller.
|
|
18
|
+
*/
|
|
19
|
+
export declare function errorResult(code: string, message: string, { retryable, retryAfterMs, fields }?: {
|
|
20
|
+
retryable?: boolean;
|
|
21
|
+
retryAfterMs?: number;
|
|
22
|
+
fields?: Record<string, unknown>;
|
|
23
|
+
}): {
|
|
24
|
+
isError: boolean;
|
|
25
|
+
content: {
|
|
26
|
+
type: "text";
|
|
27
|
+
text: string;
|
|
28
|
+
}[];
|
|
29
|
+
};
|
|
7
30
|
export declare function withErrorHandling<T extends (...args: any[]) => Promise<any>>(handler: T): T;
|
|
8
31
|
//# sourceMappingURL=helpers.d.ts.map
|
package/dist/helpers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO;;;;;EAIvC;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,IAAI,EAAE,OAAO;;;;;EAIvC;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBrE;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,EAAE,SAAiB,EAAE,YAAY,EAAE,MAAM,EAAE,GAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAO;;;;;;EAYnI;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,CAAC,CAoB3F"}
|