diff --git a/app/src/app/agents/page.tsx b/app/src/app/agents/page.tsx index 1bfbcffe..94a67e96 100644 --- a/app/src/app/agents/page.tsx +++ b/app/src/app/agents/page.tsx @@ -16,6 +16,7 @@ export const metadata: Metadata = pageMetadata({ path: "/agents", title: "Agents const sections = [ { id: "launch", icon: Rocket, label: "Launch a token" }, { id: "read", icon: BookOpen, label: "Read the API" }, + { id: "mcp", icon: Braces, label: "MCP for agents" }, { id: "trade", icon: ArrowLeftRight, label: "Trade & collect" }, ] as const; @@ -107,6 +108,17 @@ export default function AgentsPage() { +
+

MCP for agents

Tool calls over one POST. Read-only.

+

The site serves a stateless Model Context Protocol (MCP) endpoint at {SITE_URL}/api/mcp. An MCP client can list launches, read one launch, search, fetch trades and holders, read posts and pairs, see the points board, and read protocol totals. No key, no signup, no session, and no tool writes: the tools call the same read model as the JSON API.

+ + +
+

Ten read-only tools: list_launches, get_launch, search_launches, get_token_trades, get_token_holders, get_recent_activity, list_posts, list_community_pairs, get_points_leaderboard, get_protocol_totals. initialize, ping and tools/list implement the protocol. Amounts and USD caveats are the same as the JSON API.

+

Limits: 120 requests per IP per minute, 64 KB per request, and browser origins are checked. Full reference: docs/mcp.md.

+
+
+

Trade & collect

Standard pools. Direct contract calls.

diff --git a/app/src/app/api/mcp/route.test.ts b/app/src/app/api/mcp/route.test.ts new file mode 100644 index 00000000..ebb96d4a --- /dev/null +++ b/app/src/app/api/mcp/route.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import test, { beforeEach } from "node:test"; +import { resetRateLimitsForTests } from "@/lib/rateLimit"; +import { GET, OPTIONS, POST } from "./route.ts"; + +const URL_ = "http://localhost/api/mcp"; + +function post(body: unknown, headers: Record = {}, ip = "mcp-test"): Request { + return new Request(URL_, { + method: "POST", + headers: { "content-type": "application/json", "x-forwarded-for": ip, ...headers }, + body: JSON.stringify(body), + }); +} + +const initialize = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test", version: "1" } } }; + +beforeEach(() => resetRateLimitsForTests()); + +test("POST initialize returns the negotiated protocol and no-store headers", async () => { + const res = await POST(post(initialize)); + assert.equal(res.status, 200); + assert.equal(res.headers.get("cache-control"), "no-store"); + assert.match(res.headers.get("content-type") ?? "", /application\/json/); + const body = (await res.json()) as { result: { protocolVersion: string; capabilities: unknown; serverInfo: { name: string } } }; + assert.equal(body.result.protocolVersion, "2025-06-18"); + assert.equal(body.result.serverInfo.name, "openlaunch"); +}); + +test("POST tools/list advertises read-only tools without their implementation", async () => { + const res = await POST(post({ jsonrpc: "2.0", id: "list", method: "tools/list" })); + assert.equal(res.status, 200); + const body = (await res.json()) as { result: { tools: Array> } }; + assert.ok(body.result.tools.length >= 8); + assert.ok(body.result.tools.every((tool) => tool.annotations && (tool.annotations as { readOnlyHint: boolean }).readOnlyHint === true)); + assert.ok(body.result.tools.every((tool) => !("run" in tool))); +}); + +test("notifications get 202 with no body", async () => { + const res = await POST(post({ jsonrpc: "2.0", method: "notifications/initialized" })); + assert.equal(res.status, 202); + assert.equal(await res.text(), ""); +}); + +test("a browser origin is checked; non-browser clients and the site origin are allowed", async () => { + const evil = await POST(post(initialize, { origin: "https://evil.example" })); + assert.equal(evil.status, 403); + const body = (await evil.json()) as { error: { code: number } }; + assert.equal(body.error.code, -32600); + + const site = await POST(post(initialize, { origin: "https://openlaunch.lol" })); + assert.equal(site.status, 200); + const www = await POST(post(initialize, { origin: "https://www.openlaunch.lol" })); + assert.equal(www.status, 200); +}); + +test("content type, parse errors and unknown methods are handled cleanly", async () => { + const wrongType = await POST(post(initialize, { "content-type": "text/plain" })); + assert.equal(wrongType.status, 415); + + const malformed = await POST(new Request(URL_, { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "mcp-test" }, body: "{" })); + assert.equal(malformed.status, 400); + assert.equal(((await malformed.json()) as { error: { code: number } }).error.code, -32700); + + const unknown = await POST(post({ jsonrpc: "2.0", id: 9, method: "resources/list" })); + assert.equal(unknown.status, 200); + assert.equal(((await unknown.json()) as { error: { code: number } }).error.code, -32601); +}); + +test("the protocol header is validated and batches follow the declared version", async () => { + const ping = { jsonrpc: "2.0", id: 10, method: "ping" }; + const note = { jsonrpc: "2.0", method: "notifications/initialized" }; + + const unsupported = await POST(post(ping, { "mcp-protocol-version": "1999-01-01" })); + assert.equal(unsupported.status, 400); + assert.equal(((await unsupported.json()) as { error: { code: number } }).error.code, -32600); + + const supported = await POST(post(ping, { "mcp-protocol-version": "2025-03-26" })); + assert.equal(supported.status, 200); + assert.deepEqual((await supported.json()) as unknown, { jsonrpc: "2.0", id: 10, result: {} }); + + // 2024-11-05's remote transport needs a GET/SSE handshake this POST-only endpoint does not serve. + const legacy = await POST(post(ping, { "mcp-protocol-version": "2024-11-05" })); + assert.equal(legacy.status, 400); + + // 2025-06-18 removed JSON-RPC batching. + const modern = await POST(post([ping], { "mcp-protocol-version": "2025-06-18" })); + assert.equal(modern.status, 400); + assert.equal(((await modern.json()) as { error: { code: number } }).error.code, -32600); + + // Older versions batch; notifications in the batch are not answered. + const older = await POST(post([ping, note, { jsonrpc: "2.0", id: 11, method: "tools/list" }], { "mcp-protocol-version": "2025-03-26" })); + assert.equal(older.status, 200); + const olderBody = (await older.json()) as Array<{ id?: number }>; + assert.equal(olderBody.length, 2); + assert.equal(olderBody[0].id, 10); + assert.equal(olderBody[1].id, 11); + + // No header means the 2025-03-26 compatibility fallback, so a batch is accepted. + const fallback = await POST(post([ping])); + assert.equal(fallback.status, 200); + assert.equal(((await fallback.json()) as unknown[]).length, 1); + + const onlyNotifications = await POST(post([note, note], { "mcp-protocol-version": "2025-03-26" })); + assert.equal(onlyNotifications.status, 202); + assert.equal(await onlyNotifications.text(), ""); + + const empty = await POST(post([], { "mcp-protocol-version": "2025-03-26" })); + assert.equal(empty.status, 400); + assert.equal(((await empty.json()) as { error: { code: number } }).error.code, -32600); + + const tooMany = await POST(post(Array.from({ length: 21 }, (_, i) => ({ ...ping, id: i })), { "mcp-protocol-version": "2025-03-26" })); + assert.equal(tooMany.status, 400); + assert.equal(((await tooMany.json()) as { error: { code: number } }).error.code, -32600); +}); + +test("a tool call returns text content; an invalid tool call stays a tool error", async () => { + const res = await POST(post({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "get_points_leaderboard", arguments: {} } })); + assert.equal(res.status, 200); + const body = (await res.json()) as { result: { content: Array<{ type: string; text: string }>; isError: boolean } }; + // No DATABASE_URL in tests: no public season is the empty shape, not an error. + assert.equal(body.result.isError, false); + assert.equal(body.result.content[0].type, "text"); + const parsed = JSON.parse(body.result.content[0].text) as { season: null; board: string; rows: unknown[] }; + assert.equal(parsed.season, null); + assert.equal(parsed.board, "creator"); + assert.deepEqual(parsed.rows, []); + + const invalid = await POST(post({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "get_launch", arguments: { chain: "base" } } })); + assert.equal(invalid.status, 200); + const invalidBody = (await invalid.json()) as { result: { isError: boolean; content: Array<{ text: string }> } }; + assert.equal(invalidBody.result.isError, true); + assert.match(invalidBody.result.content[0].text, /token/); +}); + +test("the IP rate limit is 120 requests a minute", async () => { + for (let i = 0; i < 120; i += 1) { + const ok = await POST(post({ jsonrpc: "2.0", id: i, method: "ping" }, {}, "rate-ip")); + assert.equal(ok.status, 200); + } + const limited = await POST(post({ jsonrpc: "2.0", id: 121, method: "ping" }, {}, "rate-ip")); + assert.equal(limited.status, 429); + assert.equal(limited.headers.get("retry-after"), "60"); +}); + +test("GET and OPTIONS do not pretend to be an MCP stream", async () => { + const get = GET(); + assert.equal(get.status, 405); + assert.equal(get.headers.get("allow"), "POST"); + assert.equal(OPTIONS().status, 204); +}); diff --git a/app/src/app/api/mcp/route.ts b/app/src/app/api/mcp/route.ts new file mode 100644 index 00000000..c9d2673b --- /dev/null +++ b/app/src/app/api/mcp/route.ts @@ -0,0 +1,132 @@ +import { NextResponse } from "next/server"; +import { SITE_URL } from "@/lib/chainPublic"; +import { clientIp, readJsonValue } from "@/lib/http"; +import { rateLimited } from "@/lib/rateLimit"; +import { APP_VERSION } from "@/lib/version"; +import { originAllowed } from "@/lib/mcp/origin"; +import { + failure, + isSupportedProtocolVersion, + MCP_LATEST_PROTOCOL_VERSION, + RPC_ERRORS, + type JsonRpcResponse, +} from "@/lib/mcp/protocol"; +import { createMcpServer } from "@/lib/mcp/server"; +import { createMcpTools } from "@/lib/mcp/tools"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** One JSON-RPC message or one batch; older MCP versions allowed batches. */ +const MAX_BODY = 65_536; +/** Requests per IP per minute. A tool call is several indexed reads, not a scrape. */ +const RATE_LIMIT = 120; +const RATE_WINDOW_MS = 60_000; +/** A batch is one HTTP request; cap it so it cannot amplify the rate limit. */ +const MAX_BATCH = 20; + +const HEADERS = { + "cache-control": "no-store", + // MCP clients POST JSON-RPC; a browser fetch from this site is the only + // cross-origin case we allow (originAllowed), and no CORS headers are served. + "content-type": "application/json; charset=utf-8", + "x-content-type-options": "nosniff", +} as const; + +const server = createMcpServer({ + tools: createMcpTools(), + serverInfo: { name: "openlaunch", version: APP_VERSION ?? "0.0.0" }, + instructions: + "Read-only tools for openlaunch.lol, a free token launchpad on Base, Robinhood Chain, Arc and Elysium. " + + "Every token is a fixed-supply ERC-20 launched through the open-source factory; there is no platform fee and no owner. " + + "Use list_launches or search_launches to find a token, then get_launch, get_token_holders and get_token_trades for its facts. " + + "In launch rows, supply, volume_quote, fees_quote_collected, fees_quote_burned, fees_token_collected and " + + "fees_token_burned are raw base-unit strings: scale supply and token-side fees by the launched token's 18 decimals, " + + "and quote-side amounts by the launch's quote_decimals. USD figures such as volume_usd and price_usd are already " + + "in display units. Swap amounts from get_token_trades are raw base-unit strings; derive a price only when the " + + "launch's quote_decimals_known is true. " + + "No tool can sign, trade, launch or write. Indexing lags the chain by a few blocks; a very new launch may not be indexed yet.", + onToolError: (tool, error) => { + const message = error instanceof Error ? error.message : String(error); + console.warn(`[mcp] ${tool} failed: ${message}`); + }, +}); + +function json(body: unknown, status = 200): NextResponse { + return NextResponse.json(body, { status, headers: HEADERS }); +} + +function rpcError(status: number, code: number, message: string): NextResponse { + const body: JsonRpcResponse = failure(null, code, message); + return json(body, status); +} + +/** POST /api/mcp — one stateless MCP JSON-RPC exchange. */ +export async function POST(req: Request): Promise { + const origin = req.headers.get("origin"); + if (!originAllowed(origin, SITE_URL, { dev: process.env.NODE_ENV !== "production" })) { + return rpcError(403, RPC_ERRORS.invalidRequest, "origin not allowed"); + } + + const contentType = (req.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase(); + if (contentType !== "application/json") { + return rpcError(415, RPC_ERRORS.invalidRequest, "content-type must be application/json"); + } + + const declared = Number(req.headers.get("content-length") ?? ""); + if (Number.isFinite(declared) && declared > MAX_BODY) { + return rpcError(413, RPC_ERRORS.invalidRequest, "request body too large"); + } + + // The 2025-06-18 transport requires 400 for an unknown version header. No + // header means the client predates the header; assume 2025-03-26, as the + // spec's backwards-compatibility rule says. + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !isSupportedProtocolVersion(protocolVersion)) { + return rpcError(400, RPC_ERRORS.invalidRequest, "unsupported MCP-Protocol-Version"); + } + + const ip = clientIp(req); + if (rateLimited(`mcp:ip:${ip}`, RATE_LIMIT, RATE_WINDOW_MS)) { + return NextResponse.json( + failure(null, RPC_ERRORS.invalidRequest, "too many requests; retry in a minute"), + { status: 429, headers: { ...HEADERS, "retry-after": "60" } }, + ); + } + + const value = await readJsonValue(req, MAX_BODY); + if (value === undefined) return rpcError(400, RPC_ERRORS.parse, "parse error"); + + if (Array.isArray(value)) { + // A 2025-06-18 client must not batch; an absent header falls back to + // 2025-03-26, whose clients may. + if (protocolVersion === MCP_LATEST_PROTOCOL_VERSION) { + return rpcError(400, RPC_ERRORS.invalidRequest, "JSON-RPC batches are not supported by 2025-06-18"); + } + if (value.length === 0) return rpcError(400, RPC_ERRORS.invalidRequest, "empty JSON-RPC batch"); + if (value.length > MAX_BATCH) { + return rpcError(400, RPC_ERRORS.invalidRequest, `JSON-RPC batch is limited to ${MAX_BATCH} messages`); + } + const responses = await server.handleBatch(value); + // A batch of only notifications gets 202 and no body. + if (responses.length === 0) return new Response(null, { status: 202, headers: HEADERS }); + return json(responses); + } + + const response = await server.handle(value); + // A JSON-RPC notification gets 202 and no body, as the transport requires. + if (response === null) return new Response(null, { status: 202, headers: HEADERS }); + return json(response); +} + +/** No server-initiated SSE stream: this server is stateless and request/response only. */ +export function GET(): Response { + return new Response(JSON.stringify({ error: "POST a JSON-RPC message to this endpoint" }), { + status: 405, + headers: { ...HEADERS, allow: "POST" }, + }); +} + +export function OPTIONS(): Response { + return new Response(null, { status: 204, headers: { allow: "POST" } }); +} diff --git a/app/src/app/llms.txt/route.ts b/app/src/app/llms.txt/route.ts index efbc6545..a00ff0ac 100644 --- a/app/src/app/llms.txt/route.ts +++ b/app/src/app/llms.txt/route.ts @@ -116,6 +116,13 @@ checked hourly and suspended when its checks fail. - GET ${SITE_URL}/api/pairs (every pair: address, symbol, decimals, status, usd, price source) Pages: /pairs, /pair//
(chain: ${PAIR_CHAINS.join(" or ")}). Launch with one against the factory exactly as with any ERC-20 quote (findSalt with the pair's address). ${pairApplySection()} +## MCP (agents, read-only) +A stateless Model Context Protocol server is at ${SITE_URL}/api/mcp (Streamable HTTP, JSON response; POST JSON-RPC 2.0). +No key and no session. Tools: list_launches, get_launch, search_launches, get_token_trades, get_token_holders, +get_recent_activity, list_posts, list_community_pairs, get_points_leaderboard, get_protocol_totals. No tool writes. +Client config: {"mcpServers":{"openlaunch":{"type":"http","url":"${SITE_URL}/api/mcp"}}} +Limits: 120 requests per IP per minute, 64 KB per request; browser origins are checked. Details: ${BRAND_GITHUB}/blob/main/docs/mcp.md + ## API - GET ${SITE_URL}/api/launch/list?chain=base|robinhood|arc|elysium&sort=live|new|mcap|volume|gainers|holders&window=1h|24h|all&limit=50 sort=live (the home page default; "trending" is an alias): tokens an outside wallet traded in the last 24h first, ranked by outside diff --git a/app/src/lib/mcp/origin.ts b/app/src/lib/mcp/origin.ts new file mode 100644 index 00000000..77250696 --- /dev/null +++ b/app/src/lib/mcp/origin.ts @@ -0,0 +1,52 @@ +/** + * Origin policy for the MCP endpoint (MCP's DNS-rebinding guidance). + * + * A browser sends `Origin` on a cross-origin POST. Without a check, any page + * could make a visitor's browser call a local MCP server; the MCP specification + * tells servers to validate the header. Non-browser clients (the usual MCP + * transport) send no Origin and are allowed through; the endpoint is public and + * read-only either way. + * + * The site's own origin and its `www.` twin are allowed, and in development so + * are localhost and 127.0.0.1 on any port (Next picks another port when 3000 is + * busy). Everything else is refused. + */ + +function parseOrigin(value: string): URL | null { + let url: URL; + try { + url = new URL(value); + } catch { + return null; + } + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + // An origin is scheme://host[:port] exactly: no path, query, fragment or credentials. + if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null; + return url; +} + +function sameHost(a: URL, b: URL): boolean { + return a.protocol === b.protocol && a.host === b.host; +} + +export function originAllowed(origin: string | null, siteUrl: string, options: { dev?: boolean } = {}): boolean { + if (origin === null) return true; // a non-browser MCP client + const parsed = parseOrigin(origin.trim()); + if (!parsed) return false; + if (options.dev && (parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]")) return true; + const site = parseOrigin(siteUrl.trim()); + if (!site) return false; + if (sameHost(parsed, site)) return true; + // The legacy host redirects pages but /api stays reachable on it; accept both + // the bare site and its www twin so a browser client on either is not blocked. + if (site.hostname.startsWith("www.")) { + const bare = new URL(site.href); + bare.hostname = site.hostname.slice(4); + if (sameHost(parsed, bare)) return true; + } else { + const www = new URL(site.href); + www.hostname = `www.${site.hostname}`; + if (sameHost(parsed, www)) return true; + } + return false; +} diff --git a/app/src/lib/mcp/protocol.ts b/app/src/lib/mcp/protocol.ts new file mode 100644 index 00000000..e434a052 --- /dev/null +++ b/app/src/lib/mcp/protocol.ts @@ -0,0 +1,64 @@ +/** + * MCP (Model Context Protocol) constants and JSON-RPC 2.0 envelopes. + * + * The server is deliberately stateless: it answers one POST at a time, never + * opens an SSE stream, and never issues server-to-client requests. That is a + * valid MCP transport (the spec allows a JSON response instead of an SSE + * stream) and it keeps the endpoint behind the same global request caps as the + * rest of the JSON API. + * + * Versions are negotiated, not assumed: `initialize` echoes the client's + * version when this server speaks it and otherwise offers the newest one it + * knows, so an older client can disconnect with a reason instead of failing + * halfway through a tool call. + */ + +// 2024-11-05's Streamable HTTP transport starts with a GET/SSE handshake. This endpoint only serves POST/JSON, so +// advertising that version would strand clients that follow the spec: they could never reach initialize. +export const MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"] as const; +export type McpProtocolVersion = (typeof MCP_PROTOCOL_VERSIONS)[number]; +export const MCP_LATEST_PROTOCOL_VERSION: McpProtocolVersion = MCP_PROTOCOL_VERSIONS[0]; + +export type JsonRpcId = string | number; + +export type JsonRpcSuccess = { jsonrpc: "2.0"; id: JsonRpcId; result: unknown }; + +export type JsonRpcFailure = { + jsonrpc: "2.0"; + id: JsonRpcId | null; + error: { code: number; message: string; data?: unknown }; +}; + +export type JsonRpcResponse = JsonRpcSuccess | JsonRpcFailure; + +/** JSON-RPC 2.0 and MCP error codes used by this server. */ +export const RPC_ERRORS = { + parse: -32700, + invalidRequest: -32600, + methodNotFound: -32601, + invalidParams: -32602, + internal: -32603, +} as const; + +export function success(id: JsonRpcId, result: unknown): JsonRpcSuccess { + return { jsonrpc: "2.0", id, result }; +} + +export function failure(id: JsonRpcId | null, code: number, message: string, data?: unknown): JsonRpcFailure { + return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } }; +} + +/** True for a protocol version this server speaks. */ +export function isSupportedProtocolVersion(raw: unknown): raw is McpProtocolVersion { + return typeof raw === "string" && (MCP_PROTOCOL_VERSIONS as readonly string[]).includes(raw); +} + +/** A protocol version this server speaks (used for `initialize`). */ +export function supportedVersion(raw: unknown): McpProtocolVersion { + return isSupportedProtocolVersion(raw) ? raw : MCP_LATEST_PROTOCOL_VERSION; +} + +/** True when a JSON-RPC id is a string or a number, as MCP requires. */ +export function isJsonRpcId(value: unknown): value is JsonRpcId { + return typeof value === "string" || (typeof value === "number" && Number.isFinite(value)); +} diff --git a/app/src/lib/mcp/schema.test.ts b/app/src/lib/mcp/schema.test.ts new file mode 100644 index 00000000..2d7a87b1 --- /dev/null +++ b/app/src/lib/mcp/schema.test.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { isPlainObject, validateArgs, type ObjectSchema } from "./schema.ts"; + +const schema: ObjectSchema = { + type: "object", + properties: { + sort: { type: "string", description: "sort", enum: ["new", "live"], default: "new" }, + limit: { type: "integer", description: "limit", minimum: 1, maximum: 25, default: 10 }, + token: { type: "string", description: "token", pattern: "^0x[0-9a-fA-F]{40}$" }, + ratio: { type: "number", description: "ratio", minimum: 0, maximum: 1 }, + flag: { type: "boolean", description: "flag" }, + }, + additionalProperties: false, +}; + +test("validateArgs applies defaults and keeps supplied values", () => { + const r = validateArgs(schema, { token: "0x" + "a".repeat(40) }); + assert.equal(r.ok, true); + if (!r.ok) return; + assert.deepEqual(r.value, { sort: "new", limit: 10, token: "0x" + "a".repeat(40) }); +}); + +test("validateArgs rejects unknown keys, wrong types and out-of-range values", () => { + const cases: Array<[unknown, RegExp]> = [ + [null, /must be an object/], + [[], /must be an object/], + [{ nope: 1 }, /unknown argument "nope"/], + [{ limit: "10" }, /must be a number/], + [{ limit: 1.5 }, /must be an integer/], + [{ limit: 0 }, /at least 1/], + [{ limit: 26 }, /at most 25/], + [{ sort: "hot" }, /must be one of: new, live/], + [{ token: "0x123" }, /invalid format/], + [{ ratio: 2 }, /at most 1/], + [{ flag: "yes" }, /must be a boolean/], + ]; + for (const [input, expected] of cases) { + const r = validateArgs(schema, input); + assert.equal(r.ok, false, JSON.stringify(input)); + if (r.ok) continue; + assert.match(r.error, expected); + } +}); + +test("validateArgs requires properties listed in required", () => { + const required: ObjectSchema = { ...schema, required: ["token"] }; + const r = validateArgs(required, {}); + assert.equal(r.ok, false); + if (r.ok) return; + assert.match(r.error, /argument "token" is required/); +}); + +test("isPlainObject rejects arrays, null and class instances", () => { + assert.equal(isPlainObject({}), true); + assert.equal(isPlainObject(Object.create(null)), true); + assert.equal(isPlainObject([]), false); + assert.equal(isPlainObject(null), false); + assert.equal(isPlainObject(new Date()), false); +}); diff --git a/app/src/lib/mcp/schema.ts b/app/src/lib/mcp/schema.ts new file mode 100644 index 00000000..f162fc09 --- /dev/null +++ b/app/src/lib/mcp/schema.ts @@ -0,0 +1,110 @@ +/** + * A very small JSON Schema subset for MCP tool inputs, plus a validator. + * + * The tools are read-only and take scalars, so the whole surface is: an object + * with typed properties, enums, bounds and a string pattern. Unknown keys are + * rejected: a typo in a tool call should fail loudly instead of silently + * returning the default list. Defaults are applied by the validator, so a + * tool's `run` always sees the same shape. + * + * No dependency: the schemas are also served to clients in `tools/list`, and + * `schema.test.ts` keeps the validator and the advertised schemas honest. + */ + +export type PropertySchema = + | { + type: "string"; + description: string; + enum?: readonly string[]; + minLength?: number; + maxLength?: number; + pattern?: string; + default?: string; + } + | { + type: "integer"; + description: string; + enum?: readonly number[]; + minimum?: number; + maximum?: number; + default?: number; + } + | { + type: "number"; + description: string; + enum?: readonly number[]; + minimum?: number; + maximum?: number; + default?: number; + } + | { type: "boolean"; description: string; default?: boolean }; + +export type ObjectSchema = { + type: "object"; + properties: Record; + required?: readonly string[]; + additionalProperties?: false; +}; + +export type Validation = { ok: true; value: Record } | { ok: false; error: string }; + +/** A plain object (not an array, not null, not a class instance). */ +export function isPlainObject(value: unknown): value is Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function fail(path: string, expected: string): Validation { + return { ok: false, error: `${path} ${expected}` }; +} + +function property(name: string, schema: PropertySchema, raw: unknown): { ok: true; value: unknown } | { ok: false; error: string } { + const path = `argument "${name}"`; + if (schema.type === "string") { + if (typeof raw !== "string") return { ok: false, error: `${path} must be a string` }; + if (schema.enum && !schema.enum.includes(raw)) return { ok: false, error: `${path} must be one of: ${schema.enum.join(", ")}` }; + if (schema.minLength !== undefined && raw.length < schema.minLength) return { ok: false, error: `${path} must be at least ${schema.minLength} characters` }; + if (schema.maxLength !== undefined && raw.length > schema.maxLength) return { ok: false, error: `${path} must be at most ${schema.maxLength} characters` }; + if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(raw)) return { ok: false, error: `${path} has an invalid format` }; + return { ok: true, value: raw }; + } + if (schema.type === "integer" || schema.type === "number") { + if (typeof raw !== "number" || !Number.isFinite(raw)) return { ok: false, error: `${path} must be a number` }; + if (schema.type === "integer" && !Number.isInteger(raw)) return { ok: false, error: `${path} must be an integer` }; + if (schema.enum && !schema.enum.includes(raw)) return { ok: false, error: `${path} must be one of: ${schema.enum.join(", ")}` }; + if (schema.minimum !== undefined && raw < schema.minimum) return { ok: false, error: `${path} must be at least ${schema.minimum}` }; + if (schema.maximum !== undefined && raw > schema.maximum) return { ok: false, error: `${path} must be at most ${schema.maximum}` }; + return { ok: true, value: raw }; + } + if (typeof raw !== "boolean") return { ok: false, error: `${path} must be a boolean` }; + return { ok: true, value: raw }; +} + +/** + * Validate `input` against an object schema, applying defaults. Required + * properties have to be present; optional ones may be omitted. A value of + * `undefined` counts as omitted (JSON never carries it, but a direct caller + * can). + */ +export function validateArgs(schema: ObjectSchema, input: unknown): Validation { + if (!isPlainObject(input)) return fail("arguments", "must be an object"); + if (schema.additionalProperties === false) { + for (const key of Object.keys(input)) { + if (!Object.hasOwn(schema.properties, key)) return { ok: false, error: `unknown argument "${key}"` }; + } + } + const out: Record = {}; + for (const [name, prop] of Object.entries(schema.properties)) { + const raw = input[name]; + if (raw === undefined) { + if (schema.required?.includes(name)) return { ok: false, error: `argument "${name}" is required` }; + if (prop.default !== undefined) out[name] = prop.default; + continue; + } + const checked = property(name, prop, raw); + if (!checked.ok) return { ok: false, error: checked.error }; + out[name] = checked.value; + } + return { ok: true, value: out }; +} diff --git a/app/src/lib/mcp/server.test.ts b/app/src/lib/mcp/server.test.ts new file mode 100644 index 00000000..863d48ff --- /dev/null +++ b/app/src/lib/mcp/server.test.ts @@ -0,0 +1,178 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { failure, isJsonRpcId, isSupportedProtocolVersion, RPC_ERRORS, supportedVersion, success } from "./protocol.ts"; +import { createMcpServer, ToolError, type McpTool } from "./server.ts"; +import type { ObjectSchema } from "./schema.ts"; + +const echoSchema: ObjectSchema = { + type: "object", + properties: { + value: { type: "string", description: "text to echo", minLength: 1, default: "hello" }, + }, + additionalProperties: false, +}; + +function echoTool(overrides: Partial = {}): McpTool { + return { + name: "echo", + title: "Echo", + description: "Echo a value.", + inputSchema: echoSchema, + annotations: { readOnlyHint: true }, + run: async (args) => ({ echo: args.value }), + ...overrides, + }; +} + +function server(tools: McpTool[] = [echoTool()], onToolError?: (tool: string, error: unknown) => void) { + return createMcpServer({ + tools, + serverInfo: { name: "openlaunch-test", version: "9.9.9" }, + instructions: "read only", + onToolError, + }); +} + +const call = (method: string, params?: unknown, id: string | number = 1) => ({ jsonrpc: "2.0", id, method, params }); + +test("initialize negotiates a known version and otherwise offers the latest", async () => { + const s = server(); + const known = await s.handle(call("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "t", version: "1" } })); + assert.ok(known && "result" in known); + assert.equal((known.result as { protocolVersion: string }).protocolVersion, "2025-03-26"); + assert.deepEqual((known.result as { serverInfo: unknown }).serverInfo, { name: "openlaunch-test", version: "9.9.9" }); + assert.equal((known.result as { instructions: string }).instructions, "read only"); + + const unknown = await s.handle(call("initialize", { protocolVersion: "1999-01-01" })); + assert.ok(unknown && "result" in unknown); + assert.equal((unknown.result as { protocolVersion: string }).protocolVersion, "2025-06-18"); +}); + +test("ping and tools/list answer without running a tool", async () => { + let ran = 0; + const s = server([echoTool({ run: async () => { ran += 1; return {}; } })]); + const pong = await s.handle(call("ping")); + assert.deepEqual(pong, success(1, {})); + const list = await s.handle(call("tools/list")); + assert.ok(list && "result" in list); + const tools = (list.result as { tools: Array> }).tools; + assert.equal(tools.length, 1); + assert.equal(tools[0].name, "echo"); + assert.equal(tools[0].inputSchema, echoSchema); + assert.deepEqual(tools[0].annotations, { readOnlyHint: true }); + assert.equal("run" in tools[0], false); + assert.equal(ran, 0); +}); + +test("tools/call applies defaults, runs the tool and returns JSON text", async () => { + let seen: Record | null = null; + const s = server([echoTool({ run: async (args) => { seen = args; return { echo: args.value, ok: true }; } })]); + const r = await s.handle(call("tools/call", { name: "echo", arguments: {} })); + assert.deepEqual(seen, { value: "hello" }); + assert.ok(r && "result" in r); + const result = r.result as { content: Array<{ type: string; text: string }>; isError: boolean }; + assert.equal(result.isError, false); + assert.equal(result.content[0].type, "text"); + assert.deepEqual(JSON.parse(result.content[0].text), { echo: "hello", ok: true }); +}); + +test("invalid tool arguments are a tool execution error, not a protocol error", async () => { + let ran = 0; + const s = server([echoTool({ run: async () => { ran += 1; return {}; } })]); + for (const args of [{ nope: 1 }, { value: 42 }, { value: "" }]) { + const r = await s.handle(call("tools/call", { name: "echo", arguments: args }, 7)); + assert.ok(r && "result" in r); + assert.equal(r.id, 7); + const result = r.result as { isError: boolean; content: Array<{ text: string }> }; + assert.equal(result.isError, true); + assert.match(result.content[0].text, /argument|unknown/); + } + assert.equal(ran, 0); +}); + +test("tool errors are safe to show; unknown errors are generic and reported", async () => { + const reported: string[] = []; + const s = server([ + echoTool({ name: "known", run: async () => { throw new ToolError("no such launch"); } }), + echoTool({ name: "unknown", run: async () => { throw new Error("database password is hunter2"); } }), + ], (_tool, error) => reported.push(error instanceof Error ? error.message : String(error))); + + const known = await s.handle(call("tools/call", { name: "known", arguments: {} })); + assert.ok(known && "result" in known); + assert.deepEqual((known.result as { content: Array<{ text: string }> }).content[0].text, "no such launch"); + + const unknown = await s.handle(call("tools/call", { name: "unknown", arguments: {} })); + assert.ok(unknown && "result" in unknown); + const text = (unknown.result as { content: Array<{ text: string }> }).content[0].text; + assert.match(text, /could not complete/); + assert.doesNotMatch(text, /hunter2/); + assert.deepEqual(reported, ["database password is hunter2"]); +}); + +test("a result JSON cannot encode is a tool error, not a 500", async () => { + const reported: string[] = []; + const s = server([echoTool({ run: async () => ({ n: 1n }) })], (_tool, error) => reported.push(String(error))); + const r = await s.handle(call("tools/call", { name: "echo", arguments: {} })); + assert.ok(r && "result" in r); + assert.equal((r.result as { isError: boolean }).isError, true); + assert.equal(reported.length, 1); +}); + +test("unknown tools and methods get the right JSON-RPC errors", async () => { + const s = server(); + const tool = await s.handle(call("tools/call", { name: "nope", arguments: {} }, 3)); + assert.deepEqual(tool, failure(3, RPC_ERRORS.invalidParams, "unknown tool: nope")); + + const method = await s.handle(call("resources/list", {}, 4)); + assert.deepEqual(method, failure(4, RPC_ERRORS.methodNotFound, "method not found: resources/list")); + + const params = await s.handle({ ...call("tools/list", "bad"), params: "bad" }); + assert.deepEqual(params, failure(1, RPC_ERRORS.invalidParams, "params must be an object")); +}); + +test("handleBatch answers requests in order and omits notifications", async () => { + const s = server(); + const responses = await s.handleBatch([ + call("ping", undefined, 1), + { jsonrpc: "2.0", method: "notifications/initialized" }, + call("tools/list", undefined, "list"), + ["nested"], + call("made/up", undefined, 4), + ]); + assert.equal(responses.length, 4); + assert.deepEqual(responses[0], success(1, {})); + assert.ok("result" in responses[1]); + assert.equal((responses[1].result as { tools: unknown[] }).tools.length, 1); + assert.ok("error" in responses[2]); + assert.equal(responses[2].error.code, RPC_ERRORS.invalidRequest); + assert.deepEqual(responses[3], failure(4, RPC_ERRORS.methodNotFound, "method not found: made/up")); + + assert.deepEqual(await s.handleBatch([{ jsonrpc: "2.0", method: "made/up" }]), []); +}); + +test("notifications get no response; malformed requests get invalid-request", async () => { + const s = server(); + assert.equal(await s.handle({ jsonrpc: "2.0", method: "notifications/initialized" }), null); + assert.equal(await s.handle({ jsonrpc: "2.0", method: "made/up" }), null); + + for (const bad of [null, [], "x", { jsonrpc: "1.0", id: 1, method: "ping" }, { jsonrpc: "2.0", id: 1 }, { jsonrpc: "2.0", id: null, method: "ping" }]) { + const r = await s.handle(bad); + assert.ok(r && "error" in r, JSON.stringify(bad)); + assert.equal(r.error.code, RPC_ERRORS.invalidRequest); + } +}); + +test("isJsonRpcId and supportedVersion keep their contracts", () => { + assert.equal(isJsonRpcId("a"), true); + assert.equal(isJsonRpcId(0), true); + assert.equal(isJsonRpcId(null), false); + assert.equal(isJsonRpcId(Number.NaN), false); + assert.equal(isSupportedProtocolVersion("2025-06-18"), true); + assert.equal(isSupportedProtocolVersion("2025-03-26"), true); + // 2024-11-05's HTTP transport needs a GET/SSE handshake this server does not serve. + assert.equal(isSupportedProtocolVersion("2024-11-05"), false); + assert.equal(isSupportedProtocolVersion("nope"), false); + assert.equal(isSupportedProtocolVersion(null), false); + assert.equal(supportedVersion("2024-11-05"), "2025-06-18"); + assert.equal(supportedVersion("nope"), "2025-06-18"); +}); diff --git a/app/src/lib/mcp/server.ts b/app/src/lib/mcp/server.ts new file mode 100644 index 00000000..4e8710f3 --- /dev/null +++ b/app/src/lib/mcp/server.ts @@ -0,0 +1,173 @@ +import { isPlainObject, validateArgs, type ObjectSchema } from "./schema.ts"; +import { + failure, + isJsonRpcId, + RPC_ERRORS, + success, + supportedVersion, + type JsonRpcId, + type JsonRpcResponse, +} from "./protocol.ts"; + +/** A problem with the tool's input (or a missing record), safe to show to the caller. */ +export class ToolError extends Error { + constructor(message: string) { + super(message); + this.name = "ToolError"; + } +} + +export type ToolAnnotations = { + title?: string; + readOnlyHint?: boolean; + destructiveHint?: boolean; + idempotentHint?: boolean; + openWorldHint?: boolean; +}; + +/** + * One read-only tool. `run` receives arguments that have already been checked + * against `inputSchema` (defaults applied), and returns a JSON-serialisable + * value. Throw `ToolError` for a caller-correctable failure; anything else is + * reported as a generic tool failure and logged by the route. + */ +export type McpTool = { + name: string; + title: string; + description: string; + inputSchema: ObjectSchema; + annotations: ToolAnnotations; + run: (args: Record) => Promise; +}; + +export type McpServerInfo = { name: string; version: string }; + +export type McpServerOptions = { + tools: readonly McpTool[]; + serverInfo: McpServerInfo; + instructions?: string; + /** Called when a tool throws something other than `ToolError`. Never sent to the caller. */ + onToolError?: (tool: string, error: unknown) => void; +}; + +type Message = Record; + +function invalid(id: JsonRpcId | null, message: string): JsonRpcResponse { + return failure(id, RPC_ERRORS.invalidRequest, message); +} + +function paramsObject(params: unknown): Record | null { + return params === undefined ? {} : isPlainObject(params) ? params : null; +} + +/** + * Build a stateless MCP request handler. The returned `handle` takes one + * decoded JSON-RPC value and returns one response, or null when the message is + * a notification (which JSON-RPC forbids answering). `handleBatch` does the + * same for one batch of messages; the route decides whether the request's + * protocol version allows a batch. + */ +export function createMcpServer(options: McpServerOptions): { + handle: (value: unknown) => Promise; + handleBatch: (values: readonly unknown[]) => Promise; +} { + const byName = new Map(options.tools.map((tool) => [tool.name, tool])); + const publicTools = options.tools.map((tool) => ({ + name: tool.name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema, + annotations: tool.annotations, + })); + + async function handleOne(value: unknown): Promise { + if (!isPlainObject(value)) return invalid(null, "A JSON-RPC request must be an object"); + const message = value as Message; + if (message.jsonrpc !== "2.0") return invalid(null, 'jsonrpc must be "2.0"'); + if (typeof message.method !== "string" || message.method.length === 0) return invalid(null, "method must be a non-empty string"); + + const notification = !Object.hasOwn(message, "id"); + const id = notification ? null : isJsonRpcId(message.id) ? message.id : null; + if (!notification && id === null) return invalid(null, "id must be a string or a number"); + // A notification is never answered, including one this server does not + // know: JSON-RPC has no way to say so. + if (notification) return null; + + const requestId = id as JsonRpcId; + const params = paramsObject(message.params); + if (params === null) return failure(requestId, RPC_ERRORS.invalidParams, "params must be an object"); + + switch (message.method) { + case "initialize": + return success(requestId, { + protocolVersion: supportedVersion(params.protocolVersion), + capabilities: { tools: { listChanged: false } }, + serverInfo: options.serverInfo, + ...(options.instructions ? { instructions: options.instructions } : {}), + }); + + case "ping": + return success(requestId, {}); + + case "tools/list": + return success(requestId, { tools: publicTools }); + + case "tools/call": { + if (typeof params.name !== "string" || params.name.length === 0) { + return failure(requestId, RPC_ERRORS.invalidParams, "tools/call needs a tool name"); + } + const tool = byName.get(params.name); + if (!tool) return failure(requestId, RPC_ERRORS.invalidParams, `unknown tool: ${params.name}`); + const rawArgs = params.arguments ?? {}; + if (!isPlainObject(rawArgs)) { + return toolFailure(requestId, "tool arguments must be an object"); + } + const checked = validateArgs(tool.inputSchema, rawArgs); + if (!checked.ok) return toolFailure(requestId, checked.error); + let result: unknown; + try { + result = await tool.run(checked.value); + } catch (error) { + if (error instanceof ToolError) return toolFailure(requestId, error.message); + options.onToolError?.(tool.name, error); + return toolFailure(requestId, `${tool.name} could not complete; try again shortly`); + } + let text: string; + try { + text = JSON.stringify(result, null, 2) ?? "null"; + } catch { + options.onToolError?.(tool.name, new Error("tool result is not JSON-serialisable")); + return toolFailure(requestId, `${tool.name} returned a value that could not be encoded`); + } + return success(requestId, { content: [{ type: "text", text }], isError: false }); + } + + default: + return failure(requestId, RPC_ERRORS.methodNotFound, `method not found: ${message.method}`); + } + } + + async function handle(value: unknown): Promise { + // A single-message entry point must not accept a batch silently; the + // route calls handleBatch for versions that allow one. + if (Array.isArray(value)) return invalid(null, "send JSON-RPC batches through handleBatch"); + return handleOne(value); + } + + async function handleBatch(values: readonly unknown[]): Promise { + const responses: JsonRpcResponse[] = []; + for (const value of values) { + const response = await handleOne(value); + // Notifications have no response and are omitted, as JSON-RPC requires. + if (response !== null) responses.push(response); + } + return responses; + } + + return { handle, handleBatch }; +} + +/** A tool execution error: valid JSON-RPC, `isError: true` in the tool result, so the model can correct itself. */ +function toolFailure(id: JsonRpcId, message: string): JsonRpcResponse { + return success(id, { content: [{ type: "text", text: message }], isError: true }); +} diff --git a/app/src/lib/mcp/tools.test.ts b/app/src/lib/mcp/tools.test.ts new file mode 100644 index 00000000..038e1b89 --- /dev/null +++ b/app/src/lib/mcp/tools.test.ts @@ -0,0 +1,232 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { validateArgs } from "./schema.ts"; +import { ToolError } from "./server.ts"; +import { createMcpTools, type McpToolDeps } from "./tools.ts"; + +const TOKEN = "0x" + "a".repeat(40); +const LAUNCH = { chain: "base", token: TOKEN, quote_decimals: 18, quote_decimals_known: true, symbol: "TEST" }; + +function tools(overrides: Record) { + return createMcpTools(overrides as unknown as Partial); +} + +async function run(all: ReturnType, name: string, args: Record = {}) { + const tool = all.find((t) => t.name === name); + assert.ok(tool, name); + const checked = validateArgs(tool.inputSchema, args); + assert.equal(checked.ok, true, checked.ok ? "" : checked.error); + if (!checked.ok) throw new Error(checked.error); + return tool.run(checked.value); +} + +test("tool names are unique and every schema rejects unknown arguments", () => { + const all = createMcpTools(); + const names = all.map((t) => t.name); + assert.equal(new Set(names).size, names.length); + assert.ok(names.length >= 8); + for (const tool of all) { + assert.equal(tool.inputSchema.additionalProperties, false, tool.name); + assert.match(tool.description, /\S/); + assert.equal(tool.annotations.readOnlyHint, true); + } +}); + +test("list_launches passes defaults and the caller's options to the site's list model", async () => { + let seen: Record | null = null; + const all = tools({ + ethUsd: async () => 2_500, + listLaunchesPage: async (opts: Record) => { + seen = opts; + return { items: [LAUNCH], hasMore: true }; + }, + }); + const result = (await run(all, "list_launches")) as { eth_usd: number; has_more: boolean; launches: unknown[] }; + assert.equal(result.eth_usd, 2_500); + assert.equal(result.has_more, true); + assert.equal(result.launches.length, 1); + assert.deepEqual(seen, { + sort: "live", + window: "all", + mcap: "all", + filter: null, + chain: null, + launcher: undefined, + limit: 10, + offset: 0, + ethUsd: 2_500, + }); + + await run(all, "list_launches", { chain: "arc", sort: "volume", window: "24h", filter: "burn", launcher: TOKEN, limit: 1, offset: 2 }); + assert.deepEqual(seen && (seen as Record).chain, "arc"); + assert.deepEqual(seen && (seen as Record).filter, "burn"); + assert.deepEqual(seen && (seen as Record).limit, 1); +}); + +test("get_launch lowercases the address and reports a missing launch", async () => { + let asked: unknown[] = []; + const all = tools({ + ethUsd: async () => 3_000, + getLaunch: async (...args: unknown[]) => { + asked = args; + return LAUNCH; + }, + }); + const upper = "0x" + "A".repeat(40); + const result = (await run(all, "get_launch", { chain: "base", token: upper })) as { launch: unknown }; + assert.deepEqual(asked, ["base", TOKEN, 3_000]); + assert.equal(result.launch, LAUNCH); + + const missing = tools({ ethUsd: async () => null, getLaunch: async () => null }); + await assert.rejects(() => run(missing, "get_launch", { chain: "base", token: TOKEN }), (error: unknown) => error instanceof ToolError); +}); + +test("get_token_trades reads the launch first, for the quote's decimals", async () => { + let swapArgs: unknown[] = []; + const all = tools({ + getLaunch: async () => LAUNCH, + getSwaps: async (...args: unknown[]) => { + swapArgs = args; + return [{ tx_hash: "0x1" }]; + }, + }); + const result = (await run(all, "get_token_trades", { chain: "base", token: TOKEN, limit: 5 })) as { quote_decimals: number; trades: unknown[] }; + assert.deepEqual(swapArgs, ["base", TOKEN, 18, 5]); + assert.equal(result.quote_decimals, 18); + assert.equal(result.trades.length, 1); +}); + +test("get_token_trades refuses to price swaps when the quote's decimals are only a placeholder", async () => { + let called = false; + const all = tools({ + getLaunch: async () => ({ ...LAUNCH, quote_decimals_known: false, quote_decimals: 18 }), + getSwaps: async () => { + called = true; + return []; + }, + }); + await assert.rejects( + () => run(all, "get_token_trades", { chain: "base", token: TOKEN }), + (error: unknown) => error instanceof ToolError && /quote precision pending/i.test(error.message), + ); + assert.equal(called, false, "no price is derived from placeholder decimals"); +}); + +test("get_token_holders returns the panel or a caller-correctable error", async () => { + const panel = { holders: 12, top: [], synced: true }; + const all = tools({ getHolderPanel: async () => panel }); + assert.deepEqual(await run(all, "get_token_holders", { chain: "base", token: TOKEN }), { chain: "base", token: TOKEN, ...panel }); + + const none = tools({ getHolderPanel: async () => null }); + await assert.rejects(() => run(none, "get_token_holders", { chain: "base", token: TOKEN }), ToolError); +}); + +test("get_token_holders with an unsynced panel reports indexing instead of zero holders and no red flags", async () => { + const panel = { + synced: false, + holders: 3, + top: [{ address: TOKEN, balance: "10", bps: 100 }], + top10Bps: 100, + poolBps: 9000, + creator: { address: TOKEN, bps: 0, bought: "0", sold: "0", sells: 0 }, + sniper: { wallets: 0, bps: 0 }, + notes: [{ level: "good", text: "no red flags" }], + }; + const all = tools({ getHolderPanel: async () => panel }); + const result = (await run(all, "get_token_holders", { chain: "base", token: TOKEN })) as Record; + assert.equal(result.synced, false); + assert.equal(result.holders, null, "a partial backfill is not a count of zero"); + assert.match(String(result.indexing), /still being indexed/); + assert.equal(Object.hasOwn(result, "top"), false, "rankings are omitted while indexing"); + assert.equal(Object.hasOwn(result, "notes"), false, "trust notes are omitted while indexing"); +}); + +test("search_launches and get_recent_activity pass the price through", async () => { + let searchOpts: Record | null = null; + let feedArgs: unknown[] = []; + const all = tools({ + ethUsd: async () => 1_900, + searchLaunches: async (_q: string, opts: Record) => { + searchOpts = opts; + return [LAUNCH]; + }, + getLaunchFeed: async (...args: unknown[]) => { + feedArgs = args; + return [{ kind: "swap" }]; + }, + }); + const search = (await run(all, "search_launches", { query: "test", chain: "base", order: "holders", limit: 3 })) as { launches: unknown[] }; + assert.deepEqual(searchOpts, { chain: "base", limit: 3, ethUsd: 1_900, order: "holders" }); + assert.equal(search.launches.length, 1); + + const feed = (await run(all, "get_recent_activity", { limit: 7 })) as { activity: unknown[] }; + assert.deepEqual(feedArgs, [7, 1_900]); + assert.equal(feed.activity.length, 1); +}); + +test("list_posts requires chain and token only for the token scope", async () => { + let feedArgs: unknown[] = []; + let tokenArgs: unknown[] = []; + const all = tools({ + listFeed: async (...args: unknown[]) => { + feedArgs = args; + return [{ id: 1 }]; + }, + listTokenPosts: async (...args: unknown[]) => { + tokenArgs = args; + return { posts: [{ id: 2 }], muted: false, nextCursor: 1 }; + }, + }); + const feed = (await run(all, "list_posts", { scope: "feed", limit: 5 })) as { posts: unknown[] }; + assert.deepEqual(feedArgs, [5, 0]); + assert.equal(feed.posts.length, 1); + + const token = (await run(all, "list_posts", { scope: "token", chain: "base", token: TOKEN, limit: 5, before_id: 9 })) as { posts: unknown[] }; + assert.deepEqual(tokenArgs, ["base", TOKEN, 5, 9]); + assert.equal(token.posts.length, 1); + + await assert.rejects(() => run(all, "list_posts", { scope: "token" }), ToolError); +}); + +test("list_community_pairs shows listed pairs only and filters by chain", async () => { + const all = tools({ + loadPairs: async () => [ + { chain: "base", status: "listed", symbol: "A" }, + { chain: "base", status: "suspended", symbol: "B" }, + { chain: "arc", status: "listed", symbol: "C" }, + ], + }); + const base = (await run(all, "list_community_pairs", { chain: "base" })) as { count: number; pairs: Array<{ symbol: string }> }; + assert.equal(base.count, 1); + assert.equal(base.pairs[0].symbol, "A"); + + const every = (await run(all, "list_community_pairs")) as { count: number }; + assert.equal(every.count, 2); +}); + +test("get_points_leaderboard handles no public season and a live board", async () => { + const none = tools({ publicSeason: async () => null }); + assert.deepEqual(await run(none, "get_points_leaderboard"), { season: null, board: "creator", rows: [], names: {} }); + + const season = { id: 7, slug: "s1" }; + let boardArgs: unknown[] = []; + const all = tools({ + publicSeason: async () => season, + boardRows: async (...args: unknown[]) => { + boardArgs = args; + return { rows: [{ rank: 1 }], names: { "0x1": "alice" } }; + }, + }); + assert.deepEqual(await run(all, "get_points_leaderboard", { board: "scout", limit: 2 }), { + season, + board: "scout", + rows: [{ rank: 1 }], + names: { "0x1": "alice" }, + }); + assert.deepEqual(boardArgs, [7, "scout", 2]); +}); + +test("get_protocol_totals forwards the ETH price and the totals", async () => { + const all = tools({ ethUsd: async () => 2_000, getLaunchTotals: async () => ({ launches: 3, usd_partial: false }) }); + assert.deepEqual(await run(all, "get_protocol_totals"), { eth_usd: 2_000, totals: { launches: 3, usd_partial: false } }); +}); diff --git a/app/src/lib/mcp/tools.ts b/app/src/lib/mcp/tools.ts new file mode 100644 index 00000000..1a1b26fc --- /dev/null +++ b/app/src/lib/mcp/tools.ts @@ -0,0 +1,387 @@ +import { CHAIN_KEYS, type ChainKey } from "@/lib/chainPublic"; +import { getHolderPanel } from "@/lib/launchpad/holdersServer"; +import { holderFactsAvailable } from "@/lib/launchpad/token-market"; +import { listFeed, listTokenPosts } from "@/lib/launchpad/postsServer"; +import { loadPairs } from "@/lib/launchpad/pairsServer"; +import { boardRows, publicSeason } from "@/lib/points/server"; +import { ethUsd } from "@/lib/launchpad/ethPrice"; +import { getLaunch, getLaunchFeed, getLaunchTotals, getSwaps, listLaunchesPage, searchLaunches } from "@/lib/launchpad/queries"; +import type { LaunchSort, VolumeWindow } from "@/lib/launchpad/queries"; +import type { LaunchFilter } from "@/lib/launchpad/search"; +import type { McapMode } from "@/lib/launchpad/mcap-policy"; +import { ToolError, type McpTool } from "./server.ts"; + +const ADDRESS = "^0x[0-9a-fA-F]{40}$"; + +/** + * Everything a tool can reach. Injected so `tools.test.ts` can exercise the + * argument handling and output shape without a database, an RPC endpoint, or + * a live price feed. The defaults are the app's own read model: the same + * functions the site and `/api/launch/*` use, never a second query. + */ +export type McpToolDeps = { + ethUsd: typeof ethUsd; + listLaunchesPage: typeof listLaunchesPage; + getLaunch: typeof getLaunch; + getSwaps: typeof getSwaps; + searchLaunches: typeof searchLaunches; + getLaunchFeed: typeof getLaunchFeed; + getHolderPanel: typeof getHolderPanel; + listFeed: typeof listFeed; + listTokenPosts: typeof listTokenPosts; + loadPairs: typeof loadPairs; + publicSeason: typeof publicSeason; + boardRows: typeof boardRows; + getLaunchTotals: typeof getLaunchTotals; +}; + +const defaults: McpToolDeps = { + ethUsd, + listLaunchesPage, + getLaunch, + getSwaps, + searchLaunches, + getLaunchFeed, + getHolderPanel, + listFeed, + listTokenPosts, + loadPairs, + publicSeason, + boardRows, + getLaunchTotals, +}; + +const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const; + +const chainProperty = { + type: "string" as const, + description: "Chain to read: base, robinhood, arc or elysium. Omit for every configured chain.", + enum: CHAIN_KEYS, +}; + +const tokenProperty = { + type: "string" as const, + description: "Token contract address (0x followed by 40 hex characters).", + pattern: ADDRESS, +}; + +const limitProperty = (max: number, fallback: number) => ({ + type: "integer" as const, + description: `Maximum number of rows to return (1-${max}).`, + minimum: 1, + maximum: max, + default: fallback, +}); + +/** The public tools. Order is the order `tools/list` serves. */ +export function createMcpTools(overrides: Partial = {}): McpTool[] { + const deps: McpToolDeps = { ...defaults, ...overrides }; + + return [ + { + name: "list_launches", + title: "List launches", + description: + "Browse openlaunch tokens with the site's own sorts. Returns launch facts (price, FDV, USD values, volume windows, holders), not scores. " + + "sort=live is the home page's ranking: tokens an outside wallet traded in the last day first, then new, then quiet. " + + "mcap=filtered applies the site's browsing filter; mcap=all lists every valuation.", + inputSchema: { + type: "object", + properties: { + chain: chainProperty, + sort: { + type: "string", + description: "Ranking to use.", + enum: ["live", "new", "mcap", "volume", "gainers", "holders"], + default: "live", + }, + window: { + type: "string", + description: "Volume window for sort=volume.", + enum: ["1h", "24h", "all"], + default: "all", + }, + mcap: { + type: "string", + description: "Market-cap browsing mode: all valuations, or the site's filtered view.", + enum: ["all", "filtered"], + default: "all", + }, + filter: { + type: "string", + description: "Optional launch filter: fee0 (no trading fee), burn (all fees burned), usdg, usdc.", + enum: ["fee0", "burn", "usdg", "usdc"], + }, + launcher: { + type: "string", + description: "Only launches by this wallet address.", + pattern: ADDRESS, + }, + limit: limitProperty(25, 10), + offset: { + type: "integer", + description: "Rows to skip, for paging.", + minimum: 0, + maximum: 10_000, + default: 0, + }, + }, + additionalProperties: false, + }, + annotations: { title: "List launches", ...readOnly }, + run: async (args) => { + const usd = await deps.ethUsd(); + const page = await deps.listLaunchesPage({ + sort: args.sort as LaunchSort, + window: args.window as VolumeWindow, + mcap: args.mcap as McapMode, + filter: (args.filter as LaunchFilter | undefined) ?? null, + chain: (args.chain as ChainKey | undefined) ?? null, + launcher: args.launcher as string | undefined, + limit: args.limit as number, + offset: args.offset as number, + ethUsd: usd, + }); + return { eth_usd: usd, has_more: page.hasMore, launches: page.items }; + }, + }, + + { + name: "get_launch", + title: "Get one launch", + description: + "One launch's full indexed record by chain and token address: on-chain launch facts, pool and fee settings, live price, " + + "market cap, volume and holder count. Returns an error when the token is not an openlaunch launch on that chain.", + inputSchema: { + type: "object", + properties: { chain: { ...chainProperty, description: "Chain the token was launched on." }, token: tokenProperty }, + required: ["chain", "token"], + additionalProperties: false, + }, + annotations: { title: "Get one launch", ...readOnly }, + run: async (args) => { + const usd = await deps.ethUsd(); + const launch = await deps.getLaunch(args.chain as ChainKey, (args.token as string).toLowerCase(), usd); + if (!launch) throw new ToolError(`no launch at ${String(args.token)} on ${String(args.chain)}`); + return { eth_usd: usd, launch }; + }, + }, + + { + name: "get_token_trades", + title: "Get a token's trades", + description: + "The newest indexed swaps for one launch, newest first. Amounts are raw base-unit decimal integer strings, not display " + + "units; scale the quote side by quote_decimals from the response. When the quote's precision is not known yet the " + + "tool returns a retryable 'quote precision pending' error rather than a price derived from a placeholder decimal count.", + inputSchema: { + type: "object", + properties: { + chain: { ...chainProperty, description: "Chain the token was launched on." }, + token: tokenProperty, + limit: limitProperty(50, 20), + }, + required: ["chain", "token"], + additionalProperties: false, + }, + annotations: { title: "Get a token's trades", ...readOnly }, + run: async (args) => { + const chain = args.chain as ChainKey; + const token = (args.token as string).toLowerCase(); + const launch = await deps.getLaunch(chain, token); + if (!launch) throw new ToolError(`no launch at ${token} on ${chain}`); + // quote_decimals is a placeholder for an unlisted quote the site has not identified yet. Deriving prices from + // it can be off by many orders of magnitude; let the caller retry when precision is known instead. + if (!launch.quote_decimals_known) throw new ToolError("quote precision pending for this launch; retry once its quote decimals are known"); + return { + chain, + token, + quote_decimals: launch.quote_decimals, + trades: await deps.getSwaps(chain, token, launch.quote_decimals, args.limit as number), + }; + }, + }, + + { + name: "get_token_holders", + title: "Get token holders", + description: + "Holder distribution and trust facts for one launch: top holders, top-10 share, pool share, creator bought/sold, " + + "launch-window snipers, and the panel's plain-language notes. Facts only; there is no score. While the transfer " + + "history is still indexing the result has synced=false and no rankings, shares or trust notes: partial balances " + + "are not a clean bill of health.", + inputSchema: { + type: "object", + properties: { + chain: { ...chainProperty, description: "Chain the token was launched on." }, + token: tokenProperty, + }, + required: ["chain", "token"], + additionalProperties: false, + }, + annotations: { title: "Get token holders", ...readOnly }, + run: async (args) => { + const chain = args.chain as ChainKey; + const token = (args.token as string).toLowerCase(); + const panel = await deps.getHolderPanel(chain, token); + if (!panel) throw new ToolError(`holder data is unavailable for ${token} on ${chain}`); + // The token page waits for the same check before showing concentration or trust judgments. An unsynced panel + // carries partial balances, so returning "0 holders, no red flags" would present an index gap as a fact. + if (!holderFactsAvailable(panel)) { + return { + chain, + token, + synced: false, + indexing: "transfer history is still being indexed; holder rankings and trust facts are not ready yet", + holders: null, + }; + } + return { chain, token, ...panel }; + }, + }, + + { + name: "search_launches", + title: "Search launches", + description: "Search launches by name or symbol substring, or an exact token address. Relevance first, then newest or most-held.", + inputSchema: { + type: "object", + properties: { + query: { type: "string", description: "Name, symbol, or exact token address.", minLength: 1, maxLength: 80 }, + chain: chainProperty, + order: { + type: "string", + description: "Tie-break order: newest first, or most-held first.", + enum: ["newest", "holders"], + default: "newest", + }, + limit: limitProperty(25, 10), + }, + required: ["query"], + additionalProperties: false, + }, + annotations: { title: "Search launches", ...readOnly }, + run: async (args) => { + const usd = await deps.ethUsd(); + const launches = await deps.searchLaunches(args.query as string, { + chain: (args.chain as ChainKey | undefined) ?? null, + limit: args.limit as number, + ethUsd: usd, + order: args.order as "newest" | "holders", + }); + return { query: args.query, eth_usd: usd, launches }; + }, + }, + + { + name: "get_recent_activity", + title: "Get recent activity", + description: "The newest launches and swaps across every chain, merged newest first, in the shape the home page's live tape uses.", + inputSchema: { + type: "object", + properties: { limit: limitProperty(50, 20) }, + additionalProperties: false, + }, + annotations: { title: "Get recent activity", ...readOnly }, + run: async (args) => { + const usd = await deps.ethUsd(); + return { eth_usd: usd, activity: await deps.getLaunchFeed(args.limit as number, usd) }; + }, + }, + + { + name: "list_posts", + title: "List community posts", + description: + "Wallet-signed community posts. scope=feed returns the newest top-level posts across the site; scope=token returns one token's " + + "posts with a nextCursor. Hidden posts are never returned; reported posts stay visible until auto-hide marks them hidden.", + inputSchema: { + type: "object", + properties: { + scope: { type: "string", description: "The site-wide feed, or one token's thread.", enum: ["feed", "token"], default: "feed" }, + chain: { ...chainProperty, description: "Required for scope=token: the token's chain." }, + token: { ...tokenProperty, description: "Required for scope=token: the token address." }, + limit: limitProperty(50, 20), + before_id: { + type: "integer", + description: "scope=token only: return posts older than this post id (the previous response's nextCursor).", + minimum: 1, + }, + }, + additionalProperties: false, + }, + annotations: { title: "List community posts", ...readOnly }, + run: async (args) => { + const limit = args.limit as number; + if (args.scope === "token") { + if (typeof args.chain !== "string" || typeof args.token !== "string") { + throw new ToolError("scope=token needs both chain and token"); + } + const result = await deps.listTokenPosts(args.chain as ChainKey, args.token.toLowerCase(), limit, (args.before_id as number | undefined) ?? null); + return { scope: "token", chain: args.chain, token: args.token.toLowerCase(), ...result }; + } + return { scope: "feed", posts: await deps.listFeed(limit, 0) }; + }, + }, + + { + name: "list_community_pairs", + title: "List community pairs", + description: + "Community tokens the site badges and prices in USD. Returns the pair's record and price source. Listing is not an endorsement; " + + "suspended and delisted pairs are excluded.", + inputSchema: { + type: "object", + properties: { chain: chainProperty }, + additionalProperties: false, + }, + annotations: { title: "List community pairs", ...readOnly }, + run: async (args) => { + const chain = args.chain as ChainKey | undefined; + const pairs = (await deps.loadPairs()).filter((pair) => pair.status === "listed" && (!chain || pair.chain === chain)); + return { count: pairs.length, pairs }; + }, + }, + + { + name: "get_points_leaderboard", + title: "Get the points leaderboard", + description: + "The public season's creator or scout board. Points are computed hourly from chain activity; the response includes the season's " + + "dates, whether the board is final, and each wallet's short reason. Returns season=null before a season is public.", + inputSchema: { + type: "object", + properties: { + board: { type: "string", description: "creator or scout.", enum: ["creator", "scout"], default: "creator" }, + limit: limitProperty(100, 25), + }, + additionalProperties: false, + }, + annotations: { title: "Get the points leaderboard", ...readOnly }, + run: async (args) => { + const season = await deps.publicSeason(); + if (!season) return { season: null, board: args.board, rows: [], names: {} }; + const board = args.board as "creator" | "scout"; + const data = await deps.boardRows(season.id, board, args.limit as number); + return { season, board, ...data }; + }, + }, + + { + name: "get_protocol_totals", + title: "Get protocol totals", + description: + "The site's all-time totals: launches, trades, USD volume, fees paid to creators, fees burned, and per-chain counts. " + + "Trades and fees with a stored USD value are valued at their own hour; missing values, including community-pair trades, " + + "are valued at the quote's current price. usd_partial is true only when a quote that normally prices has no price right " + + "now, so the USD sums undercount; quotes with no price source (such as unlisted tokens) are left out without setting " + + "usd_partial and are never guessed.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + annotations: { title: "Get protocol totals", ...readOnly }, + run: async () => { + const usd = await deps.ethUsd(); + return { eth_usd: usd, totals: await deps.getLaunchTotals(usd) }; + }, + }, + ]; +} diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 00000000..234ebb55 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,203 @@ +# MCP server + +openlaunch serves a small, read-only Model Context Protocol (MCP) server over HTTP at + +``` +https://openlaunch.lol/api/mcp +``` + +It exists for the same reason `/llms.txt` and the JSON API do: the interface is optional. An MCP client can read +launch facts, trades, holders, posts, community pairs, the points board and protocol totals without scraping the +site. No API key, no account, no session, and no write path. + +The server is stateless. It answers one JSON-RPC 2.0 message per POST with a JSON response (a client using +`2025-03-26` may send one batch instead), never opens an SSE stream, and never sends +server-to-client requests. That is a valid MCP Streamable HTTP transport: the spec allows a server to answer with +`application/json` instead of `text/event-stream`. The older `2024-11-05` remote transport is not served: it needs a +GET/SSE handshake to discover the POST URL, while this endpoint only answers POST, so that version is not advertised +and its version header is rejected. + +## Connect + +Most clients take a small JSON block: + +```json +{ + "mcpServers": { + "openlaunch": { + "type": "http", + "url": "https://openlaunch.lol/api/mcp" + } + } +} +``` + +Claude Code, for example: + +```sh +claude mcp add --transport http openlaunch https://openlaunch.lol/api/mcp +``` + +For a raw check, initialize the session and list the tools: + +```sh +curl -s https://openlaunch.lol/api/mcp \ + -H 'content-type: application/json' \ + -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' + +curl -s https://openlaunch.lol/api/mcp \ + -H 'content-type: application/json' \ + -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' +``` + +The server is stateless, so the `Mcp-Session-Id` header is neither issued nor required. + +## Protocol + +- JSON-RPC 2.0. One message per POST, or one batch of up to 20 messages for `2025-03-26`. + MCP `2025-06-18` removed batching, so a batch carrying that version header is rejected. When the header is + absent the transport assumes `2025-03-26`, as the specification's compatibility rule says, and accepts a batch. +- Supported protocol versions: `2025-06-18` (latest) and `2025-03-26`. `initialize` echoes a version it + speaks and otherwise offers `2025-06-18`. After initialization, clients send `MCP-Protocol-Version`; an unknown + value gets HTTP `400`. +- Methods: `initialize`, `ping`, `tools/list`, `tools/call`. A notification (a message without `id`) gets HTTP + `202` and no body; unknown notifications are ignored, as JSON-RPC requires. +- A tool that rejects its arguments, or cannot find the requested record, returns a normal JSON-RPC result with + `isError: true` and a plain-text explanation. The client's model can correct itself and retry. Protocol-level + faults (unknown method, malformed envelope) are JSON-RPC errors. +- Tool results are `content: [{type: "text", text: ""}]`. No `outputSchema` is advertised, so no + `structuredContent` is promised. +- No resources, prompts, sampling, elicitation, logging or completions. Only tools. + +## Tools + +All tools are read-only (`readOnlyHint: true`) and call the same server-side read model as the site. Arguments with +a default can be omitted. Unknown arguments are rejected. + +### `list_launches` + +Browse launches with the site's own sorts. + +| argument | type | default | notes | +| --- | --- | --- | --- | +| `chain` | string | all | `base`, `robinhood`, `arc`, `elysium` | +| `sort` | string | `live` | `live`, `new`, `mcap`, `volume`, `gainers`, `holders` | +| `window` | string | `all` | `1h`, `24h`, `all` (for `sort=volume`) | +| `mcap` | string | `all` | `all`, or `filtered` for the site's browsing filter | +| `filter` | string | — | `fee0`, `burn`, `usdg`, `usdc` | +| `launcher` | address | — | one wallet's launches | +| `limit` | integer | `10` | 1–25 | +| `offset` | integer | `0` | 0–10000 | + +Returns `{eth_usd, has_more, launches}`. Rows are the JSON API's launch rows: price, FDV, USD values, volume +windows, holder counts and the market-cap classification facts. + +### `get_launch` + +`{chain, token}` → `{eth_usd, launch}`. The full indexed record for one launch. Errors with `isError` when the +address is not an openlaunch launch on that chain. + +### `search_launches` + +`{query, chain?, order?, limit?}` → `{query, eth_usd, launches}`. + +- `query`: name or symbol substring, or an exact token address (1–80 characters). +- `order`: `newest` (default) or `holders`. +- `limit`: 1–25, default 10. + +### `get_token_trades` + +`{chain, token, limit?}` → `{chain, token, quote_decimals, trades}`. Newest swaps first. `limit` 1–50, default 20. +`amount0` and `amount1` are raw base-unit decimal integer strings, not display units; scale the quote side by +`quote_decimals` from the response (and the token side by the token's own decimals). `price_quote` is in whole quote +units per token. If the quote's precision is not known yet (`quote_decimals_known` is false on the launch row), the +tool returns a retryable `isError` result saying "quote precision pending" instead of deriving a price from the +placeholder decimal count. + +### `get_token_holders` + +`{chain, token}` → holder distribution and trust facts: top holders, top-10 share, pool share, creator bought/sold, +launch-window snipers, and the panel's plain-language notes. Facts only; there is no score. While the transfer +history is indexing the result is `{chain, token, synced: false, indexing: "…", holders: null}` with the rankings, +shares and trust notes omitted: partial balances are not a clean bill of health. The token page uses the same +`holderFactsAvailable` check. + +### `get_recent_activity` + +`{limit?}` → `{eth_usd, activity}`. Newest launches and swaps across chains, merged newest first (the home page's +live tape shape). `limit` 1–50, default 20. + +### `list_posts` + +`{scope?, chain?, token?, limit?, before_id?}`. + +- `scope=feed` (default): newest top-level community posts across the site. +- `scope=token`: one token's posts; requires `chain` and `token`; returns a `nextCursor` for older pages. +- `limit` 1–50, default 20. + +Hidden posts are never returned. Reported posts stay visible until auto-hide marks them hidden. + +### `list_community_pairs` + +`{chain?}` → `{count, pairs}`. Listed community tokens only; suspended and delisted pairs are excluded. A listing +is not an endorsement. + +### `get_points_leaderboard` + +`{board?, limit?}` → `{season, board, rows, names}`. + +- `board`: `creator` (default) or `scout`. +- `limit`: 1–100, default 25. +- `season` is `null` before a season is public. + +Points are computed hourly from chain activity; the public season row says whether the board is final. + +### `get_protocol_totals` + +`{}` → `{eth_usd, totals}`. All-time launches, trades, USD volume, fees paid to creators, fees burned, and per-chain +counts. + +USD sums use each trade's or fee's stored trade-hour value. Missing values, including community-pair trades, stock +trades before price history began, and hours the indexer could not price yet, are valued at the quote's current price, +so a total can mix historical trade-hour values with current-price fallbacks. `usd_partial` is `true` only when a quote +that normally has a price has none right now, so the USD sums undercount. A quote with no USD price source (such as an +unlisted token) is left out of the USD sums without setting `usd_partial`, and is never guessed. + +## Data semantics + +The same caveats as the JSON API apply: + +- The chain is the source of truth; these tables are an index. Indexing lags by a few blocks, and a very new launch + may not be visible yet. `POST /api/launch/sync?chain=…&tx=…` asks the site to index a transaction immediately. +- USD figures in launch rows (`volume_usd`, `price_usd`, `fdv_usd`) are display-unit numbers. `supply`, + `volume_quote`, `fees_quote_collected`, `fees_quote_burned`, `fees_token_collected` and `fees_token_burned` are + raw base-unit strings: scale supply and token-side fees by the launched token's 18 decimals and quote-side amounts + by `quote_decimals`. Swap amounts from `get_token_trades` are raw base-unit strings too; use `quote_decimals` from + that response (or the launch row) for quote amounts, not a blanket 18, and only when `quote_decimals_known` is true. +- USD figures can be `null` or partial when the price feed is down; `usd_partial` marks a total that undercounts + because a normally-priced quote is unavailable right now. Quotes with no USD price source are left out of USD totals. +- There are no platform fees, no owner, and no write tools. A read-only MCP server cannot launch, trade or sign. + +## Limits and security + +- 120 requests per IP per minute, shared by the endpoint. A `429` carries `retry-after: 60`. +- 64 KB request body. +- `content-type: application/json` required. +- Browser requests with an `Origin` header are allowed only from `openlaunch.lol`, `www.openlaunch.lol`, and in + development from localhost. Non-browser MCP clients send no `Origin` and are allowed. This is the MCP + specification's DNS-rebinding guidance; it is not authentication. +- No CORS headers are served. The endpoint is public and read-only, but a browser page on another origin cannot use + a visitor's browser as a proxy to it. +- The endpoint is stateless: no cookies, no session, no per-user data. + +## Code + +- `app/src/lib/mcp/protocol.ts` — versions, JSON-RPC envelopes, error codes. +- `app/src/lib/mcp/schema.ts` — the tiny JSON Schema subset and its validator. +- `app/src/lib/mcp/server.ts` — transport-independent dispatcher (`initialize`, `ping`, `tools/list`, `tools/call`). +- `app/src/lib/mcp/tools.ts` — the ten tools and their dependency-injected read functions. +- `app/src/lib/mcp/origin.ts` — the browser-origin policy. +- `app/src/app/api/mcp/route.ts` — the HTTP transport, rate limit and headers. + +Run the tests with `cd app && npm test` (the MCP cases are `src/lib/mcp/*.test.ts` and +`src/app/api/mcp/route.test.ts`).