From 4596af7aee24374c614cba73cc175272549163a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 8 Aug 2026 23:55:03 +0000 Subject: [PATCH] feat: add local HTTP daemon for Stream Deck and VoiceAttack triggers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stream Deck and VoiceAttack can launch a process or hit a URL, but neither speaks MCP — it is a stdio protocol owned by the host that spawns the server. This adds a second adapter over the same tools so both devices can reach them. Extract the tool handlers out of the MCP request-handler closure into a shared registry (src/tools.ts). src/index.ts is now a thin stdio adapter with identical behaviour; src/http.ts is a new localhost daemon exposing: GET /q/:tool raw JSON, no model, answers from cache in milliseconds GET /say/:preset one plain-English sentence shaped for text-to-speech GET|POST /ask natural language via the Anthropic API, for open-ended questions no preset can answer The voice presets need their own formatter, not just their own transport — piping trade-route JSON into a speech synthesiser is useless. UEX field names vary by endpoint, so each preset reads through candidate key lists and degrades to a speakable diagnostic rather than throwing. /ask goes straight to the SDK tool runner rather than back through MCP, and caps tool output at 8k characters instead of 40k: an unfiltered trade-routes response is the dominant cost driver on that path. The daemon binds to 127.0.0.1 and rejects browser-originated requests, so a page you happen to visit cannot spend API credit against /ask. SCMCP_HTTP_TOKEN gates other local processes. Also included: - fix: silence the dotenv v17 startup banner, which printed to stdout and corrupted the MCP JSON-RPC stream on every session. Added subprocess contract tests against the built server that catch it; in-process assertions cannot, because the test runner replaces stdout before any import runs. - fix: install.sh computed MCP_ENV but never passed it, so UEXTOKEN never reached the MCP registration. - chore: upgrade axios to 1.19 (1.14 mishandles HTTPS proxies). Integrations: a PowerShell script for Stream Deck keys, a VoiceAttack inline C# function (avoids the console-window flash of shelling out), and a generator that builds a closed VoiceAttack phrase list from live commodity data — dictation mis-hears "Laranite" far more often than a fixed grammar does. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01HcVUQaPfMoyAhj94KM5ZDf --- README.md | 75 +++ install.sh | 16 +- integrations/streamdeck/scmcp.ps1 | 121 +++++ integrations/voiceattack/SCMCP.cs | 125 +++++ integrations/voiceattack/generate-grammar.mjs | 114 ++++ package-lock.json | 162 ++++-- package.json | 11 +- src/ask.ts | 114 ++++ src/http.test.ts | 125 +++++ src/http.ts | 226 ++++++++ src/index.test.ts | 7 - src/index.ts | 492 +---------------- src/mcp.test.ts | 147 ++++++ src/tools.test.ts | 166 ++++++ src/tools.ts | 496 ++++++++++++++++++ src/voice.test.ts | 198 +++++++ src/voice.ts | 207 ++++++++ 17 files changed, 2268 insertions(+), 534 deletions(-) create mode 100644 integrations/streamdeck/scmcp.ps1 create mode 100644 integrations/voiceattack/SCMCP.cs create mode 100644 integrations/voiceattack/generate-grammar.mjs create mode 100644 src/ask.ts create mode 100644 src/http.test.ts create mode 100644 src/http.ts delete mode 100644 src/index.test.ts create mode 100644 src/mcp.test.ts create mode 100644 src/tools.test.ts create mode 100644 src/tools.ts create mode 100644 src/voice.test.ts create mode 100644 src/voice.ts diff --git a/README.md b/README.md index 187b98d..21db30f 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,81 @@ A Model Context Protocol (MCP) server providing real-time access to Star Citizen - `sct_search`: Search Star Citizen Tools (starcitizen.tools) for any topic. - `sct_get_article`: Get the text content of an article from Star Citizen Tools (e.g. for lore, character info, or detailed guides). +## Triggering from a Stream Deck or VoiceAttack + +Stream Deck and VoiceAttack can launch a process or hit a URL; neither speaks MCP, which is a stdio protocol owned by the host that spawns it. So alongside the MCP server there is a **local daemon** that puts the same tools behind plain HTTP on `127.0.0.1`. + +```bash +npm run build +npm run daemon # http://127.0.0.1:7331 +``` + +Both entry points share one tool registry (`src/tools.ts`); `src/index.ts` is the MCP adapter and `src/http.ts` is the HTTP one. + +### Endpoints + +| Route | Returns | For | +|---|---|---| +| `GET /health` | JSON status | Checking the daemon is up | +| `GET /tools` | Tool names and schemas | Discovery | +| `GET /presets` | Voice preset names and params | Discovery | +| `GET /q/:tool?args` | Raw JSON | Stream Deck keys, scripts | +| `GET /say/:preset?args` | One plain-English sentence | Text-to-speech | +| `GET/POST /ask?q=...` | One sentence, via the model | Open-ended questions | + +`/q/*` is a direct call — no model, no cost, and answers from the 5-minute cache in milliseconds. `/ask` runs the question through Claude with the same tools available and takes a few seconds, so use it only where a preset can't answer. + +```bash +curl "http://127.0.0.1:7331/say/sell?commodity=Gold" +# Gold sells highest at Everus Harbor in Stanton, 32,500 per S C U. + +curl "http://127.0.0.1:7331/say/route?scu=96&investment=1000000" +# Best route: buy Gold at HDMS-Stanhope, sell at Everus Harbor, for 450,000 profit. + +curl "http://127.0.0.1:7331/q/uex_get_commodity_prices?commodity_name=Laranite" +``` + +Voice presets: `sell`, `buy`, `route`, `top`. + +### Stream Deck + +Bind a key to **System → Open**, pointing at `powershell.exe` with: + +``` +-ExecutionPolicy Bypass -File "C:\path\to\SCMCP\integrations\streamdeck\scmcp.ps1" -Preset sell -Arg commodity=Gold +``` + +The script fetches the answer and speaks it through the Windows synthesiser. Use `-Raw -NoSpeak` to print JSON instead, or `-Ask "..."` for a natural-language question. See `integrations/streamdeck/scmcp.ps1` for all options. + +*Not yet built:* a proper Stream Deck plugin (`@elgato/streamdeck`) that renders the answer on the key face rather than only speaking it. The daemon already returns everything such a plugin needs from `/q/*`. + +### VoiceAttack + +Use the inline C# function in `integrations/voiceattack/SCMCP.cs` rather than shelling out — it avoids flashing a console window over the game. The file's header comments give the exact command layout. + +For reliable recognition, prefer a **closed phrase list** over dictation. Generate one from live commodity data: + +```bash +npm run voice:grammar # prints the list and suggested commands +npm run voice:grammar -- -o grammar.txt +``` + +That produces `[Gold;Laranite;Titanium;...]` for pasting into a command phrase, with the matched word exposed as `{TXT:1}`. Dictation mode still has its place — route `{DICTATION}` to `/ask` for open-ended lore and ship questions where the vocabulary isn't known ahead of time. + +### Configuration + +| Variable | Default | Purpose | +|---|---|---| +| `SCMCP_HTTP_PORT` | `7331` | Daemon port | +| `SCMCP_HTTP_TOKEN` | *(unset)* | Shared secret required on every request | +| `SCMCP_ASK_MODEL` | `claude-opus-5` | Model behind `/ask` | +| `SCMCP_ASK_EFFORT` | `low` | Reasoning effort for `/ask` | +| `ANTHROPIC_API_KEY` | *(unset)* | Required for `/ask`; every other route works without it | + +The daemon binds to `127.0.0.1` only. It also rejects requests carrying browser headers (`Origin`, cross-site `Sec-Fetch-Site`), so a web page you happen to visit cannot quietly spend your API credit against `/ask`. Set `SCMCP_HTTP_TOKEN` if you want to gate other local processes too. + +`/ask` defaults to `claude-opus-5`. If you'd rather trade some quality for latency and cost while flying, set `SCMCP_ASK_MODEL=claude-haiku-4-5` or `claude-sonnet-5`. + ## Installation & Local Development Create a `.env` file in the root directory and add your UEX API token: diff --git a/install.sh b/install.sh index 07d0a06..76d6d83 100755 --- a/install.sh +++ b/install.sh @@ -7,12 +7,22 @@ npm install npm run build MCP_COMMAND="node $(pwd)/dist/index.js" -MCP_ENV="UEXTOKEN=$UEXTOKEN" + +# Pass UEXTOKEN through to the MCP registration. The server is spawned by the +# client in the client's working directory, so dotenv will not find this repo's +# .env file — without this the token has to be exported globally. +MCP_ENV_ARGS=() +if [ -n "$UEXTOKEN" ]; then + MCP_ENV_ARGS=(-e "UEXTOKEN=$UEXTOKEN") +else + echo "⚠️ UEXTOKEN is not set in this shell; registering without it." + echo " Set it and re-run, or add it to the MCP config by hand." +fi echo "" echo "Attempting to install Star Citizen MCP for Claude Code..." if command -v claude &> /dev/null; then - claude mcp add scmcp $MCP_COMMAND + claude mcp add scmcp "${MCP_ENV_ARGS[@]}" -- $MCP_COMMAND echo "✅ Successfully added to Claude Code." else echo "⚠️ Claude Code CLI not found. Skipping." @@ -22,7 +32,7 @@ echo "" echo "Attempting to install Star Citizen MCP for Gemini CLI..." if command -v gemini &> /dev/null; then # Assuming Gemini uses a similar plugin command or config structure - gemini mcp add scmcp $MCP_COMMAND + gemini mcp add scmcp "${MCP_ENV_ARGS[@]}" -- $MCP_COMMAND echo "✅ Successfully added to Gemini." else echo "⚠️ Gemini CLI not found. To manually add, use the following command:" diff --git a/integrations/streamdeck/scmcp.ps1 b/integrations/streamdeck/scmcp.ps1 new file mode 100644 index 0000000..f152d36 --- /dev/null +++ b/integrations/streamdeck/scmcp.ps1 @@ -0,0 +1,121 @@ +<# +.SYNOPSIS + Query the SCMCP daemon from a Stream Deck key and optionally speak the answer. + +.DESCRIPTION + Bind this to a Stream Deck "System > Open" action, or to a Multi Action, with + the App/File set to powershell.exe and the arguments set to: + + -ExecutionPolicy Bypass -File "C:\path\to\scmcp.ps1" -Preset sell -Arg commodity=Gold + + The daemon must already be running (npm run daemon). + +.PARAMETER Preset + A voice preset name: sell, buy, route, top. Returns one spoken sentence. + +.PARAMETER Tool + A raw tool name instead of a preset (e.g. uex_get_commodity_prices). + Returns JSON, which is useful with -Raw but not with -Speak. + +.PARAMETER Ask + A natural-language question, routed through the model. Slower and costs + API credit; use a preset where one exists. + +.PARAMETER Arg + Repeatable key=value query parameters, e.g. -Arg commodity=Gold -Arg system=Stanton + +.PARAMETER Speak + Read the answer aloud through the Windows speech synthesiser. On by default + for presets and questions; ignored for -Tool. + +.EXAMPLE + .\scmcp.ps1 -Preset sell -Arg commodity=Gold + +.EXAMPLE + .\scmcp.ps1 -Preset route -Arg scu=96 -Arg investment=1000000 + +.EXAMPLE + .\scmcp.ps1 -Ask "what shields does a Carrack come with?" +#> +[CmdletBinding(DefaultParameterSetName = 'Preset')] +param( + [Parameter(ParameterSetName = 'Preset', Mandatory = $true)] + [string]$Preset, + + [Parameter(ParameterSetName = 'Tool', Mandatory = $true)] + [string]$Tool, + + [Parameter(ParameterSetName = 'Ask', Mandatory = $true)] + [string]$Ask, + + [string[]]$Arg = @(), + + [string]$BaseUrl = $(if ($env:SCMCP_URL) { $env:SCMCP_URL } else { 'http://127.0.0.1:7331' }), + + [string]$Token = $env:SCMCP_HTTP_TOKEN, + + [int]$TimeoutSec = 20, + + [switch]$Raw, + + [switch]$NoSpeak +) + +$ErrorActionPreference = 'Stop' + +function Get-QueryString { + param([string[]]$Pairs) + if (-not $Pairs -or $Pairs.Count -eq 0) { return '' } + $encoded = foreach ($pair in $Pairs) { + $split = $pair -split '=', 2 + if ($split.Count -ne 2) { throw "Argument '$pair' must be in key=value form." } + '{0}={1}' -f [uri]::EscapeDataString($split[0]), [uri]::EscapeDataString($split[1]) + } + '?' + ($encoded -join '&') +} + +function Invoke-Scmcp { + param([string]$Path) + $headers = @{} + if ($Token) { $headers['X-SCMCP-Token'] = $Token } + # -UseBasicParsing keeps this working on hosts without Internet Explorer, + # and the loopback address is never proxied. + $response = Invoke-WebRequest -Uri ($BaseUrl + $Path) -Headers $headers ` + -TimeoutSec $TimeoutSec -UseBasicParsing + return $response.Content +} + +function Out-Speech { + param([string]$Text) + Add-Type -AssemblyName System.Speech + $synth = New-Object System.Speech.Synthesis.SpeechSynthesizer + try { $synth.Speak($Text) } finally { $synth.Dispose() } +} + +$query = Get-QueryString -Pairs $Arg + +switch ($PSCmdlet.ParameterSetName) { + 'Preset' { $path = "/say/$([uri]::EscapeDataString($Preset))$query"; $speakable = $true } + 'Tool' { $path = "/q/$([uri]::EscapeDataString($Tool))$query"; $speakable = $false } + 'Ask' { $path = "/ask?q=$([uri]::EscapeDataString($Ask))"; $speakable = $true } +} + +try { + $answer = Invoke-Scmcp -Path $path +} +catch { + # A dead daemon or a timeout should still tell you something out loud rather + # than opening a red console window you cannot read mid-flight. + $answer = 'The Star Citizen daemon did not respond.' + if (-not $NoSpeak -and $speakable) { Out-Speech -Text $answer } + Write-Error $_ + exit 1 +} + +if ($Raw -or -not $speakable) { + Write-Output $answer +} + +if ($speakable -and -not $NoSpeak) { + Out-Speech -Text $answer +} diff --git a/integrations/voiceattack/SCMCP.cs b/integrations/voiceattack/SCMCP.cs new file mode 100644 index 0000000..c87d27d --- /dev/null +++ b/integrations/voiceattack/SCMCP.cs @@ -0,0 +1,125 @@ +// VoiceAttack inline C# — query the SCMCP daemon and hand the answer back for TTS. +// +// Why inline C# rather than "Run an application": shelling out to curl or +// PowerShell flashes a console window over the game every time you speak. This +// runs in-process and is silent. +// +// SETUP +// 1. In VoiceAttack, edit a command and add: +// Other > Advanced > Execute an Inline Function > C# Code +// Paste this whole file in. +// 2. Before that action, add "Set a Text Value": +// ~path = /say/sell?commodity={TXT:~commodity} +// 3. After it, add: +// Other > Sounds > Say something with text-to-speech -> {TXT:~answer} +// +// A worked command, "where should I sell [Gold;Laranite;Titanium]": +// Set Text ~commodity to {TXT:1} (from the dynamic phrase list) +// Set Text ~path to /say/sell?commodity={TXT:~commodity} +// Inline C# (this file) +// Say with TTS {TXT:~answer} +// +// Optional text variables, all with sensible defaults: +// ~scmcpUrl base URL (default http://127.0.0.1:7331) +// ~scmcpToken shared secret (only if you set SCMCP_HTTP_TOKEN) +// ~timeoutMs request timeout (default 20000) +// +// Run integrations/voiceattack/generate-grammar.mjs to produce the +// [Gold;Laranite;...] phrase list from live commodity data. + +using System; +using System.IO; +using System.Net; +using System.Text; + +public class VAInline +{ + public void main() + { + string answer; + + try + { + string baseUrl = VA.GetText("~scmcpUrl"); + if (string.IsNullOrEmpty(baseUrl)) baseUrl = "http://127.0.0.1:7331"; + + string path = VA.GetText("~path"); + if (string.IsNullOrEmpty(path)) + { + VA.SetText("~answer", "No request path was set."); + VA.WriteToLog("SCMCP: ~path is empty; nothing to request.", "red"); + return; + } + + int timeoutMs = 20000; + string timeoutText = VA.GetText("~timeoutMs"); + if (!string.IsNullOrEmpty(timeoutText)) int.TryParse(timeoutText, out timeoutMs); + + answer = Get(baseUrl.TrimEnd('/') + path, VA.GetText("~scmcpToken"), timeoutMs); + } + catch (WebException ex) + { + // Distinguish "daemon isn't running" from "daemon said no", because + // the fix is completely different and you can't read a log in flight. + if (ex.Status == WebExceptionStatus.ConnectFailure) + { + answer = "The Star Citizen daemon is not running."; + } + else if (ex.Status == WebExceptionStatus.Timeout) + { + answer = "That lookup timed out."; + } + else + { + answer = ReadErrorBody(ex); + } + VA.WriteToLog("SCMCP: " + ex.Message, "red"); + } + catch (Exception ex) + { + answer = "That lookup failed."; + VA.WriteToLog("SCMCP: " + ex.Message, "red"); + } + + VA.SetText("~answer", answer); + } + + private string Get(string url, string token, int timeoutMs) + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + request.Method = "GET"; + request.Timeout = timeoutMs; + request.ReadWriteTimeout = timeoutMs; + // The daemon rejects anything that looks browser-originated, so send no + // Origin header. Loopback should never go through a configured proxy. + request.Proxy = null; + request.UserAgent = "SCMCP-VoiceAttack"; + if (!string.IsNullOrEmpty(token)) request.Headers.Add("X-SCMCP-Token", token); + + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) + using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) + { + return reader.ReadToEnd().Trim(); + } + } + + private string ReadErrorBody(WebException ex) + { + // /say and /ask return speakable text even on 4xx, so prefer the body. + try + { + if (ex.Response != null) + { + using (StreamReader reader = + new StreamReader(ex.Response.GetResponseStream(), Encoding.UTF8)) + { + string body = reader.ReadToEnd().Trim(); + if (!string.IsNullOrEmpty(body) && !body.StartsWith("{")) return body; + } + } + } + catch { /* fall through to the generic message */ } + + return "That lookup failed."; + } +} diff --git a/integrations/voiceattack/generate-grammar.mjs b/integrations/voiceattack/generate-grammar.mjs new file mode 100644 index 0000000..945b440 --- /dev/null +++ b/integrations/voiceattack/generate-grammar.mjs @@ -0,0 +1,114 @@ +#!/usr/bin/env node +/** + * Generate a VoiceAttack dynamic phrase list from live commodity data. + * + * Dictation mode will mis-hear "Laranite" more often than not. A closed grammar + * — `[Gold;Laranite;Titanium]` with the match exposed as {TXT:1} — gets the + * recognizer a fixed vocabulary and is dramatically more accurate. The cost is + * that the list has to be regenerated when CIG adds commodities, which is what + * this script is for. + * + * Usage: + * node integrations/voiceattack/generate-grammar.mjs # print to stdout + * node integrations/voiceattack/generate-grammar.mjs -o out.txt # write to a file + * + * Requires the daemon to be running (npm run daemon). + */ + +import { writeFileSync } from "node:fs"; + +const baseUrl = process.env.SCMCP_URL ?? "http://127.0.0.1:7331"; +const token = process.env.SCMCP_HTTP_TOKEN; + +const outIndex = process.argv.findIndex((a) => a === "-o" || a === "--out"); +const outFile = outIndex !== -1 ? process.argv[outIndex + 1] : undefined; + +/** + * VoiceAttack uses ; to separate alternatives and [] to delimit the list, so a + * name containing either would silently corrupt the grammar. Commas and + * parentheses confuse the recognizer without breaking it, so strip those too. + */ +function speakable(name) { + return name + .replace(/[[\];]/g, " ") + .replace(/[(),]/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +async function main() { + const url = `${baseUrl.replace(/\/+$/, "")}/q/uex_get_commodities`; + const headers = token ? { "X-SCMCP-Token": token } : {}; + + let response; + try { + response = await fetch(url, { headers }); + } catch (error) { + console.error(`Could not reach the daemon at ${baseUrl} — is it running? (npm run daemon)`); + console.error(String(error)); + process.exit(1); + } + + if (!response.ok) { + console.error(`Daemon returned ${response.status}: ${await response.text()}`); + process.exit(1); + } + + const data = await response.json(); + if (!Array.isArray(data)) { + console.error("Expected an array of commodities. Got:"); + console.error(JSON.stringify(data, null, 2).slice(0, 500)); + process.exit(1); + } + + const names = [ + ...new Set( + data + .map((row) => (row && typeof row.name === "string" ? row.name : row?.commodity_name)) + .filter((name) => typeof name === "string" && name.trim() !== "") + .map(speakable) + .filter(Boolean), + ), + ].sort((a, b) => a.localeCompare(b)); + + if (names.length === 0) { + console.error("No commodity names found in the response."); + process.exit(1); + } + + const list = `[${names.join(";")}]`; + const output = `VoiceAttack phrase list — ${names.length} commodities +Generated from ${url} + +Paste the bracketed list into a command's spoken phrase. The matched word is +available as {TXT:1}. + +--- Suggested commands --- + + where should I sell ${list} + where can I buy ${list} + price check ${list} + +For each, the command's actions are: + + Set Text ~commodity to {TXT:1} + Set Text ~path to /say/sell?commodity={TXT:~commodity} + Execute inline C# (integrations/voiceattack/SCMCP.cs) + Say with text-to-speech {TXT:~answer} + +Swap /say/sell for /say/buy on the "where can I buy" command. + +--- Phrase list --- + +${list} +`; + + if (outFile) { + writeFileSync(outFile, output, "utf8"); + console.error(`Wrote ${names.length} commodities to ${outFile}`); + } else { + process.stdout.write(output); + } +} + +main(); diff --git a/package-lock.json b/package-lock.json index 8c0f65d..0cc6ee4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,9 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + "@anthropic-ai/sdk": "^0.116.0", "@modelcontextprotocol/sdk": "^1.29.0", - "axios": "^1.14.0", + "axios": "^1.19.0", "dotenv": "^17.4.1", "zod": "^4.3.6" }, @@ -77,6 +78,27 @@ "dev": true, "license": "MIT" }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.116.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.116.0.tgz", + "integrity": "sha512-4UEapYQ+epLEMsAuLZDvW8ExVSOtHD8a7zTyLzhw0H9RXJ1eilPgmqhjwgcdg22diwx13spw6fJ4rONZ+bS7Ww==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@babel/code-frame": { "version": "7.29.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", @@ -102,6 +124,15 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", + "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -747,9 +778,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -767,9 +795,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -787,9 +812,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -807,9 +829,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -827,9 +846,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -847,9 +863,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1546,6 +1559,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -2191,16 +2210,42 @@ "license": "MIT" }, "node_modules/axios": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.14.0.tgz", - "integrity": "sha512-3Y8yrqLSwjuzpXuZ0oIYZ/XGgLwUIBU3uLvbcpb0pidD9ctpShJd43KSlEEkVQg6DS0G9NKyzOvBfUtDKEyHvQ==", + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.19.0.tgz", + "integrity": "sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==", "license": "MIT", "dependencies": { - "follow-redirects": "^1.15.11", - "form-data": "^4.0.5", + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", "proxy-from-env": "^2.1.0" } }, + "node_modules/axios/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/axios/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/balanced-match": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", @@ -3610,6 +3655,12 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, "node_modules/fast-uri": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", @@ -3758,9 +3809,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "funding": [ { "type": "individual", @@ -3778,16 +3829,16 @@ } }, "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -4075,9 +4126,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -4543,6 +4594,19 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -4749,9 +4813,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4773,9 +4834,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4797,9 +4855,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -4821,9 +4876,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -8734,6 +8786,16 @@ "dev": true, "license": "MIT" }, + "node_modules/standardwebhooks": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz", + "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -9102,6 +9164,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", diff --git a/package.json b/package.json index 7f1c253..c78f3b9 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,20 @@ { "name": "scmcp", "version": "1.0.0", - "description": "", + "description": "MCP server and local daemon for Star Citizen market, trade route, and wiki data.", "main": "dist/index.js", "type": "module", "scripts": { "build": "tsc", "start": "node dist/index.js", + "daemon": "node dist/http.js", "dev": "ts-node src/index.ts", + "dev:daemon": "ts-node src/http.ts", "lint": "eslint \"src/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\"", - "test": "vitest run" + "pretest": "tsc", + "test": "vitest run", + "voice:grammar": "node integrations/voiceattack/generate-grammar.mjs" }, "repository": { "type": "git", @@ -24,8 +28,9 @@ }, "homepage": "https://github.com/voidput/SCMCP#readme", "dependencies": { + "@anthropic-ai/sdk": "^0.116.0", "@modelcontextprotocol/sdk": "^1.29.0", - "axios": "^1.14.0", + "axios": "^1.19.0", "dotenv": "^17.4.1", "zod": "^4.3.6" }, diff --git a/src/ask.ts b/src/ask.ts new file mode 100644 index 0000000..6309d62 --- /dev/null +++ b/src/ask.ts @@ -0,0 +1,114 @@ +import Anthropic from "@anthropic-ai/sdk"; +import { betaTool } from "@anthropic-ai/sdk/helpers/beta/json-schema"; +import { describeError, formatOutput, tools } from "./tools.js"; + +/** + * Natural-language path, for the open-ended questions you can't pre-bind to a + * button or a fixed voice phrase ("what shields does a Carrack ship with?"). + * + * Deliberately NOT routed through MCP: MCP is the adapter Claude Code needs to + * spawn this project as a subprocess. In-process we can hand the same registry + * straight to the SDK's tool runner and skip a hop. + */ + +/** + * Tool results dominate the token bill here — an unfiltered trade-routes + * response is ~10k tokens. The MCP path can afford 40k characters because a + * chat session has room; a spoken one-liner does not. + */ +const ASK_OUTPUT_BUDGET = 8000; + +const DEFAULT_MODEL = "claude-opus-5"; + +const SYSTEM_PROMPT = `You answer Star Citizen questions for a pilot who is currently flying and listening, not reading. + +Rules: +- Answer in one or two spoken sentences. No lists, no markdown, no JSON, no code. +- Lead with the number or name they asked for. Detail after, only if it changes what they'd do. +- Write out what should be said aloud. Say "S C U" rather than "SCU", and write numbers plainly. +- Prices and routes move constantly. Use the tools for anything current; never answer market questions from memory. +- If a tool returns nothing useful, say so in one short sentence rather than guessing.`; + +let client: Anthropic | undefined; + +function getClient(): Anthropic { + if (!client) { + client = new Anthropic(); + } + return client; +} + +export function askAvailable(): boolean { + return Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN); +} + +const runnableTools = tools.map((tool) => + betaTool({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + run: async (input: unknown) => { + try { + const result = await tool.handler(input); + return typeof result === "string" + ? result.slice(0, ASK_OUTPUT_BUDGET) + : formatOutput(result, ASK_OUTPUT_BUDGET); + } catch (error) { + // Hand the failure back to the model so it can recover or say so aloud, + // rather than collapsing the whole request. + return describeError(error); + } + }, + }), +); + +export interface AskResult { + text: string; + model: string; + usage: { + input_tokens: number; + output_tokens: number; + cache_read_input_tokens?: number | null; + }; +} + +export async function ask(question: string): Promise { + const model = process.env.SCMCP_ASK_MODEL || DEFAULT_MODEL; + const effort = process.env.SCMCP_ASK_EFFORT || "low"; + + const message = await getClient().beta.messages.toolRunner({ + model, + max_tokens: 4096, + // Low effort suits a single lookup answered in one sentence; raise it with + // SCMCP_ASK_EFFORT for questions that need real reasoning. + output_config: { effort: effort as "low" | "medium" | "high" | "xhigh" | "max" }, + thinking: { type: "adaptive" }, + system: [ + { + type: "text", + text: SYSTEM_PROMPT, + // Tools render before system, so this breakpoint caches both. The tool + // schemas are the stable prefix; only the question varies per request. + cache_control: { type: "ephemeral" }, + }, + ], + tools: runnableTools, + messages: [{ role: "user", content: question }], + }); + + const text = message.content + .filter((block): block is Anthropic.Beta.BetaTextBlock => block.type === "text") + .map((block) => block.text) + .join(" ") + .trim(); + + return { + text: text || "No answer produced.", + model: message.model, + usage: { + input_tokens: message.usage.input_tokens, + output_tokens: message.usage.output_tokens, + cache_read_input_tokens: message.usage.cache_read_input_tokens, + }, + }; +} diff --git a/src/http.test.ts b/src/http.test.ts new file mode 100644 index 0000000..1453099 --- /dev/null +++ b/src/http.test.ts @@ -0,0 +1,125 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; +import { createServer } from "./http.js"; + +/** + * Covers routing and the request guard. Routes that would call the UEX API are + * exercised only on paths that fail before any network call, so the suite is + * offline. + */ +let server: Server; +let base: string; + +beforeAll(async () => { + server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + base = `http://127.0.0.1:${port}`; +}); + +afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); +}); + +describe("GET /health", () => { + it("reports tool and preset counts", async () => { + const res = await fetch(`${base}/health`); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.status).toBe("ok"); + expect(body.tools).toBeGreaterThan(0); + expect(body.presets).toBeGreaterThan(0); + }); +}); + +describe("discovery routes", () => { + it("lists tools with their schemas", async () => { + const body = await (await fetch(`${base}/tools`)).json(); + expect(Array.isArray(body)).toBe(true); + const prices = body.find((t: { name: string }) => t.name === "uex_get_commodity_prices"); + expect(prices.inputSchema.required).toContain("commodity_name"); + }); + + it("lists voice presets with their parameters", async () => { + const body = await (await fetch(`${base}/presets`)).json(); + const sell = body.find((p: { name: string }) => p.name === "sell"); + expect(sell.params).toContainEqual({ name: "commodity", required: true, type: "string" }); + }); + + it("ignores a trailing slash", async () => { + expect((await fetch(`${base}/health/`)).status).toBe(200); + }); +}); + +describe("request guard", () => { + it("rejects requests carrying a browser Origin", async () => { + const res = await fetch(`${base}/health`, { headers: { Origin: "https://evil.example" } }); + expect(res.status).toBe(403); + }); + + it("rejects cross-site fetches even without an Origin", async () => { + const res = await fetch(`${base}/health`, { headers: { "Sec-Fetch-Site": "cross-site" } }); + expect(res.status).toBe(403); + }); + + it("allows a same-origin-less client such as curl or Stream Deck", async () => { + expect((await fetch(`${base}/health`)).status).toBe(200); + }); + + it("refuses methods other than GET and POST", async () => { + expect((await fetch(`${base}/health`, { method: "DELETE" })).status).toBe(405); + }); +}); + +describe("GET /q/:tool", () => { + it("404s an unknown tool", async () => { + const res = await fetch(`${base}/q/not_a_tool`); + expect(res.status).toBe(404); + expect((await res.json()).error).toContain("Unknown tool"); + }); + + it("returns JSON errors, not prose", async () => { + const res = await fetch(`${base}/q/not_a_tool`); + expect(res.headers.get("content-type")).toContain("application/json"); + }); +}); + +describe("GET /say/:preset", () => { + it("404s an unknown preset with a speakable message", async () => { + const res = await fetch(`${base}/say/nonsense`); + expect(res.status).toBe(404); + expect(res.headers.get("content-type")).toContain("text/plain"); + expect(await res.text()).toBe("Unknown preset nonsense."); + }); + + it("names the missing required parameter", async () => { + const res = await fetch(`${base}/say/sell`); + expect(res.status).toBe(400); + expect(await res.text()).toBe("Missing commodity."); + }); + + it("always answers in plain text so TTS can read the body verbatim", async () => { + const res = await fetch(`${base}/say/sell`); + expect(res.headers.get("content-type")).toContain("text/plain"); + }); +}); + +describe("/ask", () => { + it("rejects an empty question before spending any credit", async () => { + const res = await fetch(`${base}/ask`); + // 400 when credentials exist, 503 when they don't; both are pre-flight. + expect([400, 503]).toContain(res.status); + }); + + it("rejects a malformed POST body", async () => { + const res = await fetch(`${base}/ask`, { method: "POST", body: "not json" }); + expect([400, 503]).toContain(res.status); + }); +}); + +describe("unknown routes", () => { + it("404s", async () => { + expect((await fetch(`${base}/nope`)).status).toBe(404); + }); +}); diff --git a/src/http.ts b/src/http.ts new file mode 100644 index 0000000..d66198b --- /dev/null +++ b/src/http.ts @@ -0,0 +1,226 @@ +import http from "node:http"; +import { pathToFileURL } from "node:url"; +import { coerceArgs, describeError, getTool, tools } from "./tools.js"; +import { presets, presetsByName } from "./voice.js"; + +/** + * Localhost daemon that puts the tool registry behind plain HTTP, because + * Stream Deck and VoiceAttack can hit a URL but cannot speak MCP. + * + * GET /health liveness + which surfaces are enabled + * GET /tools tool names and schemas + * GET /presets voice preset names and parameters + * GET /q/:tool?args raw JSON — for Stream Deck key rendering + * GET /say/:preset?args one sentence of plain text — for TTS + * POST /ask {"q": "..."} natural language via the Anthropic API + * GET /ask?q=... same, so VoiceAttack can use a plain GET + */ + +const DEFAULT_PORT = 7331; +const HOST = "127.0.0.1"; + +/** Optional shared secret; see checkAuth. */ +const TOKEN = process.env.SCMCP_HTTP_TOKEN; + +interface Handled { + status: number; + body: string; + contentType: string; +} + +function json(status: number, data: unknown): Handled { + return { + status, + body: JSON.stringify(data, null, 2), + contentType: "application/json; charset=utf-8", + }; +} + +function text(status: number, body: string): Handled { + return { status, body, contentType: "text/plain; charset=utf-8" }; +} + +/** + * A localhost bind keeps other machines out, but not other software on this + * machine — any page you visit could fetch http://127.0.0.1:7331/ask and spend + * your API credit. Browsers always attach Origin/Sec-Fetch-Site to such a + * request; curl, Stream Deck, and VoiceAttack do not. Reject on that, and + * support an optional shared secret on top. + */ +function checkAuth(req: http.IncomingMessage): string | undefined { + const origin = req.headers.origin; + const fetchSite = req.headers["sec-fetch-site"]; + if (origin || (typeof fetchSite === "string" && fetchSite !== "none")) { + return "Browser-originated requests are not accepted."; + } + + if (TOKEN) { + const header = req.headers["x-scmcp-token"]; + const url = new URL(req.url ?? "/", `http://${HOST}`); + const supplied = typeof header === "string" ? header : url.searchParams.get("token"); + if (supplied !== TOKEN) return "Invalid or missing token."; + } + + return undefined; +} + +function queryToRecord(params: URLSearchParams): Record { + const out: Record = {}; + for (const [key, value] of params) { + if (key === "token") continue; + out[key] = value; + } + return out; +} + +async function readBody(req: http.IncomingMessage, limitBytes = 64 * 1024): Promise { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + const buf = chunk as Buffer; + size += buf.length; + if (size > limitBytes) throw new Error("Request body too large"); + chunks.push(buf); + } + return Buffer.concat(chunks).toString("utf8"); +} + +async function route(req: http.IncomingMessage, url: URL): Promise { + const path = url.pathname.replace(/\/+$/, "") || "/"; + const query = queryToRecord(url.searchParams); + + if (path === "/health") { + const { askAvailable } = await import("./ask.js"); + return json(200, { + status: "ok", + tools: tools.length, + presets: presets.length, + ask: askAvailable() ? "enabled" : "no ANTHROPIC_API_KEY set", + }); + } + + if (path === "/tools") { + return json( + 200, + tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })), + ); + } + + if (path === "/presets") { + return json( + 200, + presets.map(({ name, description, params }) => ({ name, description, params })), + ); + } + + if (path.startsWith("/q/")) { + const toolName = decodeURIComponent(path.slice("/q/".length)); + const tool = getTool(toolName); + if (!tool) return json(404, { error: `Unknown tool: ${toolName}` }); + const args = coerceArgs(tool.inputSchema, query); + return json(200, await tool.handler(args)); + } + + if (path.startsWith("/say/")) { + const presetName = decodeURIComponent(path.slice("/say/".length)); + const preset = presetsByName.get(presetName); + if (!preset) { + return text(404, `Unknown preset ${presetName}.`); + } + const missing = preset.params.filter((p) => p.required && !query[p.name]).map((p) => p.name); + if (missing.length > 0) { + return text(400, `Missing ${missing.join(" and ")}.`); + } + // Presets already return a spoken sentence, including for their own + // failures, so this is always 200 with something safe to read aloud. + return text(200, await preset.render(query)); + } + + if (path === "/ask") { + const { ask, askAvailable } = await import("./ask.js"); + if (!askAvailable()) { + return text(503, "Natural language is unavailable: no Anthropic credentials configured."); + } + + let question = query.q; + if (req.method === "POST") { + const raw = await readBody(req); + try { + const parsed = JSON.parse(raw) as { q?: unknown }; + if (typeof parsed.q === "string") question = parsed.q; + } catch { + return text(400, 'Body must be JSON of the form {"q": "..."}.'); + } + } + + if (!question || question.trim() === "") return text(400, "No question supplied."); + + const result = await ask(question.trim()); + // Plain text by default so VoiceAttack can speak the body verbatim; + // ?format=json when you want the usage numbers too. + if (query.format === "json") return json(200, result); + return text(200, result.text); + } + + return json(404, { error: `No route for ${path}` }); +} + +export function createServer(): http.Server { + return http.createServer((req, res) => { + void (async () => { + const url = new URL(req.url ?? "/", `http://${HOST}`); + let handled: Handled; + + try { + const denied = checkAuth(req); + if (denied) { + handled = text(403, denied); + } else if (req.method !== "GET" && req.method !== "POST") { + handled = text(405, `Method ${req.method} not allowed.`); + } else { + handled = await route(req, url); + } + } catch (error) { + console.error(`[http] ${url.pathname} failed:`, error); + // /say and /ask are spoken aloud, so their errors must be speakable too. + const speakable = url.pathname.startsWith("/say/") || url.pathname === "/ask"; + handled = speakable + ? text(500, "That lookup failed.") + : json(500, { error: describeError(error) }); + } + + res.writeHead(handled.status, { + "Content-Type": handled.contentType, + "Cache-Control": "no-store", + }); + res.end(handled.body); + })(); + }); +} + +function main() { + const port = Number(process.env.SCMCP_HTTP_PORT) || DEFAULT_PORT; + const server = createServer(); + + server.listen(port, HOST, () => { + console.error(`SCMCP daemon listening on http://${HOST}:${port}`); + console.error(` ${tools.length} tools, ${presets.length} voice presets`); + if (!TOKEN) { + console.error(" no SCMCP_HTTP_TOKEN set — any local process can reach this daemon"); + } + }); + + server.on("error", (error) => { + console.error("Fatal error in daemon:", error); + process.exit(1); + }); + + for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.on(signal, () => server.close(() => process.exit(0))); + } +} + +// Only start listening when run directly, so tests can import createServer. +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main(); +} diff --git a/src/index.test.ts b/src/index.test.ts deleted file mode 100644 index 4080cd2..0000000 --- a/src/index.test.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { describe, it, expect } from "vitest"; - -describe("SCMCP", () => { - it("should be configured correctly", () => { - expect(true).toBe(true); - }); -}); diff --git a/src/index.ts b/src/index.ts index 213e4eb..fb2f931 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,34 +1,7 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; -import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; -import dotenv from "dotenv"; -import { z } from "zod"; - -dotenv.config(); - -const UEX_API_KEY = process.env.UEXTOKEN; -const UEX_BASE_URL = "https://api.uexcorp.space/2.0"; -const SCW_BASE_URL = "https://api.star-citizen.wiki/api/v2"; - -if (!UEX_API_KEY) { - console.error("UEXTOKEN not found in .env file"); -} - -const uexClient = axios.create({ - baseURL: UEX_BASE_URL, - headers: { - Authorization: `Bearer ${UEX_API_KEY}`, - }, -}); - -const scwClient = axios.create({ - baseURL: SCW_BASE_URL, -}); - -const sctClient = axios.create({ - baseURL: "https://starcitizen.tools", -}); +import { describeError, formatOutput, getTool, tools } from "./tools.js"; const server = new Server( { @@ -47,242 +20,14 @@ const server = new Server( */ server.setRequestHandler(ListToolsRequestSchema, async () => { return { - tools: [ - { - name: "uex_get_commodities", - description: "Get a list of all commodities in Star Citizen from UEX Corp.", - inputSchema: { - type: "object", - properties: {}, - }, - }, - { - name: "uex_get_commodity_prices", - description: - "Get current prices for a specific commodity from UEX Corp. Returns buy/sell prices at various terminals.", - inputSchema: { - type: "object", - properties: { - commodity_name: { - type: "string", - description: "The name of the commodity (e.g., 'Gold', 'Laranite').", - }, - star_system_name: { - type: "string", - description: "Optional: Filter by star system (e.g., 'Stanton', 'Pyro').", - }, - planet_name: { - type: "string", - description: "Optional: Filter by planet name.", - }, - terminal_name: { - type: "string", - description: "Optional: Filter by terminal name.", - }, - }, - required: ["commodity_name"], - }, - }, - { - name: "uex_get_commodity_averages", - description: "Get average prices for a specific commodity over time from UEX Corp.", - inputSchema: { - type: "object", - properties: { - commodity_name: { - type: "string", - description: "The name of the commodity (e.g., 'Gold', 'Laranite').", - }, - }, - required: ["commodity_name"], - }, - }, - { - name: "uex_get_terminals", - description: "Get a list of all terminals (locations) in Star Citizen from UEX Corp.", - inputSchema: { - type: "object", - properties: { - star_system_name: { - type: "string", - description: "Optional: Filter by star system (e.g., 'Stanton', 'Pyro').", - }, - planet_name: { - type: "string", - description: "Optional: Filter by planet name.", - }, - }, - }, - }, - { - name: "uex_get_trade_routes", - description: "Get suggested trade routes based on current market data from UEX Corp.", - inputSchema: { - type: "object", - properties: { - investment: { - type: "number", - description: "Available credits for investment.", - }, - cargo_capacity: { - type: "number", - description: "Cargo capacity in SCU.", - }, - }, - }, - }, - { - name: "uex_get_commodity_ranking", - description: - "Get ranking of commodities based on various metrics (e.g., profit) from UEX Corp.", - inputSchema: { - type: "object", - properties: {}, - }, - }, - { - name: "scw_search", - description: "Search the Star Citizen Wiki for any item, ship, or lore topic.", - inputSchema: { - type: "object", - properties: { - query: { - type: "string", - description: "The search query.", - }, - }, - required: ["query"], - }, - }, - { - name: "scw_get_vehicle", - description: - "Get detailed information about a vehicle (ship/ground vehicle) from the Star Citizen Wiki.", - inputSchema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the vehicle (e.g., '300i', 'Carrack').", - }, - }, - required: ["name"], - }, - }, - { - name: "scw_get_item", - description: - "Get detailed information about an item (weapon, armor, component) from the Star Citizen Wiki.", - inputSchema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the item (e.g., 'FS-9 LMG', 'Lynx Helmet').", - }, - }, - required: ["name"], - }, - }, - { - name: "sct_search", - description: "Search Star Citizen Tools (starcitizen.tools) for any topic.", - inputSchema: { - type: "object", - properties: { - query: { - type: "string", - description: "The search query.", - }, - }, - required: ["query"], - }, - }, - { - name: "sct_get_article", - description: - "Get the text content of an article from Star Citizen Tools (starcitizen.tools).", - inputSchema: { - type: "object", - properties: { - title: { - type: "string", - description: "The title of the article (e.g., 'Wikelo', 'Carrack').", - }, - }, - required: ["title"], - }, - }, - ], + tools: tools.map(({ name, description, inputSchema }) => ({ + name, + description, + inputSchema, + })), }; }); -function isObject(data: unknown): data is Record { - return typeof data === "object" && data !== null && !Array.isArray(data); -} - -function optimizeData(data: unknown): unknown { - if (Array.isArray(data)) { - return data.map(optimizeData); - } else if (isObject(data)) { - return Object.fromEntries( - Object.entries(data) - .filter(([k, v]) => { - // Remove empty values to save context - if (v === null || v === "" || v === 0) return false; - // Filter out bulky historical/statistical data from UEX - if ( - k.includes("_min") || - k.includes("_max") || - k.includes("_avg") || - k.includes("_week") || - k.includes("_month") - ) - return false; - if (k.startsWith("volatility_") || k.startsWith("id_")) return false; - if (k === "date_added" || k === "date_modified") return false; - return true; - }) - .map(([k, v]) => [k, optimizeData(v)]), - ); - } - return data; -} - -function formatOutput(data: unknown): string { - const optimized = optimizeData(data); - let jsonStr = JSON.stringify(optimized, null, 2); - - if (jsonStr.length > 40000) { - jsonStr = JSON.stringify(optimized); // Fallback to minified JSON - } - - if (jsonStr.length > 40000) { - const note = "\n... [Output truncated due to excessive length]"; - jsonStr = jsonStr.substring(0, 40000 - note.length) + note; - } - - return jsonStr; -} - -const cache = new Map(); -const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes - -async function fetchWithCache(client: AxiosInstance, url: string, config?: AxiosRequestConfig) { - const cacheKey = (client.defaults?.baseURL || "") + url + JSON.stringify(config?.params || {}); - const cached = cache.get(cacheKey); - - if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) { - console.error(`[Cache Hit] ${cacheKey}`); - return { data: cached.data }; - } - - console.error(`[Cache Miss] ${cacheKey}`); - const response = await client.get(url, config); - cache.set(cacheKey, { data: response.data, timestamp: Date.now() }); - return { data: response.data }; -} - /** * Handle tool calls. */ @@ -290,229 +35,28 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { - if (name === "uex_get_commodities") { - const response = await fetchWithCache(uexClient, "/commodities"); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; - } - - if (name === "uex_get_commodity_prices") { - const { commodity_name, star_system_name, planet_name, terminal_name } = z - .object({ - commodity_name: z.string(), - star_system_name: z.string().optional(), - planet_name: z.string().optional(), - terminal_name: z.string().optional(), - }) - .parse(args); - const response = await fetchWithCache(uexClient, "/commodities_prices", { - params: { commodity_name }, - }); - - let data = response.data.data; - if (Array.isArray(data)) { - if (star_system_name) { - data = data.filter( - (d: Record) => - typeof d.star_system_name === "string" && - d.star_system_name.toLowerCase() === star_system_name.toLowerCase(), - ); - } - if (planet_name) { - data = data.filter( - (d: Record) => - typeof d.planet_name === "string" && - d.planet_name.toLowerCase() === planet_name.toLowerCase(), - ); - } - if (terminal_name) { - data = data.filter( - (d: Record) => - typeof d.terminal_name === "string" && - d.terminal_name.toLowerCase() === terminal_name.toLowerCase(), - ); - } - } - - return { - content: [{ type: "text", text: formatOutput(data) }], - }; - } - - if (name === "uex_get_commodity_averages") { - const { commodity_name } = z.object({ commodity_name: z.string() }).parse(args); - const response = await fetchWithCache(uexClient, "/commodities_averages", { - params: { commodity_name }, - }); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; - } - - if (name === "uex_get_terminals") { - const { star_system_name, planet_name } = z - .object({ - star_system_name: z.string().optional(), - planet_name: z.string().optional(), - }) - .parse(args || {}); - const response = await fetchWithCache(uexClient, "/terminals"); - - let data = response.data.data; - if (Array.isArray(data)) { - if (star_system_name) { - data = data.filter( - (d: Record) => - typeof d.star_system_name === "string" && - d.star_system_name.toLowerCase() === star_system_name.toLowerCase(), - ); - } - if (planet_name) { - data = data.filter( - (d: Record) => - typeof d.planet_name === "string" && - d.planet_name.toLowerCase() === planet_name.toLowerCase(), - ); - } - } - - return { - content: [{ type: "text", text: formatOutput(data) }], - }; - } - - if (name === "uex_get_trade_routes") { - const { investment, cargo_capacity } = z - .object({ - investment: z.number().optional(), - cargo_capacity: z.number().optional(), - }) - .parse(args); - const response = await fetchWithCache(uexClient, "/commodities_routes", { - params: { investment, scu: cargo_capacity }, - }); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; - } - - if (name === "uex_get_commodity_ranking") { - const response = await fetchWithCache(uexClient, "/commodities_ranking"); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; + const tool = getTool(name); + if (!tool) { + throw new Error(`Unknown tool: ${name}`); } - if (name === "scw_search") { - const { query } = z.object({ query: z.string() }).parse(args); - // Using MediaWiki API for search as it's more flexible for general queries - const response = await fetchWithCache(scwClient, "https://star-citizen.wiki/api.php", { - params: { - action: "opensearch", - search: query, - format: "json", - limit: 10, - }, - }); - return { - content: [{ type: "text", text: formatOutput(response.data) }], - }; - } + const result = await tool.handler(args); - if (name === "scw_get_vehicle") { - const { name: vehicleName } = z.object({ name: z.string() }).parse(args); - const response = await fetchWithCache( - scwClient, - `/vehicles/${encodeURIComponent(vehicleName)}`, - ); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; - } - - if (name === "scw_get_item") { - const { name: itemName } = z.object({ name: z.string() }).parse(args); - const response = await fetchWithCache(scwClient, `/items/${encodeURIComponent(itemName)}`); - return { - content: [{ type: "text", text: formatOutput(response.data.data) }], - }; - } - - if (name === "sct_search") { - const { query } = z.object({ query: z.string() }).parse(args); - const response = await fetchWithCache(sctClient, "/api.php", { - params: { - action: "opensearch", - search: query, - format: "json", - limit: 10, - }, - }); - return { - content: [{ type: "text", text: formatOutput(response.data) }], - }; - } - - if (name === "sct_get_article") { - const { title } = z.object({ title: z.string() }).parse(args); - const response = await fetchWithCache(sctClient, "/api.php", { - params: { - action: "query", - prop: "extracts", - explaintext: "1", - format: "json", - titles: title, + return { + content: [ + { + type: "text", + text: typeof result === "string" ? result : formatOutput(result), }, - }); - - let textContent = ""; - if ( - response.data && - isObject(response.data) && - isObject(response.data.query) && - isObject(response.data.query.pages) - ) { - const pages = response.data.query.pages; - const pageId = Object.keys(pages)[0]; - if (pageId !== "-1" && isObject(pages[pageId])) { - textContent = (pages[pageId].extract as string) || ""; - } else { - textContent = "Article not found."; - } - } - - return { - content: [{ type: "text", text: textContent || formatOutput(response.data) }], - }; - } - - throw new Error(`Unknown tool: ${name}`); + ], + }; } catch (error: unknown) { - let errorMessage = "Unknown error occurred"; - let details = ""; - - if (error instanceof Error) { - errorMessage = error.message; - } - - if ( - error && - typeof error === "object" && - "response" in error && - error.response && - typeof error.response === "object" && - "data" in error.response - ) { - details = JSON.stringify(error.response.data); - } - return { isError: true, content: [ { type: "text", - text: `Error: ${errorMessage}${details ? `\nDetails: ${details}` : ""}`, + text: describeError(error), }, ], }; diff --git a/src/mcp.test.ts b/src/mcp.test.ts new file mode 100644 index 0000000..35c2b5b --- /dev/null +++ b/src/mcp.test.ts @@ -0,0 +1,147 @@ +import { describe, it, expect } from "vitest"; +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +/** + * Contract test for the stdio transport, run against the built server rather + * than the module graph. + * + * This has to be a subprocess test: the failure it guards against is a + * dependency writing to the real stdout at startup (dotenv v17 shipped a banner + * that did exactly this, corrupting every MCP session). In-process assertions + * miss it, because the test runner has already replaced stdout by the time any + * import runs. + */ + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const serverPath = join(root, "dist", "index.js"); + +interface JsonRpcResponse { + jsonrpc: string; + id?: number; + result?: Record; + error?: Record; +} + +function runServer(requests: unknown[], timeoutMs = 15000): Promise<{ stdout: string }> { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [serverPath], { + cwd: root, + stdio: ["pipe", "pipe", "pipe"], + // A token is not needed: these requests never reach the network. + env: { ...process.env, UEXTOKEN: process.env.UEXTOKEN ?? "test-token" }, + }); + + let stdout = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + stdout += chunk; + }); + + const timer = setTimeout(() => { + child.kill(); + reject(new Error(`Server did not respond within ${timeoutMs}ms`)); + }, timeoutMs); + + child.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + + child.on("close", () => { + clearTimeout(timer); + resolve({ stdout }); + }); + + for (const request of requests) { + child.stdin.write(JSON.stringify(request) + "\n"); + } + child.stdin.end(); + }); +} + +const INITIALIZE = { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2024-11-05", + capabilities: {}, + clientInfo: { name: "scmcp-test", version: "1.0.0" }, + }, +}; +const INITIALIZED = { jsonrpc: "2.0", method: "notifications/initialized" }; + +describe("MCP stdio server", () => { + it("has been built", () => { + // `npm test` runs tsc first via pretest; this makes a missing build obvious + // rather than surfacing as a spawn failure further down. + expect(existsSync(serverPath)).toBe(true); + }); + + it("emits nothing on stdout but JSON-RPC frames", async () => { + const { stdout } = await runServer([ + INITIALIZE, + INITIALIZED, + { jsonrpc: "2.0", id: 2, method: "tools/list" }, + ]); + + const lines = stdout.split("\n").filter((line) => line.trim() !== ""); + expect(lines.length).toBeGreaterThan(0); + + for (const line of lines) { + // Any banner, log line, or stray console.log fails here. + const parsed = JSON.parse(line) as JsonRpcResponse; + expect(parsed.jsonrpc).toBe("2.0"); + } + }, 20000); + + it("completes the initialize handshake", async () => { + const { stdout } = await runServer([INITIALIZE]); + const response = JSON.parse(stdout.split("\n")[0]) as JsonRpcResponse; + expect(response.id).toBe(1); + expect(response.result?.serverInfo).toMatchObject({ name: "star-citizen-mcp" }); + }, 20000); + + it("advertises every tool with its schema", async () => { + const { stdout } = await runServer([ + INITIALIZE, + INITIALIZED, + { jsonrpc: "2.0", id: 2, method: "tools/list" }, + ]); + + const responses = stdout + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as JsonRpcResponse); + + const list = responses.find((r) => r.id === 2); + const toolList = list?.result?.tools as { name: string; inputSchema: unknown }[]; + + expect(toolList).toHaveLength(11); + expect(toolList.map((t) => t.name)).toContain("uex_get_trade_routes"); + for (const tool of toolList) { + expect(tool.inputSchema).toBeTruthy(); + } + }, 20000); + + it("returns an error result rather than crashing on an unknown tool", async () => { + const { stdout } = await runServer([ + INITIALIZE, + INITIALIZED, + { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "nope", arguments: {} } }, + ]); + + const responses = stdout + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as JsonRpcResponse); + + const call = responses.find((r) => r.id === 3); + expect(call?.result?.isError).toBe(true); + const content = call?.result?.content as { text: string }[]; + expect(content[0].text).toContain("Unknown tool: nope"); + }, 20000); +}); diff --git a/src/tools.test.ts b/src/tools.test.ts new file mode 100644 index 0000000..376efb1 --- /dev/null +++ b/src/tools.test.ts @@ -0,0 +1,166 @@ +import { describe, it, expect } from "vitest"; +import { + coerceArgs, + describeError, + formatOutput, + getTool, + optimizeData, + tools, + type JsonSchema, +} from "./tools.js"; + +describe("tool registry", () => { + it("exposes every documented tool under a unique name", () => { + const names = tools.map((t) => t.name); + expect(new Set(names).size).toBe(names.length); + expect(names).toEqual( + expect.arrayContaining([ + "uex_get_commodities", + "uex_get_commodity_prices", + "uex_get_commodity_averages", + "uex_get_terminals", + "uex_get_trade_routes", + "uex_get_commodity_ranking", + "scw_search", + "scw_get_vehicle", + "scw_get_item", + "sct_search", + "sct_get_article", + ]), + ); + }); + + it("only marks parameters required if they are also declared", () => { + for (const tool of tools) { + for (const key of tool.inputSchema.required ?? []) { + expect(Object.keys(tool.inputSchema.properties)).toContain(key); + } + } + }); + + it("resolves tools by name and returns undefined otherwise", () => { + expect(getTool("uex_get_commodities")?.name).toBe("uex_get_commodities"); + expect(getTool("does_not_exist")).toBeUndefined(); + }); +}); + +describe("coerceArgs", () => { + const schema: JsonSchema = { + type: "object", + properties: { + commodity_name: { type: "string" }, + investment: { type: "number" }, + cargo_capacity: { type: "integer" }, + verbose: { type: "boolean" }, + }, + }; + + it("converts numeric query params to numbers", () => { + expect(coerceArgs(schema, { investment: "1000000", cargo_capacity: "96" })).toEqual({ + investment: 1000000, + cargo_capacity: 96, + }); + }); + + it("leaves string params alone", () => { + expect(coerceArgs(schema, { commodity_name: "Gold" })).toEqual({ commodity_name: "Gold" }); + }); + + it("treats an empty value as absent so ?x= does not become an empty string", () => { + expect(coerceArgs(schema, { commodity_name: "" })).toEqual({}); + }); + + it("drops params the tool does not declare", () => { + expect(coerceArgs(schema, { commodity_name: "Gold", nonsense: "1" })).toEqual({ + commodity_name: "Gold", + }); + }); + + it("reads booleans, treating only false and 0 as false", () => { + expect(coerceArgs(schema, { verbose: "true" }).verbose).toBe(true); + expect(coerceArgs(schema, { verbose: "false" }).verbose).toBe(false); + expect(coerceArgs(schema, { verbose: "0" }).verbose).toBe(false); + }); + + it("rejects a non-numeric value for a numeric param", () => { + expect(() => coerceArgs(schema, { investment: "lots" })).toThrow(/must be a number/); + }); +}); + +describe("optimizeData", () => { + it("drops empty values and bulky statistical fields", () => { + const input = { + commodity_name: "Gold", + price_sell: 32500, + price_sell_avg: 31000, + price_sell_min: 100, + volatility_price_sell: 3, + id_terminal: 42, + date_added: 1700000000, + empty_string: "", + zero: 0, + nothing: null, + }; + expect(optimizeData(input)).toEqual({ commodity_name: "Gold", price_sell: 32500 }); + }); + + it("recurses through arrays", () => { + expect( + optimizeData([ + { a: 1, b: 0 }, + { a: 2, b: null }, + ]), + ).toEqual([{ a: 1 }, { a: 2 }]); + }); + + it("passes primitives through untouched", () => { + expect(optimizeData("Gold")).toBe("Gold"); + expect(optimizeData(7)).toBe(7); + }); +}); + +describe("formatOutput", () => { + it("pretty-prints when the result fits the budget", () => { + expect(formatOutput({ a: 1 })).toBe('{\n "a": 1\n}'); + }); + + it("falls back to minified JSON before truncating", () => { + const rows = Array.from({ length: 40 }, (_, i) => ({ commodity_name: `C${i}` })); + // Budget sits between the pretty-printed and minified lengths. + const out = formatOutput(rows, 1100); + expect(out).not.toContain("\n "); + expect(out).not.toContain("truncated"); + expect(JSON.parse(out)).toHaveLength(40); + }); + + it("truncates once even minified output exceeds the budget", () => { + const rows = Array.from({ length: 500 }, (_, i) => ({ commodity_name: `Commodity ${i}` })); + const out = formatOutput(rows, 400); + expect(out.length).toBeLessThanOrEqual(400); + expect(out).toContain("[Output truncated due to excessive length]"); + }); + + it("applies a tighter budget when the caller asks for one", () => { + const rows = Array.from({ length: 500 }, (_, i) => ({ commodity_name: `Commodity ${i}` })); + expect(formatOutput(rows, 400).length).toBeLessThan(formatOutput(rows, 8000).length); + }); +}); + +describe("describeError", () => { + it("reports a plain error message", () => { + expect(describeError(new Error("boom"))).toBe("Error: boom"); + }); + + it("appends upstream response details when present", () => { + const axiosLike = Object.assign(new Error("Request failed"), { + response: { data: { message: "bad token" } }, + }); + expect(describeError(axiosLike)).toBe( + 'Error: Request failed\nDetails: {"message":"bad token"}', + ); + }); + + it("handles values that are not Errors", () => { + expect(describeError("nope")).toBe("Error: Unknown error occurred"); + }); +}); diff --git a/src/tools.ts b/src/tools.ts new file mode 100644 index 0000000..394029e --- /dev/null +++ b/src/tools.ts @@ -0,0 +1,496 @@ +import axios, { AxiosInstance, AxiosRequestConfig } from "axios"; +import dotenv from "dotenv"; +import { z } from "zod"; + +// quiet is essential, not cosmetic: dotenv v17 prints a banner to stdout, and +// the MCP transport requires stdout to carry nothing but JSON-RPC frames. +dotenv.config({ quiet: true }); + +const UEX_API_KEY = process.env.UEXTOKEN; +const UEX_BASE_URL = "https://api.uexcorp.space/2.0"; +const SCW_BASE_URL = "https://api.star-citizen.wiki/api/v2"; + +if (!UEX_API_KEY) { + console.error("UEXTOKEN not found in .env file"); +} + +const uexClient = axios.create({ + baseURL: UEX_BASE_URL, + headers: { + Authorization: `Bearer ${UEX_API_KEY}`, + }, +}); + +const scwClient = axios.create({ + baseURL: SCW_BASE_URL, +}); + +const sctClient = axios.create({ + baseURL: "https://starcitizen.tools", +}); + +export function isObject(data: unknown): data is Record { + return typeof data === "object" && data !== null && !Array.isArray(data); +} + +/** + * Strip bulky and empty fields to save model context. + * + * This is a presentation concern for LLM consumers only. Tool handlers return + * raw upstream data so that non-LLM adapters (the HTTP daemon, voice presets) + * can read fields this would otherwise discard. + */ +export function optimizeData(data: unknown): unknown { + if (Array.isArray(data)) { + return data.map(optimizeData); + } else if (isObject(data)) { + return Object.fromEntries( + Object.entries(data) + .filter(([k, v]) => { + // Remove empty values to save context + if (v === null || v === "" || v === 0) return false; + // Filter out bulky historical/statistical data from UEX + if ( + k.includes("_min") || + k.includes("_max") || + k.includes("_avg") || + k.includes("_week") || + k.includes("_month") + ) + return false; + if (k.startsWith("volatility_") || k.startsWith("id_")) return false; + if (k === "date_added" || k === "date_modified") return false; + return true; + }) + .map(([k, v]) => [k, optimizeData(v)]), + ); + } + return data; +} + +export const DEFAULT_OUTPUT_BUDGET = 40000; + +export function formatOutput(data: unknown, maxLength: number = DEFAULT_OUTPUT_BUDGET): string { + const optimized = optimizeData(data); + let jsonStr = JSON.stringify(optimized, null, 2); + + if (jsonStr.length > maxLength) { + jsonStr = JSON.stringify(optimized); // Fallback to minified JSON + } + + if (jsonStr.length > maxLength) { + const note = "\n... [Output truncated due to excessive length]"; + jsonStr = jsonStr.substring(0, maxLength - note.length) + note; + } + + return jsonStr; +} + +const cache = new Map(); +const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes + +export function clearCache() { + cache.clear(); +} + +async function fetchWithCache(client: AxiosInstance, url: string, config?: AxiosRequestConfig) { + const cacheKey = (client.defaults?.baseURL || "") + url + JSON.stringify(config?.params || {}); + const cached = cache.get(cacheKey); + + if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) { + console.error(`[Cache Hit] ${cacheKey}`); + return { data: cached.data }; + } + + console.error(`[Cache Miss] ${cacheKey}`); + const response = await client.get(url, config); + cache.set(cacheKey, { data: response.data, timestamp: Date.now() }); + return { data: response.data }; +} + +function filterByField(data: unknown, field: string, value: string | undefined) { + if (!value || !Array.isArray(data)) return data; + return data.filter( + (d: Record) => + typeof d[field] === "string" && (d[field] as string).toLowerCase() === value.toLowerCase(), + ); +} + +export type JsonSchemaType = + | "string" + | "number" + | "integer" + | "boolean" + | "array" + | "object" + | "null"; + +export interface JsonSchema { + type: "object"; + properties: Record; + required?: string[]; +} + +export interface ToolDefinition { + name: string; + description: string; + inputSchema: JsonSchema; + /** + * Returns raw upstream data. A string return is emitted verbatim by adapters; + * anything else is serialized by the adapter that consumes it. + */ + handler: (args: unknown) => Promise; +} + +export const tools: ToolDefinition[] = [ + { + name: "uex_get_commodities", + description: "Get a list of all commodities in Star Citizen from UEX Corp.", + inputSchema: { + type: "object", + properties: {}, + }, + handler: async () => { + const response = await fetchWithCache(uexClient, "/commodities"); + return response.data.data; + }, + }, + { + name: "uex_get_commodity_prices", + description: + "Get current prices for a specific commodity from UEX Corp. Returns buy/sell prices at various terminals.", + inputSchema: { + type: "object", + properties: { + commodity_name: { + type: "string", + description: "The name of the commodity (e.g., 'Gold', 'Laranite').", + }, + star_system_name: { + type: "string", + description: "Optional: Filter by star system (e.g., 'Stanton', 'Pyro').", + }, + planet_name: { + type: "string", + description: "Optional: Filter by planet name.", + }, + terminal_name: { + type: "string", + description: "Optional: Filter by terminal name.", + }, + }, + required: ["commodity_name"], + }, + handler: async (args) => { + const { commodity_name, star_system_name, planet_name, terminal_name } = z + .object({ + commodity_name: z.string(), + star_system_name: z.string().optional(), + planet_name: z.string().optional(), + terminal_name: z.string().optional(), + }) + .parse(args); + const response = await fetchWithCache(uexClient, "/commodities_prices", { + params: { commodity_name }, + }); + + let data = response.data.data; + data = filterByField(data, "star_system_name", star_system_name); + data = filterByField(data, "planet_name", planet_name); + data = filterByField(data, "terminal_name", terminal_name); + return data; + }, + }, + { + name: "uex_get_commodity_averages", + description: "Get average prices for a specific commodity over time from UEX Corp.", + inputSchema: { + type: "object", + properties: { + commodity_name: { + type: "string", + description: "The name of the commodity (e.g., 'Gold', 'Laranite').", + }, + }, + required: ["commodity_name"], + }, + handler: async (args) => { + const { commodity_name } = z.object({ commodity_name: z.string() }).parse(args); + const response = await fetchWithCache(uexClient, "/commodities_averages", { + params: { commodity_name }, + }); + return response.data.data; + }, + }, + { + name: "uex_get_terminals", + description: "Get a list of all terminals (locations) in Star Citizen from UEX Corp.", + inputSchema: { + type: "object", + properties: { + star_system_name: { + type: "string", + description: "Optional: Filter by star system (e.g., 'Stanton', 'Pyro').", + }, + planet_name: { + type: "string", + description: "Optional: Filter by planet name.", + }, + }, + }, + handler: async (args) => { + const { star_system_name, planet_name } = z + .object({ + star_system_name: z.string().optional(), + planet_name: z.string().optional(), + }) + .parse(args || {}); + const response = await fetchWithCache(uexClient, "/terminals"); + + let data = response.data.data; + data = filterByField(data, "star_system_name", star_system_name); + data = filterByField(data, "planet_name", planet_name); + return data; + }, + }, + { + name: "uex_get_trade_routes", + description: "Get suggested trade routes based on current market data from UEX Corp.", + inputSchema: { + type: "object", + properties: { + investment: { + type: "number", + description: "Available credits for investment.", + }, + cargo_capacity: { + type: "number", + description: "Cargo capacity in SCU.", + }, + }, + }, + handler: async (args) => { + const { investment, cargo_capacity } = z + .object({ + investment: z.number().optional(), + cargo_capacity: z.number().optional(), + }) + .parse(args || {}); + const response = await fetchWithCache(uexClient, "/commodities_routes", { + params: { investment, scu: cargo_capacity }, + }); + return response.data.data; + }, + }, + { + name: "uex_get_commodity_ranking", + description: + "Get ranking of commodities based on various metrics (e.g., profit) from UEX Corp.", + inputSchema: { + type: "object", + properties: {}, + }, + handler: async () => { + const response = await fetchWithCache(uexClient, "/commodities_ranking"); + return response.data.data; + }, + }, + { + name: "scw_search", + description: "Search the Star Citizen Wiki for any item, ship, or lore topic.", + inputSchema: { + type: "object", + properties: { + query: { + type: "string", + description: "The search query.", + }, + }, + required: ["query"], + }, + handler: async (args) => { + const { query } = z.object({ query: z.string() }).parse(args); + // Using MediaWiki API for search as it's more flexible for general queries + const response = await fetchWithCache(scwClient, "https://star-citizen.wiki/api.php", { + params: { + action: "opensearch", + search: query, + format: "json", + limit: 10, + }, + }); + return response.data; + }, + }, + { + name: "scw_get_vehicle", + description: + "Get detailed information about a vehicle (ship/ground vehicle) from the Star Citizen Wiki.", + inputSchema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the vehicle (e.g., '300i', 'Carrack').", + }, + }, + required: ["name"], + }, + handler: async (args) => { + const { name: vehicleName } = z.object({ name: z.string() }).parse(args); + const response = await fetchWithCache( + scwClient, + `/vehicles/${encodeURIComponent(vehicleName)}`, + ); + return response.data.data; + }, + }, + { + name: "scw_get_item", + description: + "Get detailed information about an item (weapon, armor, component) from the Star Citizen Wiki.", + inputSchema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the item (e.g., 'FS-9 LMG', 'Lynx Helmet').", + }, + }, + required: ["name"], + }, + handler: async (args) => { + const { name: itemName } = z.object({ name: z.string() }).parse(args); + const response = await fetchWithCache(scwClient, `/items/${encodeURIComponent(itemName)}`); + return response.data.data; + }, + }, + { + name: "sct_search", + description: "Search Star Citizen Tools (starcitizen.tools) for any topic.", + inputSchema: { + type: "object", + properties: { + query: { + type: "string", + description: "The search query.", + }, + }, + required: ["query"], + }, + handler: async (args) => { + const { query } = z.object({ query: z.string() }).parse(args); + const response = await fetchWithCache(sctClient, "/api.php", { + params: { + action: "opensearch", + search: query, + format: "json", + limit: 10, + }, + }); + return response.data; + }, + }, + { + name: "sct_get_article", + description: "Get the text content of an article from Star Citizen Tools (starcitizen.tools).", + inputSchema: { + type: "object", + properties: { + title: { + type: "string", + description: "The title of the article (e.g., 'Wikelo', 'Carrack').", + }, + }, + required: ["title"], + }, + handler: async (args) => { + const { title } = z.object({ title: z.string() }).parse(args); + const response = await fetchWithCache(sctClient, "/api.php", { + params: { + action: "query", + prop: "extracts", + explaintext: "1", + format: "json", + titles: title, + }, + }); + + if ( + response.data && + isObject(response.data) && + isObject(response.data.query) && + isObject(response.data.query.pages) + ) { + const pages = response.data.query.pages; + const pageId = Object.keys(pages)[0]; + if (pageId !== "-1" && isObject(pages[pageId])) { + const extract = pages[pageId].extract as string | undefined; + // Fall through to the raw payload when the page exists but has no extract. + if (extract) return extract; + } else { + return "Article not found."; + } + } + + return response.data; + }, + }, +]; + +export const toolsByName = new Map(tools.map((t) => [t.name, t])); + +export function getTool(name: string): ToolDefinition | undefined { + return toolsByName.get(name); +} + +/** + * Coerce a flat string map (an HTTP query string) into the shape a tool's + * inputSchema declares. Query params arrive as strings; number and boolean + * properties need converting before the handler's zod schema sees them. + */ +export function coerceArgs( + schema: JsonSchema, + raw: Record, +): Record { + const out: Record = {}; + for (const [key, value] of Object.entries(raw)) { + const prop = schema.properties[key]; + if (!prop) continue; // ignore params the tool doesn't declare + if (value === "") continue; // treat ?x= as absent + if (prop.type === "number" || prop.type === "integer") { + const n = Number(value); + if (Number.isNaN(n)) { + throw new Error(`Parameter '${key}' must be a number, got '${value}'`); + } + out[key] = n; + } else if (prop.type === "boolean") { + out[key] = value !== "false" && value !== "0"; + } else { + out[key] = value; + } + } + return out; +} + +export function describeError(error: unknown): string { + let errorMessage = "Unknown error occurred"; + let details = ""; + + if (error instanceof Error) { + errorMessage = error.message; + } + + if ( + error && + typeof error === "object" && + "response" in error && + error.response && + typeof error.response === "object" && + "data" in error.response + ) { + details = JSON.stringify(error.response.data); + } + + return `Error: ${errorMessage}${details ? `\nDetails: ${details}` : ""}`; +} diff --git a/src/voice.test.ts b/src/voice.test.ts new file mode 100644 index 0000000..5ad87de --- /dev/null +++ b/src/voice.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * The presets are exercised against stubbed tool handlers so the suite never + * touches the UEX API. Field names below mirror the shapes the presets expect; + * the "unfamiliar field names" cases cover what happens when they don't. + */ +const handlers = vi.hoisted(() => ({ + current: new Map Promise>(), +})); + +vi.mock("./tools.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + getTool: (name: string) => { + const handler = handlers.current.get(name); + return handler ? { name, description: "", inputSchema: {}, handler } : undefined; + }, + }; +}); + +const { presets, presetsByName, spokenNumber } = await import("./voice.js"); + +function stub(name: string, data: unknown) { + handlers.current.set(name, async () => data); +} + +function render(preset: string, args: Record = {}) { + const found = presetsByName.get(preset); + if (!found) throw new Error(`no preset ${preset}`); + return found.render(args); +} + +beforeEach(() => { + handlers.current.clear(); +}); + +describe("spokenNumber", () => { + it("adds separators so TTS reads the magnitude correctly", () => { + expect(spokenNumber(32500)).toBe("32,500"); + expect(spokenNumber(1234567.6)).toBe("1,234,568"); + }); +}); + +describe("preset registry", () => { + it("registers every preset under a unique name", () => { + const names = presets.map((p) => p.name); + expect(new Set(names).size).toBe(names.length); + expect(names).toEqual(["sell", "buy", "route", "top"]); + }); +}); + +describe("sell / buy presets", () => { + const rows = [ + { + terminal_name: "Area 18 TDD", + star_system_name: "Stanton", + price_sell: 30000, + price_buy: 28000, + }, + { + terminal_name: "Everus Harbor", + star_system_name: "Stanton", + price_sell: 32500, + price_buy: 31000, + }, + { + terminal_name: "Port Tressler", + star_system_name: "Stanton", + price_sell: 29000, + price_buy: 25000, + }, + ]; + + it("names the highest-paying terminal for a sell", async () => { + stub("uex_get_commodity_prices", rows); + const out = await render("sell", { commodity: "Gold" }); + expect(out).toBe("Gold sells highest at Everus Harbor in Stanton, 32,500 per S C U."); + }); + + it("names the cheapest terminal for a buy", async () => { + stub("uex_get_commodity_prices", rows); + const out = await render("buy", { commodity: "Gold" }); + expect(out).toBe("Gold is cheapest at Port Tressler in Stanton, 25,000 per S C U."); + }); + + it("forwards location filters to the tool", async () => { + const seen: unknown[] = []; + handlers.current.set("uex_get_commodity_prices", async (args) => { + seen.push(args); + return rows; + }); + await render("sell", { commodity: "Gold", system: "Pyro", terminal: "Ruin Station" }); + expect(seen[0]).toMatchObject({ + commodity_name: "Gold", + star_system_name: "Pyro", + terminal_name: "Ruin Station", + }); + }); + + it("ignores rows priced at zero rather than calling them the cheapest", async () => { + stub("uex_get_commodity_prices", [ + { terminal_name: "Nowhere", price_buy: 0 }, + { terminal_name: "Lorville", price_buy: 26000 }, + ]); + expect(await render("buy", { commodity: "Gold" })).toContain("Lorville"); + }); + + it("says so plainly when nothing is priced", async () => { + stub("uex_get_commodity_prices", []); + expect(await render("sell", { commodity: "Gold", system: "Pyro" })).toBe( + "No sell prices found for Gold in Pyro.", + ); + }); + + it("reports a missing commodity instead of querying", async () => { + expect(await render("sell", {})).toBe("No commodity specified."); + }); + + it("omits the system clause when the row does not carry one", async () => { + stub("uex_get_commodity_prices", [{ terminal_name: "Everus Harbor", price_sell: 32500 }]); + expect(await render("sell", { commodity: "Gold" })).toBe( + "Gold sells highest at Everus Harbor, 32,500 per S C U.", + ); + }); +}); + +describe("route preset", () => { + it("reads the most profitable route", async () => { + stub("uex_get_trade_routes", [ + { + commodity_name: "Laranite", + origin_terminal_name: "ArcCorp Mining 141", + destination_terminal_name: "Area 18 TDD", + profit: 120000, + }, + { + commodity_name: "Gold", + origin_terminal_name: "HDMS-Stanhope", + destination_terminal_name: "Everus Harbor", + profit: 450000, + }, + ]); + expect(await render("route", { scu: "96", investment: "1000000" })).toBe( + "Best route: buy Gold at HDMS-Stanhope, sell at Everus Harbor, for 450,000 profit.", + ); + }); + + it("passes SCU and investment through as numbers", async () => { + const seen: unknown[] = []; + handlers.current.set("uex_get_trade_routes", async (args) => { + seen.push(args); + return []; + }); + await render("route", { scu: "96", investment: "1000000" }); + expect(seen[0]).toEqual({ cargo_capacity: 96, investment: 1000000 }); + }); + + it("stays speakable when the route fields are unfamiliar", async () => { + stub("uex_get_trade_routes", [{ some_unexpected_shape: true }]); + const out = await render("route", {}); + expect(out).toContain("could not read the route fields"); + expect(out).not.toContain("undefined"); + }); + + it("reports an empty result", async () => { + stub("uex_get_trade_routes", []); + expect(await render("route", {})).toBe("No trade routes returned."); + }); +}); + +describe("top preset", () => { + const ranking = Array.from({ length: 10 }, (_, i) => ({ commodity_name: `Commodity ${i}` })); + + it("defaults to three commodities", async () => { + stub("uex_get_commodity_ranking", ranking); + expect(await render("top", {})).toBe( + "Top 3 commodities: Commodity 0, Commodity 1, Commodity 2.", + ); + }); + + it("clamps the count to at most five", async () => { + stub("uex_get_commodity_ranking", ranking); + const out = await render("top", { count: "50" }); + expect(out.startsWith("Top 5 commodities:")).toBe(true); + }); + + it("clamps a nonsensical count back to the default", async () => { + stub("uex_get_commodity_ranking", ranking); + expect(await render("top", { count: "-4" })).toContain("Top 3 commodities"); + }); + + it("says so when no names are readable", async () => { + stub("uex_get_commodity_ranking", [{ unexpected: 1 }]); + expect(await render("top", {})).toBe("Ranking returned but no commodity names were readable."); + }); +}); diff --git a/src/voice.ts b/src/voice.ts new file mode 100644 index 0000000..4e62119 --- /dev/null +++ b/src/voice.ts @@ -0,0 +1,207 @@ +import { getTool, isObject } from "./tools.js"; + +/** + * Voice presets render a tool result as one plain-English sentence suitable for + * text-to-speech. JSON is useless to a speech synthesiser, so the voice path + * needs its own formatter rather than just its own transport. + * + * UEX field names vary across endpoints and have changed between API revisions, + * so every field read goes through `pickNumber` / `pickString` with a candidate + * list and each preset degrades to a diagnostic sentence rather than throwing. + */ + +export interface VoicePreset { + name: string; + description: string; + params: { name: string; required: boolean; type: "string" | "number" }[]; + render: (args: Record) => Promise; +} + +function pickNumber(obj: unknown, candidates: string[]): number | undefined { + if (!isObject(obj)) return undefined; + for (const key of candidates) { + const value = obj[key]; + if (typeof value === "number" && Number.isFinite(value)) return value; + if (typeof value === "string" && value.trim() !== "" && !Number.isNaN(Number(value))) { + return Number(value); + } + } + return undefined; +} + +function pickString(obj: unknown, candidates: string[]): string | undefined { + if (!isObject(obj)) return undefined; + for (const key of candidates) { + const value = obj[key]; + if (typeof value === "string" && value.trim() !== "") return value.trim(); + } + return undefined; +} + +/** Numbers read more naturally to SAPI/Windows TTS with thousands separators. */ +export function spokenNumber(n: number): string { + return Math.round(n).toLocaleString("en-US"); +} + +const LOCATION_KEYS = [ + "terminal_name", + "space_station_name", + "outpost_name", + "city_name", + "planet_name", + "orbit_name", + "star_system_name", +]; + +const SELL_PRICE_KEYS = ["price_sell"]; +const BUY_PRICE_KEYS = ["price_buy"]; + +function asArray(data: unknown): Record[] { + return Array.isArray(data) ? (data.filter(isObject) as Record[]) : []; +} + +async function callTool(name: string, args: Record): Promise { + const tool = getTool(name); + if (!tool) throw new Error(`Unknown tool: ${name}`); + return tool.handler(args); +} + +async function bestPrice(args: Record, direction: "sell" | "buy"): Promise { + const commodity = args.commodity; + if (!commodity) return "No commodity specified."; + + const rows = asArray( + await callTool("uex_get_commodity_prices", { + commodity_name: commodity, + star_system_name: args.system, + planet_name: args.planet, + terminal_name: args.terminal, + }), + ); + + const priceKeys = direction === "sell" ? SELL_PRICE_KEYS : BUY_PRICE_KEYS; + const priced = rows + .map((row) => ({ row, price: pickNumber(row, priceKeys) })) + .filter((r): r is { row: Record; price: number } => (r.price ?? 0) > 0); + + if (priced.length === 0) { + const scope = args.system ? ` in ${args.system}` : ""; + return `No ${direction} prices found for ${commodity}${scope}.`; + } + + // Best sell is the highest price; best buy is the lowest. + priced.sort((a, b) => (direction === "sell" ? b.price - a.price : a.price - b.price)); + const best = priced[0]; + const where = pickString(best.row, LOCATION_KEYS) ?? "an unnamed terminal"; + const system = pickString(best.row, ["star_system_name"]); + const verb = direction === "sell" ? "sells highest at" : "is cheapest at"; + + return ( + `${commodity} ${verb} ${where}${system ? ` in ${system}` : ""}, ` + + `${spokenNumber(best.price)} per S C U.` + ); +} + +export const presets: VoicePreset[] = [ + { + name: "sell", + description: "Where a commodity sells for the most.", + params: [ + { name: "commodity", required: true, type: "string" }, + { name: "system", required: false, type: "string" }, + { name: "planet", required: false, type: "string" }, + { name: "terminal", required: false, type: "string" }, + ], + render: (args) => bestPrice(args, "sell"), + }, + { + name: "buy", + description: "Where a commodity is cheapest to buy.", + params: [ + { name: "commodity", required: true, type: "string" }, + { name: "system", required: false, type: "string" }, + { name: "planet", required: false, type: "string" }, + { name: "terminal", required: false, type: "string" }, + ], + render: (args) => bestPrice(args, "buy"), + }, + { + name: "route", + description: "The most profitable trade route for a given hold and budget.", + params: [ + { name: "scu", required: false, type: "number" }, + { name: "investment", required: false, type: "number" }, + ], + render: async (args) => { + const scu = args.scu ? Number(args.scu) : undefined; + const investment = args.investment ? Number(args.investment) : undefined; + + const rows = asArray( + await callTool("uex_get_trade_routes", { + cargo_capacity: scu, + investment, + }), + ); + + if (rows.length === 0) return "No trade routes returned."; + + const scored = rows.map((row) => ({ + row, + profit: pickNumber(row, ["profit", "profit_margin", "price_margin", "margin"]), + })); + scored.sort((a, b) => (b.profit ?? 0) - (a.profit ?? 0)); + const best = scored[0]; + + const commodity = pickString(best.row, ["commodity_name", "commodity"]); + const origin = pickString(best.row, [ + "origin_terminal_name", + "terminal_origin_name", + "origin_name", + "origin", + ]); + const destination = pickString(best.row, [ + "destination_terminal_name", + "terminal_destination_name", + "destination_name", + "destination", + ]); + + if (!commodity || !origin || !destination) { + // Field names drifted; say something useful instead of throwing. + return ( + `Got ${rows.length} routes but could not read the route fields. ` + + `Check slash q slash uex underscore get underscore trade underscore routes.` + ); + } + + const profitText = + best.profit !== undefined ? `, for ${spokenNumber(best.profit)} profit` : ""; + return `Best route: buy ${commodity} at ${origin}, sell at ${destination}${profitText}.`; + }, + }, + { + name: "top", + description: "The top-ranked commodities by profitability.", + params: [{ name: "count", required: false, type: "number" }], + render: async (args) => { + // Anything absent, non-numeric, or non-positive falls back to the default + // rather than clamping to a single result. + const requested = Math.floor(Number(args.count)); + const count = Number.isFinite(requested) && requested > 0 ? Math.min(requested, 5) : 3; + const rows = asArray(await callTool("uex_get_commodity_ranking", {})); + + if (rows.length === 0) return "No commodity ranking returned."; + + const names = rows + .slice(0, count) + .map((row) => pickString(row, ["commodity_name", "name", "commodity"])) + .filter((n): n is string => Boolean(n)); + + if (names.length === 0) return "Ranking returned but no commodity names were readable."; + + return `Top ${names.length} commodities: ${names.join(", ")}.`; + }, + }, +]; + +export const presetsByName = new Map(presets.map((p) => [p.name, p]));