Repository navigation
feat(mcp): add a read-only MCP server for agents #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ayush7614
wants to merge
5
commits into
Twigpine:main
Choose a base branch
from
Ayush7614:feat/mcp-server
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
7f2a7ca
feat(mcp): serve a read-only MCP endpoint for agents
Ayush7614 26e4442
docs(mcp): avoid linking an external protocol host
Ayush7614 a2903f8
fix(mcp): honor negotiated versions and correct tool docs
Ayush7614 8fbaee3
docs(mcp): describe protocol totals valuation accurately
Ayush7614 1c4971c
fix(mcp): gate priced trades and holder facts, drop legacy transport …
Ayush7614 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| // 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" } }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.