Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions app/src/app/agents/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -107,6 +108,17 @@ export default function AgentsPage() {
</div>
</section>

<section id="mcp" tabIndex={-1} className={`${shell.anchorSection} ${styles.section}`} aria-labelledby="agents-mcp-title">
<div className={styles.sectionHeading}><span className={styles.sectionIcon} aria-hidden="true"><Braces size={17} /></span><div><h2 id="agents-mcp-title">MCP for agents</h2><p>Tool calls over one POST. Read-only.</p></div></div>
<p className={styles.prose}>The site serves a stateless Model Context Protocol (MCP) endpoint at <code>{SITE_URL}/api/mcp</code>. 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.</p>
<AgentsCodeBlock title="MCP client configuration" language="JSON" code={`{\n "mcpServers": {\n "openlaunch": {\n "type": "http",\n "url": "${SITE_URL}/api/mcp"\n }\n }\n}`} />
<AgentsCodeBlock title="One tool call" language="HTTP reference" code={`POST ${SITE_URL}/api/mcp\nContent-Type: application/json\n\n{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_launches","arguments":{"chain":"base","limit":3}}}`} />
<div className={styles.dataNote}>
<p>Ten read-only tools: <code>list_launches</code>, <code>get_launch</code>, <code>search_launches</code>, <code>get_token_trades</code>, <code>get_token_holders</code>, <code>get_recent_activity</code>, <code>list_posts</code>, <code>list_community_pairs</code>, <code>get_points_leaderboard</code>, <code>get_protocol_totals</code>. <code>initialize</code>, <code>ping</code> and <code>tools/list</code> implement the protocol. Amounts and USD caveats are the same as the JSON API.</p>
<p>Limits: 120 requests per IP per minute, 64 KB per request, and browser origins are checked. Full reference: <a href={`${BRAND_GITHUB}/blob/main/docs/mcp.md`} target="_blank" rel="noreferrer">docs/mcp.md<ArrowUpRight size={13} aria-hidden="true" /></a>.</p>
</div>
</section>

<section id="trade" tabIndex={-1} className={`${shell.anchorSection} ${styles.section}`} aria-labelledby="agents-trade-title">
<div className={styles.sectionHeading}><span className={styles.sectionIcon} aria-hidden="true"><ArrowLeftRight size={17} /></span><div><h2 id="agents-trade-title">Trade & collect</h2><p>Standard pools. Direct contract calls.</p></div></div>
<div className={styles.tradeReference}>
Expand Down
151 changes: 151 additions & 0 deletions app/src/app/api/mcp/route.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}, 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<Record<string, unknown>> } };
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);
});
132 changes: 132 additions & 0 deletions app/src/app/api/mcp/route.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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" } });
}
7 changes: 7 additions & 0 deletions app/src/app/llms.txt/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>/<address> (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
Expand Down
Loading
Loading