From 0a9be13dd5b8e64fefcc2e42b3f7029436450db4 Mon Sep 17 00:00:00 2001 From: NeziahTech Date: Mon, 23 Nov 2026 22:03:25 +0100 Subject: [PATCH 1/2] Add lens_quote: what one trade of a given size costs (#685) An agent could ask Lens for a price but not for the cost of *its* order. Route, depth and impact answered that in REST across three routes and in MCP not at all, so the agent had to make three HTTP calls and join them itself. lens_quote answers all three legs in one call, at the order size the caller names: it runs the very functions GET /price/:assetA/:assetB/route, GET /price/:assetA/:assetB/depth and GET /impact/:assetA/:assetB run, and tests/mcp-quote-parity.test.ts drives both surfaces against the same stubs and asserts the bodies are equal and the arguments handed to the shared pricing code are identical. The tool module stays pure: pair resolution, argument validation and the envelope live in src/mcp/quoteTool.ts, and every number arrives through the injected LensQuoteQueries (src/mcp/quoteQueries.ts), so nothing behind the tool reaches a database driver. Issuer rules are REST's rules, and a code that matches while its issuer does not is refused as ERR_ASSET_ISSUER_MISMATCH rather than priced against a same-named asset. A leg that cannot price the order is a qualified result, not a failed call: depth carries status "unavailable" with its reason and excludedPools, impact is null, and both appear in `unavailable`. Only a read that throws becomes ERR_SERVICE_UNREACHABLE, worded so it cannot be read as zero liquidity. --- README.md | 3 +- src/mcp/priceTool.ts | 5 +- src/mcp/quoteQueries.ts | 48 ++++ src/mcp/quoteTool.ts | 500 +++++++++++++++++++++++++++++++++ src/mcp/server.ts | 64 +++++ tests/mcp-quote-parity.test.ts | 480 +++++++++++++++++++++++++++++++ tests/mcp-quote-tool.test.ts | 497 ++++++++++++++++++++++++++++++++ 7 files changed, 1595 insertions(+), 2 deletions(-) create mode 100644 src/mcp/quoteQueries.ts create mode 100644 src/mcp/quoteTool.ts create mode 100644 tests/mcp-quote-parity.test.ts create mode 100644 tests/mcp-quote-tool.test.ts diff --git a/README.md b/README.md index ac7ef3e6..a7889b93 100644 --- a/README.md +++ b/README.md @@ -468,11 +468,12 @@ When multiple venues quote the same pair, their prices naturally diverge due to | `paid_call` | Fetches an x402-gated URL and handles the `402 → sign → retry` loop. | **Yes — it signs with a real Stellar key** | | `payment_budget` | Reports the configured limits and what is left of today's budget. | No | | `lens_get_price` | Reads Lens's own aggregated price for a watched pair. | No | +| `lens_quote` | What one order of a size the caller names would cost: the best route, the order-book depth and the price-impact ladder, in one answer. | No | | `lens_list_pairs` | Lists the pairs watched on one network, one bounded page at a time, each with its latest price and the issuer of both assets in full. | No | | `lens_get_pools` | Lists AMM pools with their newest reserves, spot price and fee — how much liquidity stands behind a pair. | No | | `lens_screen_pairs` | Ranks watched pairs by volume, 24h change, price or liquidity, with the same filters as `GET /screener`. | No | -`payment_budget` appears whenever a spend budget is configured, which the example always sets, and `lens_get_price` only where the server can reach Lens's own price data. The three data tools follow the same rule: they are advertised only where the host supplies Lens's data, and each one runs the very function its REST route runs, so a page over MCP is the same rows and cursor as a page over HTTP. Every one of them is served over **either** transport, and the tool list, schemas and error codes are identical whichever you pick. Which transport runs is selected by configuration; **stdio is the default**, so an existing setup needs no changes. +`payment_budget` appears whenever a spend budget is configured, which the example always sets, and `lens_get_price` only where the server can reach Lens's own price data. The three data tools follow the same rule: they are advertised only where the host supplies Lens's data, and each one runs the very function its REST route runs, so a page over MCP is the same rows and cursor as a page over HTTP. `lens_quote` follows it on the pricing side: it is advertised only where the host can read Lens's markets, and its three legs are the very calls `GET /price/:assetA/:assetB/route`, `GET /price/:assetA/:assetB/depth` and `GET /impact/:assetA/:assetB` make, so one quote over MCP is the same route, depth and impact the three HTTP requests return — at the order size the caller names instead of a fixed 1000. A leg that cannot price the order arrives as a qualified part of the answer (`depth.status: "unavailable"` with its reason, or `impact: null`), never as a zero and never as a failed call; only a read that outright fails answers `ERR_SERVICE_UNREACHABLE`, which means retry. Every one of them is served over **either** transport, and the tool list, schemas and error codes are identical whichever you pick. Which transport runs is selected by configuration; **stdio is the default**, so an existing setup needs no changes. **⚠️ Warning:** the mainnet key signs with real XLM. Read the configuration, spending warning, and worked example before running. diff --git a/src/mcp/priceTool.ts b/src/mcp/priceTool.ts index 3f5d3104..6ebc8bac 100644 --- a/src/mcp/priceTool.ts +++ b/src/mcp/priceTool.ts @@ -95,8 +95,11 @@ const VALID_NETWORKS: readonly NetworkName[] = ['testnet', 'mainnet'] * issuer. Codes are matched case-sensitively because that is how Stellar stores * them — "usdc" and "USDC" are different strings on the ledger — so a lowercase * code is refused rather than quietly folded. + * + * Exported because every Lens market tool declares the same asset grammar in its + * input schema; a second copy of the pattern is a second thing to keep in sync. */ -const ASSET_PATTERN = '^(?:native|[A-Z][A-Z0-9]{0,11}(?::G[A-Z2-7]{55})?)$' +export const ASSET_PATTERN = '^(?:native|[A-Z][A-Z0-9]{0,11}(?::G[A-Z2-7]{55})?)$' const ASSET_RE = new RegExp(ASSET_PATTERN) const ISSUER_RE = /^G[A-Z2-7]{55}$/ diff --git a/src/mcp/quoteQueries.ts b/src/mcp/quoteQueries.ts new file mode 100644 index 00000000..f599c56a --- /dev/null +++ b/src/mcp/quoteQueries.ts @@ -0,0 +1,48 @@ +import { getBestRoute } from '../aggregator/bestRoute' +import { getDepth, getImpact } from '../pricing/depth' +import { activeNetwork, getNetworkConfig } from '../config' +import type { NetworkName } from '../config' +import type { LensQuoteQueries } from './quoteTool.js' + +/** + * The data layer behind `lens_quote` (#685), built from the three functions the + * REST routes call: `getBestRoute` serves `GET /price/:a/:b/route`, `getDepth` + * serves `GET /price/:a/:b/depth` and `getImpact` serves `GET /impact/:a/:b`. + * Asking through MCP is therefore a different transport, not a different answer. + * + * It lives here rather than in `quoteTool.ts` so the tool logic stays testable + * with a stub and a stdio server that does not serve Lens's own markets never + * imports `pg` — the same split {@link createLensPriceQueries} makes. + */ +export function createLensQuoteQueries(): LensQuoteQueries { + return { + activeNetwork, + + // The declared pair list for that network — the exact list REST's `findPair` + // searches — with issuers intact. Not the process-wide live registry: a pair + // REST cannot resolve, this tool must not quietly price. + watchedPairs(network: NetworkName) { + return getNetworkConfig(network).pairs + }, + + // Argument order matches the route: the pair's own asset objects, its pair + // key, the caller's order size, then the network. + route(assetA, assetB, pairKey, amount, network) { + return getBestRoute(assetA, assetB, pairKey, amount, network) + }, + + // `getDepth` takes the network first and needs the fee reader's Horizon URL, + // read from the same network's config the route reads it from. + depth(network: NetworkName, pairKey: string, amount: number) { + return getDepth(network, pairKey, amount, { + horizonUrl: getNetworkConfig(network).horizon.url, + }) + }, + + // The thresholds and liquidity fraction come from the tool, which is where + // they are documented — this layer only passes them down. + impact(pairKey, network, thresholds, liquidityFraction) { + return getImpact(pairKey, { thresholds: [...thresholds], liquidityFraction }, network) + }, + } +} diff --git a/src/mcp/quoteTool.ts b/src/mcp/quoteTool.ts new file mode 100644 index 00000000..5c105554 --- /dev/null +++ b/src/mcp/quoteTool.ts @@ -0,0 +1,500 @@ +import { MCP_ERROR_CODES } from './codes.js' +import type { McpErrorCode } from './codes.js' +import type { AssetId, RouteInfo, WatchedPair } from '../types.js' +import type { NetworkName } from '../config.js' +import { ASSET_PATTERN, parseAssetRef, resolveWatchedPair } from './priceTool.js' +import type { AssetRef, PriceToolFailure } from './priceTool.js' + +/** + * #685 — an agent could already ask "what is the price" (`lens_get_price`) and + * "what is the best venue" (the same tool's 1000-unit route), but not "what + * would *my* trade cost". Cost is not one number: it is which venue fills it, + * how deep that venue is, and how far the price moves as it is eaten through. + * REST answers all three (`GET /price/:a/:b/route`, `GET /price/:a/:b/depth`, + * `GET /impact/:a/:b`) and MCP answered none, so an agent had to make three + * HTTP calls and join them itself — or guess. + * + * Like `priceTool.ts`, this module is the pure half: argument shape, pair + * resolution, and the envelope. Every number comes from an injected read + * ({@link LensQuoteQueries}) that is the very function the REST route calls, so + * this module cannot grow its own pricing maths and cannot reach a database. + */ + +export const LENS_QUOTE_TOOL_NAME = 'lens_quote' + +/** + * The impact leg's parameters. They are fixed here rather than exposed as + * arguments because the REST route's own defaults are the contract: `thresholds` + * 1/5/10 percent and half the pool's base reserve as the usable ceiling. An + * agent asking for a different fraction would get an answer no REST caller can + * reproduce, which is the drift this tool exists to avoid. + */ +export const QUOTE_IMPACT_THRESHOLDS: readonly number[] = [1, 5, 10] +export const QUOTE_IMPACT_LIQUIDITY_FRACTION = 0.5 + +/** + * What `getDepth` returns, mirrored locally instead of imported. + * + * `src/pricing/depth.ts` reaches Postgres, so importing its types here would put + * a database behind a tool module that is supposed to be testable with a stub — + * the same reason `priceTool.ts` declares {@link AggregatedPriceFields} rather + * than importing the aggregator's. These shapes are kept field-for-field equal + * to the real ones, and the parity tests compare the tool's legs against the REST + * bodies built from the same functions, so a divergence fails a test rather than + * shipping quietly. + */ +export interface QuoteDepthLevel { + price: number + size: number +} + +export interface QuoteExcludedPool { + poolId: string + reason: string +} + +export interface QuoteDepthPriced { + status: 'ok' + network: string + pairKey: string + spotPrice: number + executionPrice: number + slippagePct: number + asks: QuoteDepthLevel[] + bids: QuoteDepthLevel[] + source: 'AMM' + pool: { + poolId: string + feeBp: number + feeReadAt: string + reservesObservedAt: string + } + excludedPools: QuoteExcludedPool[] +} + +/** A pair the venue cannot price right now: a reason and the exclusions, never zeros. */ +export interface QuoteDepthUnavailable { + status: 'unavailable' + network: string + pairKey: string + reason: string + excludedPools: QuoteExcludedPool[] +} + +export type QuoteDepthOutcome = QuoteDepthPriced | QuoteDepthUnavailable + +export interface QuoteImpactPoint { + size: number + output: number + executionPrice: number + slippagePct: number +} + +export interface QuoteImpactThreshold { + thresholdPct: number + crossed: boolean + size: number | null +} + +export interface QuoteImpact { + status: 'ok' | 'insufficient_liquidity' + spotPrice: number + availableLiquidity: number + smallestSize: number + ladder: QuoteImpactPoint[] + thresholds: QuoteImpactThreshold[] + source: 'AMM' +} + +/** The reads `lens_quote` needs, supplied by the process that hosts the tool. */ +export interface LensQuoteQueries { + /** Network the caller gets when they name none — the deployment's own default. */ + readonly activeNetwork: NetworkName + /** + * Pairs watched on that network, issuers intact: the same list REST's + * `findPair` searches, so a pair REST answers 404 for is refused here too. + */ + watchedPairs(network: NetworkName): readonly WatchedPair[] + /** `GET /price/:assetA/:assetB/route`'s own call, at the caller's order size. */ + route( + assetA: AssetId, + assetB: AssetId, + pairKey: string, + amount: number, + network: NetworkName + ): Promise + /** `GET /price/:assetA/:assetB/depth`'s own call. */ + depth(network: NetworkName, pairKey: string, amount: number): Promise + /** `GET /impact/:assetA/:assetB`'s own call; null when there is no AMM leg to measure. */ + impact( + pairKey: string, + network: NetworkName, + thresholds: readonly number[], + liquidityFraction: number + ): Promise +} + +/** A leg that has an answer to report but no number: stated, not hidden. */ +export interface QuoteUnavailableLeg { + leg: 'depth' | 'impact' + code: McpErrorCode + reason: string +} + +export type LensQuoteResult = { + network: NetworkName + pairKey: string + /** The order size every leg is priced for, in units of `base`. */ + amount: number + /** The pair's base side, issuer intact. `amount` is a quantity of this. */ + base: AssetRef + /** The pair's quote side. Every price in the legs is units of this per one base. */ + quote: AssetRef + /** Whether the pair matched in the order asked, or the other way round. */ + direction: 'as-requested' | 'reversed' + /** Constant, so no leg can be read backwards. */ + orientation: 'quote-per-base' + /** Exactly the `GET /price/:assetA/:assetB/route` body. */ + route: RouteInfo + /** Exactly the `GET /price/:assetA/:assetB/depth` body, on either arm. */ + depth: { assetA: string; assetB: string } & QuoteDepthOutcome + /** Exactly the `GET /impact/:assetA/:assetB` body, or null — see `unavailable`. */ + impact: ({ assetA: string; assetB: string; pairKey: string } & QuoteImpact) | null + /** + * Legs whose answer is "we cannot price that", each with the reason the data + * layer gave. Empty when every leg priced the order. + */ + unavailable: QuoteUnavailableLeg[] + lastUpdated: string +} + +export type QuoteToolOutcome = + | { ok: true; result: LensQuoteResult } + | { ok: false; error: PriceToolFailure } + +const VALID_NETWORKS: readonly NetworkName[] = ['testnet', 'mainnet'] + +/** + * A plain decimal, optionally without the leading zero. Deliberately not + * `parseFloat`: `parseFloat('100abc')` is 100, so a typo'd argument would price + * a different trade than the one the agent meant to ask about. Nor is it + * `Number()` alone, which would accept `''`, `' '` and `'1e5'` — an empty string + * becoming 0 and an exponent nobody asked for. + */ +const AMOUNT_RE = /^(?:\d+(?:\.\d+)?|\.\d+)$/ + +/** + * Validate the order size. Both REST legs already refuse a non-positive or + * unparseable amount with a 400, so this is the same rule in the tool's + * vocabulary — and it runs before any query, so a bad amount costs the database + * nothing. + */ +export function parseQuoteAmount(raw: unknown): { amount: number } | PriceToolFailure { + const invalid = (detail: string): PriceToolFailure => ({ + code: MCP_ERROR_CODES.ERR_BAD_REQUEST, + reason: `amount must be a positive, finite decimal number of units to sell — ${detail}`, + }) + + if (typeof raw === 'number') { + if (!Number.isFinite(raw)) return invalid(`${raw} is not a finite number`) + if (!(raw > 0)) return invalid(`${raw} is not greater than zero`) + return { amount: raw } + } + + if (typeof raw === 'string') { + const trimmed = raw.trim() + if (!AMOUNT_RE.test(trimmed)) { + if (/^[+-]?\d+(?:\.\d+)?[eE][+-]?\d+$/.test(trimmed)) { + return invalid(`"${raw}" is written in scientific notation; write the number out in full`) + } + return invalid(`"${raw}" is not a plain decimal. Trailing text is not ignored: "100abc" is refused, not read as 100.`) + } + const amount = Number(trimmed) + if (!Number.isFinite(amount) || !(amount > 0)) { + return invalid(`"${raw}" does not resolve to a positive, finite amount`) + } + return { amount } + } + + return invalid(`it is ${raw === undefined ? 'missing' : typeof raw}`) +} + +function failure(code: McpErrorCode, reason: string): QuoteToolOutcome { + return { ok: false, error: { code, reason } } +} + +/** + * Run one `lens_quote` request. + * + * A refusal (bad asset, bad amount, bad network, unwatched pair, mismatched + * issuer) returns before anything is read. A leg that reads successfully and + * reports "unavailable" is not a refusal: it stays in the result, because the + * other legs may still price the order and an agent needs the reason, not a + * thrown-away quote. A read that *throws* is a different thing and is left to + * throw — the hosting server turns it into ERR_SERVICE_UNREACHABLE, because + * "the store was unreachable" must never be readable as "there is no liquidity". + */ +export async function readLensQuote( + args: unknown, + queries: LensQuoteQueries +): Promise { + if (typeof args !== 'object' || args === null || Array.isArray(args)) { + return failure(MCP_ERROR_CODES.ERR_BAD_REQUEST, 'lens_quote expects an object of arguments') + } + + const given = args as Record + + // As in the price tool: `additionalProperties: false` is only a promise until + // something enforces it, and an ignored key means the agent got an answer to a + // question it did not ask. + const allowed = ['assetA', 'assetB', 'amount', 'network'] + const unexpected = Object.keys(given).filter(k => !allowed.includes(k)) + if (unexpected.length > 0) { + return failure( + MCP_ERROR_CODES.ERR_BAD_REQUEST, + `Unknown argument(s): ${unexpected.join(', ')}. lens_quote accepts only ${allowed.join(', ')}.` + ) + } + + const parsedA = parseAssetRef(given.assetA, 'assetA') + if ('code' in parsedA) return failure(parsedA.code, parsedA.reason) + const parsedB = parseAssetRef(given.assetB, 'assetB') + if ('code' in parsedB) return failure(parsedB.code, parsedB.reason) + + let network = queries.activeNetwork + if (given.network !== undefined) { + if (typeof given.network !== 'string' || !(VALID_NETWORKS as readonly string[]).includes(given.network)) { + return failure( + MCP_ERROR_CODES.ERR_BAD_REQUEST, + `network must be one of ${VALID_NETWORKS.join(' or ')}, got ${JSON.stringify(given.network)}` + ) + } + network = given.network as NetworkName + } + + // Before pair resolution, matching REST's route leg: a malformed request + // parameter is a refusal whatever the pair. + const parsedAmount = parseQuoteAmount(given.amount) + if ('code' in parsedAmount) return failure(parsedAmount.code, parsedAmount.reason) + const { amount } = parsedAmount + + const resolved = resolveWatchedPair(parsedA.asset, parsedB.asset, network, queries.watchedPairs(network)) + if ('code' in resolved) return failure(resolved.code, resolved.reason) + const { pair, direction } = resolved + + const [route, depth, impact] = await Promise.all([ + queries.route(pair.assetA, pair.assetB, pair.pairKey, amount, network), + queries.depth(network, pair.pairKey, amount), + queries.impact(pair.pairKey, network, QUOTE_IMPACT_THRESHOLDS, QUOTE_IMPACT_LIQUIDITY_FRACTION), + ]) + + // Every leg is rendered from the pair's own order, exactly as the REST routes + // do it: `assetA`/`assetB` are the watched codes, not what the caller typed, + // and `amount` is always a quantity of the base side. + const assetA = pair.assetA.code + const assetB = pair.assetB.code + + const depthBody = { assetA, assetB, ...depth } + const impactBody = impact ? { assetA, assetB, pairKey: pair.pairKey, ...impact } : null + + const unavailable: QuoteUnavailableLeg[] = [] + if (depth.status === 'unavailable') { + unavailable.push({ + leg: 'depth', + code: MCP_ERROR_CODES.ERR_NO_RESULTS, + reason: `Depth is unavailable for ${pair.pairKey} on ${network}: ${depth.reason}`, + }) + } + if (impact === null) { + unavailable.push({ + leg: 'impact', + code: MCP_ERROR_CODES.ERR_NO_RESULTS, + reason: + `No AMM liquidity available for ${assetA}/${assetB} on ${network}: this pair has no AMM pool ` + + `snapshot to measure against, so no impact curve exists. The route and depth legs are unaffected.`, + }) + } else if (impact.status === 'insufficient_liquidity') { + unavailable.push({ + leg: 'impact', + code: MCP_ERROR_CODES.ERR_NO_RESULTS, + reason: + `AMM liquidity for ${pair.pairKey} on ${network} is too thin to build an impact curve ` + + `(status insufficient_liquidity, ladder empty). The numbers in the impact leg are its spot ` + + `price and usable liquidity only; no size was priced.`, + }) + } + + return { + ok: true, + result: { + network, + pairKey: pair.pairKey, + amount, + base: { code: pair.assetA.code, issuer: pair.assetA.issuer ?? null }, + quote: { code: pair.assetB.code, issuer: pair.assetB.issuer ?? null }, + direction, + orientation: 'quote-per-base', + route, + depth: depthBody, + impact: impactBody, + unavailable, + lastUpdated: new Date().toISOString(), + }, + } +} + +function assetRefSchema() { + return { + type: 'object', + properties: { + code: { type: 'string' }, + issuer: { type: ['string', 'null'] }, + }, + required: ['code', 'issuer'], + additionalProperties: false, + } +} + +/** + * The three legs are declared as open objects carrying their discriminant and + * their headline fields. That is deliberate: each one *is* a REST response body, + * whose full contract lives in `openapi.yaml` and is asserted field-for-field by + * the parity tests. Restating those schemas here would give the same contract two + * owners, and the copy that is not generated is the one that rots. + */ +function depthSchema() { + return { + type: 'object', + properties: { + assetA: { type: 'string' }, + assetB: { type: 'string' }, + pairKey: { type: 'string' }, + network: { type: 'string' }, + status: { type: 'string', enum: ['ok', 'unavailable'] }, + reason: { type: 'string' }, + excludedPools: { + type: 'array', + items: { + type: 'object', + properties: { + poolId: { type: 'string' }, + reason: { type: 'string' }, + }, + required: ['poolId', 'reason'], + }, + }, + }, + required: ['assetA', 'assetB', 'pairKey', 'status', 'excludedPools'], + } +} + +function impactSchema() { + return { + anyOf: [ + { + type: 'object', + properties: { + assetA: { type: 'string' }, + assetB: { type: 'string' }, + pairKey: { type: 'string' }, + status: { type: 'string', enum: ['ok', 'insufficient_liquidity'] }, + source: { type: 'string', enum: ['AMM'] }, + }, + required: ['assetA', 'assetB', 'pairKey', 'status', 'source'], + }, + { type: 'null' }, + ], + } +} + +export const lensQuoteToolDefinition = () => ({ + name: LENS_QUOTE_TOOL_NAME, + description: + 'What one specific trade would cost on Lens right now, for an order size the caller names: the ' + + 'best route and its estimated output, the order-book depth around the fill, and the price impact ' + + 'ladder. Equal to the three REST routes GET /price/:assetA/:assetB/route, ' + + 'GET /price/:assetA/:assetB/depth and GET /impact/:assetA/:assetB — the same functions, the same ' + + 'pair, the same numbers, with the route and impact legs at the caller\'s `amount` instead of a ' + + 'fixed 1000. Read-only: it signs nothing, sends nothing and pays nothing, so use it instead of ' + + 'paid_call for any question about Lens\'s own markets. ' + + 'Assets are CODE or CODE:ISSUER (use "native" or "XLM" for lumens) and the pair is matched both ' + + 'ways; give the issuer for a token, because asset codes are not unique on Stellar and a request ' + + 'whose code matches but whose issuer does not is refused as ERR_ASSET_ISSUER_MISMATCH rather than ' + + 'priced against a same-named asset. ' + + '`amount` is REQUIRED, unlike REST where it defaults to 1000, because a cost without a size is not ' + + 'a cost. It is a positive, finite decimal counted in units of `base` — the pair\'s own base side, ' + + 'which `direction` says whether you asked for it in that order or the other. Trailing junk is ' + + 'refused (ERR_BAD_REQUEST), never truncated to a round number. ' + + 'Every price is units of `quote` per one `base` (`orientation` is always "quote-per-base"). ' + + 'Network is "testnet" or "mainnet", defaulting to the network this server runs. ' + + 'A leg that cannot price the order is reported in the result, not as a tool error: `depth.status` ' + + 'is "unavailable" with its `reason` and the `excludedPools` that were left out, `impact` is null ' + + 'when the pair has no AMM pool to measure, and each of those also appears in `unavailable` with a ' + + 'code and the reason in full. That is deliberate — the other legs may still be perfectly good, and ' + + 'a caller that only reads `route` still gets a quote that was honestly qualified. Only a read that ' + + 'fails outright (the database or Horizon being unreachable) answers ERR_SERVICE_UNREACHABLE, which ' + + 'means retry later and is never readable as "no liquidity". The impact leg is always computed at ' + + 'thresholds 1/5/10 percent and half the usable base reserve, the same defaults REST uses.', + inputSchema: { + type: 'object', + properties: { + assetA: { + type: 'string', + description: 'First asset: CODE, CODE:ISSUER, or "native" for lumens. Codes are uppercase.', + pattern: ASSET_PATTERN, + examples: ['XLM', 'USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN'], + }, + assetB: { + type: 'string', + description: 'Second asset, same form as assetA. Order does not matter; the pair is matched both ways.', + pattern: ASSET_PATTERN, + examples: ['USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN'], + }, + amount: { + type: ['number', 'string'], + description: + 'Order size to price, in units of the pair\'s base side. Positive, finite, plain decimal.', + }, + network: { + type: 'string', + enum: [...VALID_NETWORKS], + description: 'Stellar network to quote. Defaults to the network this server is configured for.', + }, + }, + required: ['assetA', 'assetB', 'amount'], + additionalProperties: false, + }, + outputSchema: { + type: 'object', + properties: { + network: { type: 'string', enum: [...VALID_NETWORKS] }, + pairKey: { type: 'string' }, + amount: { type: 'number' }, + base: assetRefSchema(), + quote: assetRefSchema(), + direction: { type: 'string', enum: ['as-requested', 'reversed'] }, + orientation: { type: 'string', enum: ['quote-per-base'] }, + route: { type: 'object' }, + depth: depthSchema(), + impact: impactSchema(), + unavailable: { + type: 'array', + items: { + type: 'object', + properties: { + leg: { type: 'string', enum: ['depth', 'impact'] }, + code: { type: 'string' }, + reason: { type: 'string' }, + }, + required: ['leg', 'code', 'reason'], + }, + }, + lastUpdated: { type: 'string' }, + }, + required: [ + 'network', 'pairKey', 'amount', 'base', 'quote', 'direction', 'orientation', + 'route', 'depth', 'impact', 'unavailable', 'lastUpdated', + ], + additionalProperties: false, + }, +}) diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 3e5051fb..2b9ef951 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -29,6 +29,12 @@ import { PaymentLedger } from './ledger.js'; import { getMetrics, register } from '../metrics.js'; import { checkPaidCallTarget, parsePaidCallAllowlist, type PaidCallAllowRule } from './paidCallAllowlist.js'; import { LENS_PRICE_TOOL_NAME, lensPriceToolDefinition, readLensPrice, type LensPriceQueries } from './priceTool.js'; +import { + LENS_QUOTE_TOOL_NAME, + lensQuoteToolDefinition, + readLensQuote, + type LensQuoteQueries, +} from './quoteTool.js'; import { LENS_GET_POOLS_TOOL_NAME, LENS_LIST_PAIRS_TOOL_NAME, @@ -134,6 +140,13 @@ export interface McpServerConfig { * the tools, so an agent is never offered a listing this server cannot produce. */ dataQueries?: LensDataQueries; + /** + * Lens's own route, depth and impact reads, for `lens_quote` (#685). Hosts + * that can price an order pass {@link createLensQuoteQueries}; leaving it out + * does not advertise the tool, so an agent is never offered a quote this + * server cannot produce. + */ + quoteQueries?: LensQuoteQueries; /** * Outbound fetch policy for `bazaar_search`. Falls back to the operator's * shared `OUTBOUND_ALLOWED_HOSTS` allowlist. `lookup`/`fetchImpl` exist so @@ -290,6 +303,7 @@ export class BazaarMcpServer { private bazaarFetchOptions: SsrfFetchOptions; private priceQueries?: LensPriceQueries; private dataQueries?: LensDataQueries; + private quoteQueries?: LensQuoteQueries; private budget?: SpendBudget; private limits: McpLimits; private resources: LensResourceDescriptor[]; @@ -300,6 +314,7 @@ export class BazaarMcpServer { this.fetchWithPayment = config_.fetchWithPayment; this.priceQueries = config_.priceQueries; this.dataQueries = config_.dataQueries; + this.quoteQueries = config_.quoteQueries; this.budget = config_.budget; this.paymentLedger = config_.paymentLedger ?? new PaymentLedger(); this.limits = { ...config.mcp, ...config_.limits }; @@ -400,6 +415,13 @@ export class BazaarMcpServer { tools.push(...lensDataToolDefinitions()); } + // #685: one question the price tool cannot answer — what a trade of a + // *given size* costs. Advertised only where the host can price an order, + // so an agent is never offered a quote it would have to compute itself. + if (this.quoteQueries) { + tools.push(lensQuoteToolDefinition()); + } + return { tools }; }); @@ -503,6 +525,48 @@ export class BazaarMcpServer { } } + if (request.params.name === LENS_QUOTE_TOOL_NAME) { + if (!this.quoteQueries) { + return this.createErrorResponse( + 'ERR_INTERNAL_FAILURE', + 'lens_quote is not available: this server has no Lens quote source configured.' + ); + } + + try { + const outcome = await readLensQuote(request.params.arguments, this.quoteQueries); + + if (!outcome.ok) { + return this.createErrorResponse(outcome.error.code, outcome.error.reason); + } + + // A quote carries three ladders — depth levels, impact sizes and the + // threshold answers — so it is the largest of the read-only tools. + // Over the output budget it is labelled as truncated rather than + // shipped whole, exactly as the price tool answers #416. + const bounded = boundSerialized(outcome.result, { + maxBytes: this.limits.maxResultBytes, + maxItems: Number.MAX_SAFE_INTEGER, + offset: 0, + notice: `A Lens quote was truncated to fit a ${this.limits.maxResultBytes}-byte tool output limit; the depth and impact ladders are the part that was cut.`, + }); + return bounded.truncated + ? { content: [{ type: 'text', text: bounded.text }] } + : { content: [{ type: 'text', text: bounded.text }], structuredContent: outcome.result }; + } catch (e: any) { + // Every leg reads Postgres and Horizon, so a throw here means the data + // layer was unreachable — which is not the same answer as a pair with + // no liquidity, and must not reach the agent as one. The driver error + // belongs in the log, not in a transcript: it can carry the connection + // string. + console.error(`[mcp-server] ${request.params.name} failed:`, e); + return this.createErrorResponse( + 'ERR_SERVICE_UNREACHABLE', + 'lens_quote could not price this order: the backing store is unreachable. Retry later rather than treating the missing numbers as zero liquidity.' + ); + } + } + if (isLensDataToolName(request.params.name)) { if (!this.dataQueries) { return this.createErrorResponse( diff --git a/tests/mcp-quote-parity.test.ts b/tests/mcp-quote-parity.test.ts new file mode 100644 index 00000000..9d26e78d --- /dev/null +++ b/tests/mcp-quote-parity.test.ts @@ -0,0 +1,480 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import type { AddressInfo } from 'node:net' +import Fastify from 'fastify' +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' +import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js' +import { BazaarMcpServer, type McpHttpServerHandle } from '../src/mcp/server' +import { createLensQuoteQueries } from '../src/mcp/quoteQueries' +import { LENS_QUOTE_TOOL_NAME } from '../src/mcp/quoteTool' +import { registerNetworkSelector } from '../src/middleware/network' + +/** + * #685's done-when is a comparison, not a description: the route, depth and + * impact a `lens_quote` returns have to *equal* what the three REST routes + * return for the same pair, size and network. + * + * So the pricing legs are stubbed at the module the routes call, and both + * surfaces are driven against those same stubs: the real Fastify routes and the + * real MCP tool, fed by `createLensQuoteQueries()`. What is asserted is the body + * each surface answers with and the arguments each one handed to the shared + * function — parity of output and of call, not of fixture. + */ + +const TESTNET_USDC = 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' +const MAINNET_USDC = 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN' +const TESTNET_PAIR = `USDC:${TESTNET_USDC}/XLM` +const TEST_AUTH_TOKEN = 'lens-mcp-quote-test-token-9c3a7e15b4d2' + +/** HTTP handles opened by the transport tests, closed by its `afterEach`. */ +const openHandles: McpHttpServerHandle[] = [] + +// The pair list is settled by `src/config.ts` at import time, so the watched +// pair has to be in the environment before anything reads it. The literals are +// written out here rather than built from the constants below because a +// `vi.hoisted` callback runs before any module-level `const` is initialised. +vi.hoisted(() => { + process.env.STELLAR_NETWORK = 'testnet' + process.env.WATCHED_PAIRS_TESTNET = + 'USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5/XLM' + process.env.REQUIRE_API_KEY = 'false' +}) + +const legs = vi.hoisted(() => ({ + getBestRoute: vi.fn(), + getDepth: vi.fn(), + getImpact: vi.fn(), +})) + +vi.mock('../src/aggregator/bestRoute', () => ({ getBestRoute: legs.getBestRoute })) +vi.mock('../src/pricing/depth', () => ({ getDepth: legs.getDepth, getImpact: legs.getImpact })) +vi.mock('../src/db', () => ({ pgPool: { query: vi.fn() }, prisma: {} })) +vi.mock('../src/redis', () => ({ + redis: { get: vi.fn(), set: vi.fn(), del: vi.fn(), on: vi.fn(), ping: vi.fn() }, + getCachedPrice: vi.fn().mockResolvedValue(null), + setCachedPrice: vi.fn(), +})) + +// Imported after the mocks above, which vitest hoists regardless. +import { registerRESTRoutes } from '../src/api/rest' + +const ROUTE = { + route: 'AMM', + sdexPrice: 0.184, + ammPrice: 0.185, + estimatedOutput: 46.25, + slippagePct: 0.54, + recommendation: 'AMM offers 0.54% better rate', + network: 'testnet', +} + +const DEPTH_OK = { + status: 'ok', + network: 'testnet', + pairKey: TESTNET_PAIR, + spotPrice: 0.185, + executionPrice: 0.1843, + slippagePct: 0.38, + asks: [ + { price: 0.1851, size: 500 }, + { price: 0.1855, size: 1000 }, + ], + bids: [{ price: 0.1849, size: 800 }], + source: 'AMM', + pool: { + poolId: 'pool-a', + feeBp: 30, + feeReadAt: '2026-11-23T10:00:00.000Z', + reservesObservedAt: '2026-11-23T09:59:40.000Z', + }, + excludedPools: [{ poolId: 'pool-b', reason: 'fee could not be read from the venue' }], +} + +const DEPTH_UNAVAILABLE = { + status: 'unavailable', + network: 'testnet', + pairKey: TESTNET_PAIR, + reason: 'no AMM pool snapshots for this pair on this network', + excludedPools: [], +} + +const IMPACT = { + status: 'ok', + spotPrice: 0.185, + availableLiquidity: 25_000, + smallestSize: 100, + ladder: [{ size: 100, output: 18.49, executionPrice: 0.1849, slippagePct: 0.05 }], + thresholds: [{ thresholdPct: 1, crossed: true, size: 11_800 }], + source: 'AMM', +} + +function stubLegs(over: { route?: unknown; depth?: unknown; impact?: unknown } = {}) { + // `??` would do the wrong thing for `impact: null`, which is exactly the case + // one test is about: a pair with no AMM leg to measure. + legs.getBestRoute.mockReset().mockResolvedValue(over.route === undefined ? ROUTE : over.route) + legs.getDepth.mockReset().mockResolvedValue(over.depth === undefined ? DEPTH_OK : over.depth) + legs.getImpact.mockReset().mockResolvedValue(over.impact === undefined ? IMPACT : over.impact) +} + +async function buildRestApp() { + const app = Fastify({ logger: false }) + await app.register(registerNetworkSelector) + await registerRESTRoutes(app) + await app.ready() + return app +} + +function buildToolServer() { + const server = new BazaarMcpServer({ + fetchWithPayment: vi.fn(), + quoteQueries: createLensQuoteQueries(), + }) + let call: ((request: any) => Promise) | null = null + ;(server as any).server.setRequestHandler = (schema: any, fn: any) => { + if (schema === CallToolRequestSchema) call = fn + } + ;(server as any).setupHandlers() + // The raw handler response, exactly as an agent receives it: `isError` plus a + // text block, or structuredContent. Wrapping it in assertions here would hide + // refusals behind the "did not error" check below. + const raw = async (arguments_: unknown) => + (call as any)({ params: { name: LENS_QUOTE_TOOL_NAME, arguments: arguments_ } }) + return { + raw, + quote: async (arguments_: unknown) => { + const response = await raw(arguments_) + expect(response.isError, `lens_quote errored: ${response.content?.[0]?.text}`).toBeFalsy() + return response.structuredContent ?? JSON.parse(response.content[0].text) + }, + } +} + +const restPaths = (assetA: string, assetB: string) => ({ + route: (amount: number, network?: string) => + `/price/${assetA}/${assetB}/route?amount=${amount}${network ? `&network=${network}` : ''}`, + depth: (amount: number, network?: string) => + `/price/${assetA}/${assetB}/depth?amount=${amount}${network ? `&network=${network}` : ''}`, + impact: (network?: string) => `/impact/${assetA}/${assetB}${network ? `?network=${network}` : ''}`, +}) + +describe('lens_quote is the three REST pricing routes in one call', () => { + // The first test in the file compiles both surfaces cold — Fastify's schema + // serializers and the MCP SDK's output validator — so it is given the time a + // slow machine needs rather than being trimmed to fit a 20s default. + it('returns the route, depth and impact bodies the routes return', { timeout: 60_000 }, async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + const paths = restPaths('XLM', `USDC:${TESTNET_USDC}`) + + const restRoute = await app.inject({ method: 'GET', url: paths.route(250) }) + const restDepth = await app.inject({ method: 'GET', url: paths.depth(250) }) + const restImpact = await app.inject({ method: 'GET', url: paths.impact() }) + expect([restRoute.statusCode, restDepth.statusCode, restImpact.statusCode]).toEqual([200, 200, 200]) + + const quote = await server.quote({ assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }) + + // Field for field. `lastUpdated` and the envelope are the tool's own; the + // three legs are the route bodies, untouched. + expect(quote.route).toEqual(restRoute.json()) + expect(quote.depth).toEqual(restDepth.json()) + expect(quote.impact).toEqual(restImpact.json()) + + await app.close() + }) + + it('asks the shared functions for the same pair, size and network REST does', async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + const paths = restPaths('XLM', `USDC:${TESTNET_USDC}`) + + await app.inject({ method: 'GET', url: paths.route(250) }) + await app.inject({ method: 'GET', url: paths.depth(250) }) + await app.inject({ method: 'GET', url: paths.impact() }) + const restCalls = { + route: legs.getBestRoute.mock.calls[0].slice(), + depth: legs.getDepth.mock.calls[0].slice(), + impact: legs.getImpact.mock.calls[0].slice(), + } + + legs.getBestRoute.mockClear() + legs.getDepth.mockClear() + legs.getImpact.mockClear() + await server.quote({ assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }) + + // Not equal output from equal fixtures: the identical arguments. The pair is + // resolved the way REST resolves it — to the watched order, with issuers — + // and the order size reaches all three legs. + expect(legs.getBestRoute.mock.calls[0]).toEqual(restCalls.route) + expect(legs.getDepth.mock.calls[0]).toEqual(restCalls.depth) + expect(legs.getImpact.mock.calls[0]).toEqual(restCalls.impact) + + await app.close() + }) + + it('prices the pair base whichever way round the assets were given', async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + const forward = restPaths(`USDC:${TESTNET_USDC}`, 'XLM') + + const restRoute = await app.inject({ method: 'GET', url: forward.route(250) }) + const restDepth = await app.inject({ method: 'GET', url: forward.depth(250) }) + const restImpact = await app.inject({ method: 'GET', url: forward.impact() }) + + const reversed = await server.quote({ assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }) + expect(reversed.direction).toBe('reversed') + expect(reversed.route).toEqual(restRoute.json()) + expect(reversed.depth).toEqual(restDepth.json()) + expect(reversed.impact).toEqual(restImpact.json()) + + const asAsked = await server.quote({ assetA: `USDC:${TESTNET_USDC}`, assetB: 'XLM', amount: 250 }) + expect(asAsked.direction).toBe('as-requested') + // One pair, one quote: the order the caller typed changes nothing but the + // label, because `amount` is always a quantity of the pair's base side. + expect(asAsked.route).toEqual(reversed.route) + expect(asAsked.depth).toEqual(reversed.depth) + expect(asAsked.impact).toEqual(reversed.impact) + + await app.close() + }) + + it('scopes a named network to that network on every leg', async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + const mainnetPair = `USDC:${MAINNET_USDC}/XLM` + const paths = restPaths('XLM', `USDC:${MAINNET_USDC}`) + + await app.inject({ method: 'GET', url: paths.route(50, 'mainnet') }) + await app.inject({ method: 'GET', url: paths.depth(50, 'mainnet') }) + await app.inject({ method: 'GET', url: paths.impact('mainnet') }) + const restNetworks = legs.getBestRoute.mock.calls[0].at(-1) + expect(restNetworks).toBe('mainnet') + + const quote = await server.quote({ + assetA: 'XLM', + assetB: `USDC:${MAINNET_USDC}`, + amount: 50, + network: 'mainnet', + }) + expect(quote.network).toBe('mainnet') + expect(quote.pairKey).toBe(mainnetPair) + expect(legs.getBestRoute.mock.calls.at(-1)![0]).toEqual({ code: 'USDC', issuer: MAINNET_USDC }) + expect(legs.getBestRoute.mock.calls.at(-1)![4]).toBe('mainnet') + // getDepth is (network, pairKey, amount) — and the pair key it carries is the + // mainnet one, so a testnet pool can never price a mainnet order. + expect(legs.getDepth.mock.calls.at(-1)![0]).toBe('mainnet') + expect(legs.getDepth.mock.calls.at(-1)![1]).toBe(mainnetPair) + // getImpact is (pairKey, options, network). + expect(legs.getImpact.mock.calls.at(-1)![0]).toBe(mainnetPair) + expect(legs.getImpact.mock.calls.at(-1)![2]).toBe('mainnet') + + await app.close() + }) + + it('carries the unavailable depth arm REST answers with a 503, reason and all', async () => { + stubLegs({ depth: DEPTH_UNAVAILABLE }) + const app = await buildRestApp() + const server = buildToolServer() + const paths = restPaths('XLM', `USDC:${TESTNET_USDC}`) + + const restDepth = await app.inject({ method: 'GET', url: paths.depth(250) }) + // REST says 503: watched pair, no price right now, retry. + expect(restDepth.statusCode).toBe(503) + expect(restDepth.json().status).toBe('unavailable') + + const quote = await server.quote({ assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }) + expect(quote.depth).toEqual(restDepth.json()) + // The tool does not answer 503 — it reports the leg and keeps the legs that + // did price the order. + expect(quote.route).toEqual(ROUTE) + expect(quote.unavailable.map((u: { leg: string }) => u.leg)).toEqual(['depth']) + expect(quote.unavailable[0].reason).toContain(DEPTH_UNAVAILABLE.reason) + + await app.close() + }) + + it('reports a missing impact leg the way REST reports it with a 404', async () => { + stubLegs({ impact: null }) + const app = await buildRestApp() + const server = buildToolServer() + + const restImpact = await app.inject({ method: 'GET', url: restPaths('XLM', `USDC:${TESTNET_USDC}`).impact() }) + expect(restImpact.statusCode).toBe(404) + expect(restImpact.json().code).toBe('unknown_pair') + + const quote = await server.quote({ assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }) + expect(quote.impact).toBe(null) + expect(quote.unavailable.map((u: { leg: string }) => u.leg)).toEqual(['impact']) + + await app.close() + }) + + it('refuses a pair REST refuses, with the pair list rather than a guess', async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + + const restRoute = await app.inject({ method: 'GET', url: restPaths('BTC', 'XLM').route(250) }) + expect(restRoute.statusCode).toBe(404) + expect(restRoute.json().code).toBe('unwatched_pair') + + const refused = await server.raw({ assetA: 'BTC', assetB: 'XLM', amount: 250 }) + expect(refused.isError).toBe(true) + const body = JSON.parse(refused.content[0].text) + expect(body.code).toBe('ERR_PAIR_NOT_WATCHED') + // The same facts in the reason: the pair the caller asked for, the network it + // was looked up on, and what is actually watched there. + expect(body.reason).toContain('BTC') + expect(body.reason).toContain(TESTNET_PAIR) + // Nothing was priced for a pair neither surface knows. + expect(legs.getBestRoute).not.toHaveBeenCalled() + expect(legs.getDepth).not.toHaveBeenCalled() + expect(legs.getImpact).not.toHaveBeenCalled() + + await app.close() + }) + + it('refuses a mismatched issuer instead of quoting a same-named asset', async () => { + stubLegs() + const app = await buildRestApp() + const server = buildToolServer() + + // Same code, a different issuer — here Circle's mainnet USDC, whose address is + // copied in full from src/config.ts rather than invented. On Stellar that is a + // different asset, and the price of one is not the price of the other. + const refused = await server.raw({ + assetA: 'XLM', + assetB: `USDC:${MAINNET_USDC}`, + amount: 250, + }) + expect(refused.isError).toBe(true) + const body = JSON.parse(refused.content[0].text) + expect(body.code).toBe('ERR_ASSET_ISSUER_MISMATCH') + // Names the issuer this network actually prices, so the caller can fix the request. + expect(body.reason).toContain(TESTNET_USDC) + expect(legs.getBestRoute).not.toHaveBeenCalled() + + const restRoute = await app.inject({ + method: 'GET', + url: restPaths('XLM', `USDC:${MAINNET_USDC}`).route(250), + }) + // REST refuses the same request with its own 404. The tool refuses it more + // precisely — a code that matches is not a pair that matches — but neither + // one quotes a same-named asset. + expect(restRoute.statusCode).toBe(404) + expect(restRoute.json().code).toBe('unwatched_pair') + + await app.close() + }) +}) + +// ── Both transports ─────────────────────────────────────────────────────────── + +async function connectStdioClient() { + const server = new BazaarMcpServer({ + fetchWithPayment: vi.fn(), + quoteQueries: createLensQuoteQueries(), + }) + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + await (server as any).server.connect(serverTransport) + const client = new Client({ name: 'lens-quote-test', version: '1.0.0' }, { capabilities: {} }) + await client.connect(clientTransport) + return { client, server } +} + +async function connectHttpClient() { + const server = new BazaarMcpServer({ + fetchWithPayment: vi.fn(), + quoteQueries: createLensQuoteQueries(), + }) + const handle = await server.runHttp({ + host: '127.0.0.1', + port: 0, + path: '/mcp', + authToken: TEST_AUTH_TOKEN, + }) + openHandles.push(handle) + const address = handle.server.address() as AddressInfo + const transport = new StreamableHTTPClientTransport( + new URL(`http://127.0.0.1:${address.port}/mcp`), + { requestInit: { headers: { authorization: `Bearer ${TEST_AUTH_TOKEN}` } } } + ) + const client = new Client({ name: 'lens-quote-http-test', version: '1.0.0' }, { capabilities: {} }) + await client.connect(transport) + return client +} + +describe('lens_quote over both transports', () => { + afterEach(async () => { + while (openHandles.length) await openHandles.pop()!.close() + }) + + it('is advertised and answered identically over stdio and Streamable HTTP', async () => { + stubLegs() + const args = { assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 } + + const { client: stdioClient, server: stdioServer } = await connectStdioClient() + const stdioTools = await stdioClient.listTools() + const stdioQuote = await stdioClient.callTool({ name: LENS_QUOTE_TOOL_NAME, arguments: args }) + await stdioClient.close() + await (stdioServer as any).server.close() + + const httpClient = await connectHttpClient() + const httpTools = await httpClient.listTools() + const httpQuote = await httpClient.callTool({ name: LENS_QUOTE_TOOL_NAME, arguments: args }) + await httpClient.close() + + // The same declaration, so the same contract, whichever transport connected. + expect(httpTools).toEqual(stdioTools) + const declared = stdioTools.tools.find(t => t.name === LENS_QUOTE_TOOL_NAME) + expect(declared).toBeDefined() + expect(declared!.outputSchema).toBeDefined() + + expect(stdioQuote.isError).toBeFalsy() + // `lastUpdated` is stamped when each quote is built, so the two calls cannot + // be byte-identical; everything else must be. + const { lastUpdated: stdioAt, ...stdioBody } = stdioQuote.structuredContent as any + const { lastUpdated: httpAt, ...httpBody } = httpQuote.structuredContent as any + expect(httpBody).toEqual(stdioBody) + expect(stdioAt).toMatch(/T.*Z$/) + expect(httpAt).toMatch(/T.*Z$/) + expect(httpBody.route).toEqual(ROUTE) + expect(httpBody.amount).toBe(250) + // A client that only renders text reads the same numbers. + expect(JSON.parse((httpQuote.content as any)[0].text).pairKey).toBe(TESTNET_PAIR) + }) + + it('refuses an unauthenticated HTTP caller before any pricing read runs', async () => { + stubLegs() + const server = new BazaarMcpServer({ + fetchWithPayment: vi.fn(), + quoteQueries: createLensQuoteQueries(), + }) + const handle = await server.runHttp({ + host: '127.0.0.1', + port: 0, + path: '/mcp', + authToken: TEST_AUTH_TOKEN, + }) + openHandles.push(handle) + const address = handle.server.address() as AddressInfo + + const res = await fetch(`http://127.0.0.1:${address.port}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: LENS_QUOTE_TOOL_NAME, arguments: { assetA: 'XLM', assetB: 'USDC', amount: 250 } }, + }), + }) + expect(res.status).toBe(401) + // The token gate ran before the tool, so the data layer was never asked. + expect(legs.getBestRoute).not.toHaveBeenCalled() + }) +}) diff --git a/tests/mcp-quote-tool.test.ts b/tests/mcp-quote-tool.test.ts new file mode 100644 index 00000000..b39ee907 --- /dev/null +++ b/tests/mcp-quote-tool.test.ts @@ -0,0 +1,497 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js' +import { BazaarMcpServer } from '../src/mcp/server' +import { + LENS_QUOTE_TOOL_NAME, + QUOTE_IMPACT_LIQUIDITY_FRACTION, + QUOTE_IMPACT_THRESHOLDS, + parseQuoteAmount, + readLensQuote, + type LensQuoteQueries, + type LensQuoteResult, + type QuoteDepthOutcome, + type QuoteImpact, +} from '../src/mcp/quoteTool' +import type { McpLimits } from '../src/mcp/limits' +import type { NetworkName } from '../src/config' +import type { RouteInfo, WatchedPair } from '../src/types' + +/** + * #685 — `lens_quote` answers "what would this trade cost" for a size the agent + * names, from the three reads REST already serves. These tests drive the pure + * tool half with injected reads only: no database, no Horizon, no network. That + * is the point of the split, and the last block here checks the split is real. + */ + +const TESTNET_USDC = 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5' +const MAINNET_USDC = 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN' +const TESTNET_PAIR_KEY = `USDC:${TESTNET_USDC}/XLM` + +const jsonOf = (result: unknown) => + JSON.parse((result as { content: Array<{ text: string }> }).content[0].text) + +function watchedPair(issuer: string): WatchedPair { + return { + assetA: { code: 'USDC', issuer }, + assetB: { code: 'XLM', issuer: null }, + pairKey: `USDC:${issuer}/XLM`, + } +} + +const routeInfo = (): RouteInfo => ({ + route: 'AMM', + sdexPrice: 0.184, + ammPrice: 0.185, + estimatedOutput: 185, + slippagePct: 0.5, + recommendation: 'AMM offers 0.54% better rate', + network: 'testnet', +}) + +const depthPriced = (): QuoteDepthOutcome => ({ + status: 'ok', + network: 'testnet', + pairKey: TESTNET_PAIR_KEY, + spotPrice: 0.185, + executionPrice: 0.1843, + slippagePct: 0.38, + asks: [ + { price: 0.1851, size: 500 }, + { price: 0.1855, size: 1000 }, + ], + bids: [{ price: 0.1849, size: 800 }], + source: 'AMM', + pool: { + poolId: 'pool-a', + feeBp: 30, + feeReadAt: '2026-11-23T10:00:00.000Z', + reservesObservedAt: '2026-11-23T09:59:40.000Z', + }, + excludedPools: [{ poolId: 'pool-b', reason: 'fee could not be read from the venue' }], +}) + +const depthUnreachable: QuoteDepthOutcome = { + status: 'unavailable', + network: 'testnet', + pairKey: TESTNET_PAIR_KEY, + reason: 'every AMM pool for this pair was excluded', + excludedPools: [{ poolId: 'pool-b', reason: 'pool has no reserves in its latest snapshot' }], +} + +const impactOk = (): QuoteImpact => ({ + status: 'ok', + spotPrice: 0.185, + availableLiquidity: 25_000, + smallestSize: 100, + ladder: [ + { size: 100, output: 18.49, executionPrice: 0.1849, slippagePct: 0.05 }, + { size: 25_000, output: 4512.9, executionPrice: 0.1805, slippagePct: 2.43 }, + ], + thresholds: [ + { thresholdPct: 1, crossed: true, size: 11_800 }, + { thresholdPct: 5, crossed: false, size: null }, + { thresholdPct: 10, crossed: false, size: null }, + ], + source: 'AMM', +}) + +interface HarnessOptions { + pairs?: Partial> + activeNetwork?: NetworkName + route?: RouteInfo | Error + depth?: QuoteDepthOutcome | Error + impact?: QuoteImpact | null | Error +} + +function buildHarness(options: HarnessOptions = {}) { + const pairs: Record = { + testnet: [watchedPair(TESTNET_USDC)], + mainnet: [watchedPair(MAINNET_USDC)], + ...options.pairs, + } + + const settle = (value: T | Error | undefined, fallback: T): Promise => + value instanceof Error ? Promise.reject(value) : Promise.resolve(value ?? fallback) + + const route = vi.fn(() => settle(options.route, routeInfo())) + const depth = vi.fn(() => settle(options.depth, depthPriced())) + // `null` is an answer here (the pair has no AMM leg), so it cannot go through + // `settle`'s nullish fallback. + const impact = vi.fn(() => + options.impact instanceof Error + ? Promise.reject(options.impact) + : Promise.resolve(options.impact === undefined ? impactOk() : options.impact) + ) + + const quoteQueries: LensQuoteQueries = { + activeNetwork: options.activeNetwork ?? 'testnet', + watchedPairs: network => pairs[network] ?? [], + route, + depth, + impact, + } + + return { + quoteQueries, + route, + depth, + impact, + pairs, + call: (arguments_: unknown) => readLensQuote(arguments_, quoteQueries), + } +} + +/** The tool over a real server, so the dispatch and output budget are exercised. */ +function buildServer(quoteQueries: LensQuoteQueries | undefined, limits?: Partial) { + const server = new BazaarMcpServer({ + fetchWithPayment: vi.fn(), + ...(quoteQueries ? { quoteQueries } : {}), + ...(limits ? { limits } : {}), + }) + const handlers: Record = {} + ;(server as any).server.setRequestHandler = (schema: any, fn: any) => { + if (schema === CallToolRequestSchema) handlers.call = fn + if (schema === ListToolsRequestSchema) handlers.list = fn + } + ;(server as any).setupHandlers() + return { + listTools: async () => (await handlers.list()).tools, + callTool: (arguments_: unknown) => + handlers.call({ params: { name: LENS_QUOTE_TOOL_NAME, arguments: arguments_ } }), + } +} + +const ask = { assetA: 'XLM', assetB: `USDC:${TESTNET_USDC}`, amount: 250 } + +beforeEach(() => { + vi.restoreAllMocks() +}) + +// ── The order size ──────────────────────────────────────────────────────────── + +describe('lens_quote amount validation', () => { + it('prices a positive decimal number', async () => { + const outcome = await readLensQuote( + { assetA: 'native', assetB: `USDC:${TESTNET_USDC}`, amount: 250 }, + buildHarness().quoteQueries + ) + expect(outcome.ok).toBe(true) + if (outcome.ok) expect(outcome.result.amount).toBe(250) + }) + + it('accepts a decimal string, including one without a leading zero', () => { + for (const raw of ['250', '250.5', '.5', ' 250 ']) { + const parsed = parseQuoteAmount(raw) + expect('amount' in parsed, `${raw} refused`).toBe(true) + } + }) + + it('refuses trailing junk instead of reading it as the number in front', () => { + // The parseFloat trap this repo has been burned by: parseFloat('100abc') is + // 100, so a typo'd order size would silently price a different trade. + for (const raw of ['100abc', '100 AB', '12.5.5', '1_000', '0x10', 'abc']) { + const parsed = parseQuoteAmount(raw) + expect('code' in parsed, `${raw} was accepted`).toBe(true) + if ('code' in parsed) expect(parsed.code).toBe('ERR_BAD_REQUEST') + } + }) + + it('refuses everything that is not a positive finite number', () => { + for (const raw of [0, -1, -0.5, Number.NaN, Number.POSITIVE_INFINITY, '', ' ', '1e5', '100abc']) { + const parsed = parseQuoteAmount(raw) + expect('code' in parsed, `${JSON.stringify(raw)} was accepted`).toBe(true) + } + expect(parseQuoteAmount(undefined)).toMatchObject({ code: 'ERR_BAD_REQUEST' }) + expect(parseQuoteAmount(true)).toMatchObject({ code: 'ERR_BAD_REQUEST' }) + expect(parseQuoteAmount(null)).toMatchObject({ code: 'ERR_BAD_REQUEST' }) + expect(parseQuoteAmount({ amount: 1 })).toMatchObject({ code: 'ERR_BAD_REQUEST' }) + }) + + it('names scientific notation as the thing it will not read', () => { + const parsed = parseQuoteAmount('1e5') + expect('reason' in parsed).toBe(true) + if ('reason' in parsed) expect(parsed.reason).toMatch(/scientific notation/) + }) + + it('requires amount rather than defaulting it, and refuses before reading', async () => { + const harness = buildHarness() + const response = buildServer(harness.quoteQueries).callTool({ + assetA: 'native', + assetB: `USDC:${TESTNET_USDC}`, + }) + const payload = jsonOf(await response) + expect(payload.isError).toBe(true) + expect(payload.code).toBe('ERR_BAD_REQUEST') + expect(payload.reason).toMatch(/amount/) + expect(harness.route).not.toHaveBeenCalled() + expect(harness.depth).not.toHaveBeenCalled() + expect(harness.impact).not.toHaveBeenCalled() + }) + + it('refuses a bad amount whatever the pair, like REST does', async () => { + const harness = buildHarness() + // BTC/XLM is not watched either, so which refusal comes back proves the + // order: a malformed argument is settled before the pair is looked up. + const outcome = await harness.call({ assetA: 'BTC', assetB: 'XLM', amount: '100abc' }) + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_BAD_REQUEST' } }) + expect(harness.route).not.toHaveBeenCalled() + }) +}) + +// ── The envelope ────────────────────────────────────────────────────────────── + +describe('lens_quote result', () => { + it('names the pair, the size and both assets with their issuers in full', async () => { + const outcome = await buildHarness().call(ask) + expect(outcome.ok).toBe(true) + if (!outcome.ok) return + const result = outcome.result + + expect(result.network).toBe('testnet') + expect(result.pairKey).toBe(TESTNET_PAIR_KEY) + expect(result.amount).toBe(250) + expect(result.orientation).toBe('quote-per-base') + // The watched pair's own order, not the order the caller typed: XLM was asked + // for first, but this pair is USDC-issued-by-Circle over XLM. + expect(result.base).toEqual({ code: 'USDC', issuer: TESTNET_USDC }) + expect(result.quote).toEqual({ code: 'XLM', issuer: null }) + expect(result.direction).toBe('reversed') + // An issuer is part of an asset's identity, so it travels complete. + expect(result.base.issuer).toHaveLength(56) + expect(result.lastUpdated).toMatch(/T.*Z$/) + }) + + it('prices every leg in the pair order at the caller size', async () => { + const harness = buildHarness() + await harness.call(ask) + + const pair = harness.pairs.testnet[0] + // `amount` is a quantity of the pair's base side, so a reversed request still + // prices base→quote — which is why the result carries `direction`. + expect(harness.route).toHaveBeenCalledWith(pair.assetA, pair.assetB, TESTNET_PAIR_KEY, 250, 'testnet') + expect(harness.depth).toHaveBeenCalledWith('testnet', TESTNET_PAIR_KEY, 250) + expect(harness.impact).toHaveBeenCalledWith( + TESTNET_PAIR_KEY, + 'testnet', + QUOTE_IMPACT_THRESHOLDS, + QUOTE_IMPACT_LIQUIDITY_FRACTION + ) + }) + + it('renders the legs as the REST bodies: codes, pair key, then the read', async () => { + const outcome = await buildHarness().call(ask) + if (!outcome.ok) throw new Error('quote was refused') + const result = outcome.result as LensQuoteResult + + expect(result.route).toEqual(routeInfo()) + expect(result.depth).toEqual({ assetA: 'USDC', assetB: 'XLM', ...depthPriced() }) + expect(result.impact).toEqual({ + assetA: 'USDC', + assetB: 'XLM', + pairKey: TESTNET_PAIR_KEY, + ...impactOk(), + }) + expect(result.unavailable).toEqual([]) + }) + + it('defaults to the server network and quotes another when named', async () => { + const harness = buildHarness() + const outcome = await harness.call({ + assetA: 'native', + assetB: `USDC:${MAINNET_USDC}`, + amount: 10, + network: 'mainnet', + }) + expect(outcome.ok).toBe(true) + if (!outcome.ok) return + expect(outcome.result.network).toBe('mainnet') + expect(outcome.result.pairKey).toBe(`USDC:${MAINNET_USDC}/XLM`) + expect(harness.depth).toHaveBeenCalledWith('mainnet', `USDC:${MAINNET_USDC}/XLM`, 10) + }) +}) + +// ── Refusals ────────────────────────────────────────────────────────────────── + +describe('lens_quote refusals', () => { + it('refuses a same-named asset with a different issuer instead of pricing it', async () => { + const harness = buildHarness() + const outcome = await harness.call({ assetA: 'native', assetB: `USDC:${MAINNET_USDC}`, amount: 100 }) + + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_ASSET_ISSUER_MISMATCH' } }) + expect(harness.route).not.toHaveBeenCalled() + }) + + it('refuses an unwatched pair and lists what is watched', async () => { + const harness = buildHarness() + const outcome = await harness.call({ assetA: 'BTC', assetB: 'XLM', amount: 100 }) + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_PAIR_NOT_WATCHED' } }) + if (!outcome.ok) expect(outcome.error.reason).toContain(TESTNET_PAIR_KEY) + }) + + it('refuses a malformed asset with ERR_INVALID_ASSET', async () => { + const harness = buildHarness() + for (const bad of ['usdc', 'USDC:GA5', 'TOO_LONG_CODE:X']) { + const outcome = await harness.call({ assetA: bad, assetB: 'XLM', amount: 1 }) + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_INVALID_ASSET' } }) + } + }) + + it('refuses an unknown network with the vocabulary the other tools use', async () => { + const harness = buildHarness() + const outcome = await harness.call({ ...ask, network: 'devnet' }) + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_BAD_REQUEST' } }) + expect(harness.route).not.toHaveBeenCalled() + }) + + it('refuses an argument it does not take rather than ignoring it', async () => { + const harness = buildHarness() + const outcome = await harness.call({ ...ask, thresholds: '1,5,10' }) + expect(outcome).toMatchObject({ ok: false, error: { code: 'ERR_BAD_REQUEST' } }) + if (!outcome.ok) expect(outcome.error.reason).toMatch(/thresholds/) + expect(harness.impact).not.toHaveBeenCalled() + }) +}) + +// ── A leg that cannot price the order ───────────────────────────────────────── + +describe('lens_quote carries an unavailable leg through honestly', () => { + it('keeps the depth refusal as a result and says why', async () => { + const harness = buildHarness({ depth: depthUnreachable }) + const outcome = await harness.call(ask) + + expect(outcome.ok).toBe(true) + if (!outcome.ok) return + expect(outcome.result.depth).toEqual({ assetA: 'USDC', assetB: 'XLM', ...depthUnreachable }) + expect(outcome.result.depth.status).toBe('unavailable') + // The reason and the excluded pools reach the agent; no zero is invented. + if (outcome.result.depth.status !== 'unavailable') throw new Error('depth arm changed') + expect(outcome.result.depth.reason).toBe('every AMM pool for this pair was excluded') + expect(outcome.result.depth.excludedPools).toHaveLength(1) + // And it is visible at the top level too, not only inside the leg. + expect(outcome.result.unavailable).toHaveLength(1) + expect(outcome.result.unavailable[0].leg).toBe('depth') + expect(outcome.result.unavailable[0].code).toBe('ERR_NO_RESULTS') + expect(outcome.result.unavailable[0].reason).toContain('every AMM pool for this pair was excluded') + // The legs that did price are unaffected. + expect(outcome.result.route).toEqual(routeInfo()) + }) + + it('reports a missing impact leg with the reason REST gives', async () => { + const harness = buildHarness({ impact: null }) + const outcome = await harness.call(ask) + + expect(outcome.ok).toBe(true) + if (!outcome.ok) return + expect(outcome.result.impact).toBe(null) + expect(outcome.result.unavailable).toHaveLength(1) + expect(outcome.result.unavailable[0]).toMatchObject({ leg: 'impact', code: 'ERR_NO_RESULTS' }) + expect(outcome.result.unavailable[0].reason).toMatch(/No AMM liquidity available for USDC\/XLM/) + }) + + it('flags an empty impact curve as unavailable without hiding its numbers', async () => { + const thin: QuoteImpact = { + status: 'insufficient_liquidity', + spotPrice: 0.185, + availableLiquidity: 40, + smallestSize: 100, + ladder: [], + thresholds: [{ thresholdPct: 1, crossed: false, size: null }], + source: 'AMM', + } + const outcome = await buildHarness({ impact: thin }).call(ask) + expect(outcome.ok).toBe(true) + if (!outcome.ok) return + expect(outcome.result.impact).toMatchObject({ status: 'insufficient_liquidity', ladder: [] }) + expect(outcome.result.unavailable).toHaveLength(1) + expect(outcome.result.unavailable[0].leg).toBe('impact') + expect(outcome.result.unavailable[0].reason).toMatch(/insufficient_liquidity/) + }) + + it('turns a failing read into ERR_SERVICE_UNREACHABLE, never into an empty quote', async () => { + const harness = buildHarness({ route: new Error('connection refused postgres://user:secret@host') }) + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const server = buildServer(harness.quoteQueries) + + const response = await server.callTool(ask) + expect(response.isError).toBe(true) + const payload = jsonOf(response) + expect(payload.code).toBe('ERR_SERVICE_UNREACHABLE') + // "unreachable" and "no liquidity" are different answers, and the reply says + // which one it is. + expect(payload.reason).toMatch(/retry later/i) + // A driver error can carry the connection string; a transcript must not. + expect(response.content[0].text).not.toMatch(/secret/) + expect(spy).toHaveBeenCalled() + }) +}) + +// ── Advertising, budget and boundaries ──────────────────────────────────────── + +describe('lens_quote on the server', () => { + it('is advertised only when its reads are supplied', async () => { + const withQuotes = buildServer(buildHarness().quoteQueries) + expect((await withQuotes.listTools()).map((t: { name: string }) => t.name)).toContain( + LENS_QUOTE_TOOL_NAME + ) + + const without = buildServer(undefined) + expect((await without.listTools()).map((t: { name: string }) => t.name)).not.toContain( + LENS_QUOTE_TOOL_NAME + ) + + // Called anyway, it refuses with the reason instead of an empty quote. + const response = await without.callTool(ask) + expect(response.isError).toBe(true) + expect(jsonOf(response).code).toBe('ERR_INTERNAL_FAILURE') + }) + + it('labels a quote over the output budget rather than dumping it into context', async () => { + // A depth ladder of 40 levels is comfortably past a 400-byte budget, and the + // point of #416 is that the agent is told rather than flooded. + const wide: QuoteDepthOutcome = { + ...(depthPriced() as Extract), + asks: Array.from({ length: 40 }, (_, i) => ({ price: 0.185 + i / 10_000, size: 1000 + i })), + } + const harness = buildHarness({ depth: wide }) + const server = buildServer(harness.quoteQueries, { maxResultBytes: 400 }) + + const response = await server.callTool(ask) + expect(response.structuredContent).toBeUndefined() + const body = jsonOf(response) + expect(body.truncated).toBe(true) + expect(body.notice).toMatch(/depth and impact ladders/) + }) + + it('declares the tool the way an agent needs: parity, size, and refusal vocabulary', async () => { + const server = buildServer(buildHarness().quoteQueries) + const tool = (await server.listTools()).find((t: { name: string }) => t.name === LENS_QUOTE_TOOL_NAME) + + expect(tool.inputSchema.required).toEqual(['assetA', 'assetB', 'amount']) + expect(tool.inputSchema.additionalProperties).toBe(false) + expect(tool.outputSchema).toBeDefined() + for (const route of ['/route', '/depth', '/impact']) { + expect(tool.description).toContain(route) + } + // The decisions an agent cannot infer from the payload. + expect(tool.description).toMatch(/ERR_ASSET_ISSUER_MISMATCH/) + expect(tool.description).toMatch(/units of/) + expect(tool.description).toMatch(/read-only/i) + }) + + it('keeps the tool module free of the data layer', () => { + // #685's rule, checked on the file rather than trusted: the tool's logic is + // testable with a stub only if it cannot reach a database by itself. + const source = readFileSync( + fileURLToPath(new URL('../src/mcp/quoteTool.ts', import.meta.url)), + 'utf8' + ) + const imports = [...source.matchAll(/from\s+'([^']+)'/g)].map(match => match[1]) + const forbidden = ['db', 'prisma', '/pg', 'pricing/depth', 'aggregator', 'stellar-sdk', 'routes/'] + const offenders = imports.filter(spec => forbidden.some(word => spec.includes(word))) + expect(offenders, `quoteTool.ts imports ${offenders.join(', ')}`).toEqual([]) + expect(imports).toContain('./codes.js') + expect(imports).toContain('./priceTool.js') + }) +}) From 5f7d6c79637cba852aaf2d2fbf1d8eaf7d5667cd Mon Sep 17 00:00:00 2001 From: NeziahTech Date: Mon, 23 Nov 2026 23:19:20 +0100 Subject: [PATCH 2/2] List lens_quote with the other MCP tools in the resources doc --- docs/mcp-resources.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/mcp-resources.md b/docs/mcp-resources.md index ba0a9c89..1bf5f840 100644 --- a/docs/mcp-resources.md +++ b/docs/mcp-resources.md @@ -4,7 +4,10 @@ The Lens MCP server (`src/mcp/server.ts`) offers an agent two kinds of thing: - **Tools** — functions it calls to *do* something: `bazaar_search`, `paid_call`, `lens_get_price`, and where Lens's own data is reachable the - three data tools `lens_list_pairs`, `lens_get_pools` and `lens_screen_pairs`. + data tools `lens_list_pairs`, `lens_get_pools`, `lens_screen_pairs` and + `lens_quote` — one order size in, and the route, the depth ladder and the + price-impact ladder out, which is what an agent needs to ask "what would + *my* trade cost" in a single call. - **Resources** — read-only content it attaches to its context once, instead of re-fetching by calling a tool every turn.