@basedloans/mcp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Based Loans
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @basedloans/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP server for [Based Loans](https://based.loans) on Base: market data, token risk reports, exact loan quotes, positions, and unsigned borrow and lend transactions. Holds no keys.
4
+
5
+ ## Use it
6
+
7
+ Claude Desktop, Cursor and other MCP clients:
8
+
9
+ ```json
10
+ {
11
+ "mcpServers": {
12
+ "basedloans": {
13
+ "command": "npx",
14
+ "args": ["-y", "@basedloans/mcp"],
15
+ "env": { "BASE_RPC_URL": "https://your-base-rpc" }
16
+ }
17
+ }
18
+ }
19
+ ```
20
+
21
+ Hosted (Streamable HTTP): `https://mcp.based.loans/mcp`
22
+
23
+ ## Tools
24
+
25
+ Read: `get_protocol_info`, `list_markets`, `get_market`, `get_risk_report`, `quote_borrow`, `get_loan`, `get_borrower_loans`, `get_lender_position`, `request_token_listing`, `explain_collateral_types`, `simulate_transaction`.
26
+
27
+ Prepare (return unsigned transactions): `build_borrow`, `build_buyback`, `build_deposit`, `build_set_limits`, `build_withdraw`, `build_claim_proceeds`, `build_claim_collateral`, `build_set_auto_redeploy`.
28
+
29
+ Every tool is annotated read-only: none of them change anything on-chain. The prepare tools return transactions for the user's wallet to sign.
30
+
31
+ ## Environment
32
+
33
+ | Variable | Meaning |
34
+ |---|---|
35
+ | `BASE_RPC_URL` | Base RPC (defaults to the public endpoint, which is rate-limited) |
36
+ | `BASEDLOANS_READ_ONLY=1` | Hide the prepare tools |
37
+ | `BASEDLOANS_BUILDER_CODE` | Base Builder Code appended to every prepared transaction (ERC-8021). Empty string disables it |
38
+ | `BASEDLOANS_DATA_SUFFIX` | Raw hex suffix instead of a builder code |
39
+ | `PORT`, `RATE_PER_MINUTE` | HTTP mode only |
40
+
41
+ ## HTTP mode
42
+
43
+ `node dist/http.js` serves MCP at `/mcp` and a GET API at `/v1` (see `GET /v1`). `/v1/tx/*` endpoints return calls in the `send_calls` shape. The same handler is exported as `@basedloans/mcp/fetch` for web-standard runtimes; see [`deploy/vercel`](deploy/vercel/README.md).
@@ -0,0 +1,189 @@
1
+ import {
2
+ COLLATERAL_TYPES_GUIDE,
3
+ createServer
4
+ } from "./chunk-WAPVXQ4B.js";
5
+
6
+ // src/fetch.ts
7
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
8
+ import { BasedLoansError, createBasedLoans, explainError } from "@basedloans/sdk";
9
+ import { getAddress, isAddress } from "viem";
10
+ function optionsFromEnv(env = process.env) {
11
+ return {
12
+ rpcUrl: env.BASE_RPC_URL || void 0,
13
+ dataSuffix: env.BASEDLOANS_DATA_SUFFIX || void 0,
14
+ ...env.BASEDLOANS_BUILDER_CODE !== void 0 ? { builderCode: env.BASEDLOANS_BUILDER_CODE || null } : {},
15
+ readOnly: env.BASEDLOANS_READ_ONLY === "1"
16
+ };
17
+ }
18
+ var CORS = {
19
+ "access-control-allow-origin": "*",
20
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
21
+ "access-control-allow-headers": "content-type, mcp-session-id, mcp-protocol-version",
22
+ "access-control-expose-headers": "mcp-session-id"
23
+ };
24
+ var json = (status, body) => new Response(JSON.stringify(body, (_k, v) => typeof v === "bigint" ? v.toString() : v, 2), {
25
+ status,
26
+ headers: { "content-type": "application/json", "cache-control": "no-store", ...CORS }
27
+ });
28
+ function createFetchHandler(opts = optionsFromEnv()) {
29
+ const bl = createBasedLoans(opts);
30
+ const RATE = Number(process.env.RATE_PER_MINUTE ?? 60);
31
+ const hits = /* @__PURE__ */ new Map();
32
+ const limited = (ip) => {
33
+ const now = Date.now();
34
+ const h = hits.get(ip);
35
+ if (!h || now - h.t > 6e4) {
36
+ hits.set(ip, { n: 1, t: now });
37
+ if (hits.size > 1e4) hits.clear();
38
+ return false;
39
+ }
40
+ return ++h.n > RATE;
41
+ };
42
+ const asCalls = (plan) => ({
43
+ chainId: bl.ctx.chainId,
44
+ summary: plan.summary,
45
+ warnings: plan.warnings,
46
+ // send_calls shape: run in order, approval first when present.
47
+ calls: plan.steps.map((s) => ({ to: s.to, data: s.data, value: `0x${BigInt(s.value).toString(16)}`, description: s.description }))
48
+ });
49
+ const addr = (v, name) => {
50
+ if (!v || !isAddress(v)) throw new BasedLoansError(`Query parameter ${name} must be a 0x address.`, "INVALID_INPUT");
51
+ return getAddress(v);
52
+ };
53
+ const asset = (v) => {
54
+ if (!v) throw new BasedLoansError("Query parameter asset is required.", "INVALID_INPUT");
55
+ if (isAddress(v)) return getAddress(v);
56
+ const m = [...bl.ctx.assets.values()].filter((a) => a.symbol.toLowerCase() === v.toLowerCase());
57
+ if (m.length === 1) return getAddress(m[0].address);
58
+ throw new BasedLoansError(`Unknown or ambiguous token "${v}". Pass its contract address.`, "UNKNOWN_TOKEN");
59
+ };
60
+ const need = (v, name) => {
61
+ if (!v) throw new BasedLoansError(`Query parameter ${name} is required.`, "INVALID_INPUT");
62
+ return v;
63
+ };
64
+ async function api(url) {
65
+ const q = url.searchParams;
66
+ const p = url.pathname.replace(/\/+$/, "");
67
+ switch (p) {
68
+ case "/v1":
69
+ return {
70
+ name: "Based Loans API",
71
+ docs: "https://based.loans",
72
+ mcp: "/mcp",
73
+ endpoints: [
74
+ "GET /v1/protocol",
75
+ "GET /v1/markets?only_with_funds=true",
76
+ "GET /v1/market?asset=",
77
+ "GET /v1/risk?asset=",
78
+ "GET /v1/quote?asset=&collateral=&term=&loan_usdc=",
79
+ "GET /v1/loans?borrower=",
80
+ "GET /v1/lender?address=",
81
+ "GET /v1/request-token?token=",
82
+ "GET /v1/collateral-types",
83
+ ...opts.readOnly ? [] : [
84
+ "GET /v1/tx/borrow?asset=&collateral=&term=&borrower=&loan_usdc=",
85
+ "GET /v1/tx/buyback?loan_id=&borrower=&payment_usdc=",
86
+ "GET /v1/tx/deposit?amount_usdc=&lender=&limits=ASSET:USDC,ASSET:USDC",
87
+ "GET /v1/tx/limits?lender=&limits=ASSET:USDC,...",
88
+ "GET /v1/tx/withdraw?amount_usdc=|max&lender=&as_musdc=true",
89
+ "GET /v1/tx/claim-proceeds?loan_ids=1,2&mode=withdraw|redeploy",
90
+ "GET /v1/tx/claim-collateral?loan_ids=1,2"
91
+ ]
92
+ ]
93
+ };
94
+ case "/v1/protocol":
95
+ return bl.getProtocolParams();
96
+ case "/v1/markets":
97
+ return bl.listMarkets({ onlyWithFunds: q.get("only_with_funds") === "true" });
98
+ case "/v1/market":
99
+ return await bl.getMarket(asset(q.get("asset"))) ?? { notListed: true };
100
+ case "/v1/risk":
101
+ return await bl.getRiskReport(asset(q.get("asset")), { skipDepth: q.get("skip_depth") === "true" }) ?? { notListed: true };
102
+ case "/v1/quote":
103
+ return bl.quoteBorrow({
104
+ asset: asset(q.get("asset")),
105
+ collateralAmount: need(q.get("collateral"), "collateral"),
106
+ loanAmountUsdc: q.get("loan_usdc") ?? void 0,
107
+ term: need(q.get("term"), "term")
108
+ });
109
+ case "/v1/loans":
110
+ return bl.getBorrowerLoans(addr(q.get("borrower"), "borrower"));
111
+ case "/v1/lender":
112
+ return bl.getLenderPosition(addr(q.get("address"), "address"));
113
+ case "/v1/request-token":
114
+ return bl.requestTokenListing(need(q.get("token"), "token"));
115
+ case "/v1/collateral-types":
116
+ return { guide: COLLATERAL_TYPES_GUIDE };
117
+ }
118
+ if (opts.readOnly) throw new BasedLoansError("Not found.", "NOT_FOUND");
119
+ const limits = (s) => (s ?? "").split(",").filter(Boolean).map((pair) => {
120
+ const [a, l] = pair.split(":");
121
+ return { asset: asset(a ?? null), limitUsdc: need(l ?? null, "limit") };
122
+ });
123
+ const ids = (s) => need(s, "loan_ids").split(",").filter(Boolean);
124
+ switch (p) {
125
+ case "/v1/tx/borrow":
126
+ return asCalls(
127
+ await bl.buildBorrow({
128
+ asset: asset(q.get("asset")),
129
+ collateralAmount: need(q.get("collateral"), "collateral"),
130
+ loanAmountUsdc: q.get("loan_usdc") ?? void 0,
131
+ term: need(q.get("term"), "term"),
132
+ borrower: addr(q.get("borrower"), "borrower")
133
+ })
134
+ );
135
+ case "/v1/tx/buyback":
136
+ return asCalls(
137
+ await bl.buildBuyback({ loanId: need(q.get("loan_id"), "loan_id"), paymentUsdc: q.get("payment_usdc") ?? void 0, borrower: addr(q.get("borrower"), "borrower") })
138
+ );
139
+ case "/v1/tx/deposit": {
140
+ const l = limits(q.get("limits"));
141
+ return asCalls(await bl.buildDeposit({ amountUsdc: need(q.get("amount_usdc"), "amount_usdc"), lender: addr(q.get("lender"), "lender"), limits: l.length ? l : void 0 }));
142
+ }
143
+ case "/v1/tx/limits":
144
+ return asCalls(await bl.buildSetLimits({ limits: limits(q.get("limits")), lender: addr(q.get("lender"), "lender") }));
145
+ case "/v1/tx/withdraw": {
146
+ const amt = need(q.get("amount_usdc"), "amount_usdc");
147
+ return asCalls(await bl.buildWithdraw({ amountUsdc: amt === "max" ? "max" : amt, lender: addr(q.get("lender"), "lender"), asMusdc: q.get("as_musdc") === "true" }));
148
+ }
149
+ case "/v1/tx/claim-proceeds":
150
+ return asCalls(await bl.buildClaimProceeds({ loanIds: ids(q.get("loan_ids")), mode: q.get("mode") === "redeploy" ? "redeploy" : "withdraw" }));
151
+ case "/v1/tx/claim-collateral":
152
+ return asCalls(await bl.buildClaimCollateral({ loanIds: ids(q.get("loan_ids")) }));
153
+ }
154
+ throw new BasedLoansError("Not found. GET /v1 lists the endpoints.", "NOT_FOUND");
155
+ }
156
+ return async function handle(request, clientIp = "?") {
157
+ const url = new URL(request.url);
158
+ try {
159
+ if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: CORS });
160
+ if (url.pathname === "/health") return json(200, { ok: true });
161
+ const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || clientIp;
162
+ if (limited(ip)) return json(429, { error: "Too many requests. Slow down and retry in a minute." });
163
+ if (url.pathname === "/mcp") {
164
+ if (Number(request.headers.get("content-length") ?? 0) > 1e6) return json(413, { error: "Request too large." });
165
+ const server = createServer(opts);
166
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: void 0, enableJsonResponse: true });
167
+ await server.connect(transport);
168
+ const res = await transport.handleRequest(request);
169
+ const headers = new Headers(res.headers);
170
+ for (const [k, v] of Object.entries(CORS)) headers.set(k, v);
171
+ return new Response(res.body, { status: res.status, headers });
172
+ }
173
+ if (request.method === "GET" && url.pathname.startsWith("/v1")) return json(200, await api(url));
174
+ if (url.pathname === "/" || url.pathname === "") {
175
+ return json(200, { name: "Based Loans agent server", mcp: `${url.origin}/mcp`, api: `${url.origin}/v1`, docs: "https://based.loans" });
176
+ }
177
+ return json(404, { error: "Not found. MCP is at /mcp, the HTTP API at /v1." });
178
+ } catch (e) {
179
+ const status = e instanceof BasedLoansError ? e.code === "NOT_FOUND" ? 404 : e.code === "RPC_ERROR" ? 503 : 400 : 400;
180
+ const message = e instanceof BasedLoansError ? e.message : explainError(e).message;
181
+ return json(status, { error: message, code: e instanceof BasedLoansError ? e.code : "ERROR" });
182
+ }
183
+ };
184
+ }
185
+
186
+ export {
187
+ optionsFromEnv,
188
+ createFetchHandler
189
+ };
@@ -0,0 +1,299 @@
1
+ // src/server.ts
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import {
4
+ BasedLoansError,
5
+ createBasedLoans,
6
+ explainError
7
+ } from "@basedloans/sdk";
8
+ import { getAddress, isAddress } from "viem";
9
+ import { z } from "zod";
10
+
11
+ // src/text.ts
12
+ var SERVER_INSTRUCTIONS = (readOnly) => `Based Loans is a fixed-term lending protocol on Base with no liquidations. A borrower deposits a token as collateral and receives USDC right away. They can buy the collateral back at a fixed price any time before the due date. If they do not, they keep the USDC and the lenders who funded the loan receive the collateral instead. Prices can move as much as they like during the loan; nothing is ever sold off early.
13
+
14
+ Lenders deposit USDC and choose which tokens they are willing to lend against, with a USDC limit per token. No lender is exposed to a token they did not choose.
15
+
16
+ How to help a user:
17
+ - To borrow: get_market or list_markets, then quote_borrow, then ${readOnly ? "send them to https://based.loans/borrow" : "build_borrow"}. Always show the buyback cost and due date before they commit.
18
+ - To lend: get_risk_report for every token they are considering, explain the flags in plain words, then ${readOnly ? "send them to https://based.loans/lend" : "build_deposit with limits"}.
19
+ - To see positions: get_borrower_loans or get_lender_position.
20
+ - If a token is not supported: request_token_listing returns a link for the user to submit. Never claim a request was submitted.
21
+ ${readOnly ? "" : "\nTransaction tools return unsigned transactions in order (approval first when needed). This server never holds keys and never sends anything. The user's wallet signs each step. You can dry-run a step with simulate_transaction.\n"}
22
+ All amounts are decimal strings in token units (USDC has 6 decimals). Every number is read live from Base mainnet. Risk reports describe the data; they are not advice.`;
23
+ var COLLATERAL_TYPES_GUIDE = `# How Based Loans prices collateral
24
+
25
+ Every loan is sized from the token's price at the moment the loan opens. The price is the lowest of the token's working price sources, and the loan is a share of that value (the max loan-to-value, usually 50%). Price sources are time-weighted averages from DEX pools (usually over 30 minutes) and, for some tokens, DIA price data. Tokens with two or more sources only open loans when the sources agree within a set range.
26
+
27
+ There are four kinds of collateral. get_market and get_risk_report return which kind a token is as pricingType.
28
+
29
+ ## 1. Regular tokens (market)
30
+ Priced straight from a DEX pool against USDC or WETH, sometimes with DIA as a second check.
31
+ Examples: WETH, cbBTC, cbETH, VIRTUAL, AERO.
32
+ What to know: the deeper the pool, the harder the price is to move. Tokens with only one pool and no second source have nothing double-checking their price.
33
+
34
+ ## 2. Two-hop tokens (market_two_hop)
35
+ The token's main pool is against another token, so the price goes through that token first. For example MONSTRO trades against ALB, so MONSTRO is priced as MONSTRO in ALB, then ALB in WETH.
36
+ Examples: MONSTRO, PLAZM, DUB.
37
+ What to know: the price depends on both pools. A thin second pool matters as much as a thin first one. get_risk_report measures both.
38
+
39
+ ## 3. Staked and share tokens (derived_live_ratio)
40
+ Tokens that represent a claim on another token, like a staked or liquid-staking token or a vault share. Priced as the base token's price times the exchange rate the token's own contract reports, read live.
41
+ Examples: xMONSTRO (priced from MONSTRO times its redemption rate), xl-LSTEAK (priced from LSTEAK times its exchange rate).
42
+ What to know: the risk is mostly the base token's risk, plus trust in the contract reporting the rate. If a lender ends up holding one, they may need to redeem it through its own contract, which can have fees or delays, before they have the base token.
43
+
44
+ ## 4. Escrowed and locked tokens (derived_fixed_ratio)
45
+ Tokens that convert into a liquid token over time, like escrowed rewards that vest. Priced as the liquid token's price times a fixed discount set by governance.
46
+ Example: esALB is priced at 85% of ALB, because it has to vest before it becomes ALB.
47
+ What to know: the discount does not move with the market. If the real discount widens, the protocol's price stays the same until governance updates it. A lender who ends up holding an escrowed token may have to wait for it to vest before they can sell it.
48
+
49
+ ## For borrowers
50
+ You never get liquidated. Whatever the token does during the loan, you can buy your collateral back for the fixed buyback cost before the due date, or walk away and keep the USDC.
51
+
52
+ ## For lenders
53
+ You only lend against tokens you pick, up to the limits you set. If a borrower walks away, you receive your share of their collateral. Before adding a token, check get_risk_report: how many price sources it has, how deep its pools are, and what kind of collateral it is.`;
54
+
55
+ // src/server.ts
56
+ var SERVER_NAME = "basedloans";
57
+ var SERVER_VERSION = "0.1.1";
58
+ var address = z.string().regex(/^0x[0-9a-fA-F]{40}$/, "a 0x-prefixed 20-byte address");
59
+ var assetRef = z.string().min(1).describe("Token contract address on Base (preferred) or its symbol, e.g. WETH, VIRTUAL, esALB");
60
+ var amount = z.string().regex(/^\d+(\.\d+)?$/, "a plain decimal like 12.5");
61
+ var term = z.union([z.enum(["short", "medium", "long"]), z.number().int().min(0).max(2)]).describe("Loan term: short, medium or long (or 0/1/2). Durations and costs come from get_protocol_info.");
62
+ var loanId = z.union([z.string().regex(/^\d+$/), z.number().int().nonnegative()]).describe("Loan ID");
63
+ var json = (v) => JSON.stringify(v, (_k, x) => typeof x === "bigint" ? x.toString() : x, 2);
64
+ function ok(result) {
65
+ return { content: [{ type: "text", text: json(result) }] };
66
+ }
67
+ function fail(e) {
68
+ const message = e instanceof BasedLoansError ? e.message : e instanceof Error && !("walk" in e) ? e.message : explainError(e).message;
69
+ return { isError: true, content: [{ type: "text", text: message }] };
70
+ }
71
+ function resolveAsset(bl, ref) {
72
+ if (isAddress(ref)) return getAddress(ref);
73
+ const want = ref.trim().toLowerCase();
74
+ const matches = [...bl.ctx.assets.values()].filter((a) => a.symbol.toLowerCase() === want);
75
+ if (matches.length === 1) return getAddress(matches[0].address);
76
+ if (matches.length > 1) {
77
+ throw new BasedLoansError(`More than one token is called ${ref}. Pass the contract address instead: ${matches.map((m) => m.address).join(", ")}`, "AMBIGUOUS");
78
+ }
79
+ throw new BasedLoansError(`No known token called "${ref}". Pass its contract address, or use request_token_listing.`, "UNKNOWN_TOKEN");
80
+ }
81
+ var READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
82
+ var BUILD = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
83
+ var BUILD_META = { "basedloans/returns": "unsigned_transactions" };
84
+ function createServer(opts = {}) {
85
+ const bl = createBasedLoans(opts);
86
+ const server = new McpServer(
87
+ { name: SERVER_NAME, version: SERVER_VERSION, title: "Based Loans" },
88
+ { instructions: SERVER_INSTRUCTIONS(opts.readOnly ?? false) }
89
+ );
90
+ const tool = (name, title, description, shape, annotations, run, meta) => server.registerTool(
91
+ name,
92
+ { title, description, inputSchema: shape, annotations: { title, ...annotations }, ...meta ? { _meta: meta } : {} },
93
+ (async (args) => {
94
+ try {
95
+ return ok(await run(args));
96
+ } catch (e) {
97
+ return fail(e);
98
+ }
99
+ })
100
+ );
101
+ tool(
102
+ "get_protocol_info",
103
+ "Protocol info",
104
+ "Live protocol parameters: loan fee, the three loan terms with their durations and buyback costs, minimum loan and deposit sizes, per-token lending limit bounds, and whether the protocol is paused.",
105
+ {},
106
+ READ,
107
+ () => bl.getProtocolParams()
108
+ );
109
+ tool(
110
+ "list_markets",
111
+ "List collateral tokens",
112
+ "Every token currently accepted as collateral, with price, max loan-to-value, USDC available to borrow against it, active loans, and how it is priced. Set only_with_funds to see only tokens lenders are currently backing.",
113
+ { only_with_funds: z.boolean().optional().describe("Only tokens with USDC available to borrow right now") },
114
+ READ,
115
+ ({ only_with_funds }) => bl.listMarkets({ onlyWithFunds: only_with_funds })
116
+ );
117
+ tool(
118
+ "get_market",
119
+ "Get one collateral token",
120
+ "Price, max loan-to-value, USDC available to borrow, active loans and pricing type for one token.",
121
+ { asset: assetRef },
122
+ READ,
123
+ async ({ asset }) => await bl.getMarket(resolveAsset(bl, asset)) ?? { notListed: true, hint: "Use request_token_listing." }
124
+ );
125
+ tool(
126
+ "get_risk_report",
127
+ "Token risk report",
128
+ "Live risk data for lending against (or borrowing with) a token: how many price sources it has and whether they cross-check each other, how far back its pool price history goes, how much trading it would take to move its pool price 2x and 10x, USDC available to borrow against it, its active loan limit, and plain-language explanations of every flag. Use this before setting a lending limit on a token.",
129
+ { asset: assetRef, skip_depth: z.boolean().optional().describe("Skip the pool depth calculation (faster)") },
130
+ READ,
131
+ async ({ asset, skip_depth }) => await bl.getRiskReport(resolveAsset(bl, asset), { skipDepth: skip_depth }) ?? { notListed: true }
132
+ );
133
+ tool(
134
+ "quote_borrow",
135
+ "Quote a loan",
136
+ "Exact loan quote using the same math the contract runs: USDC you receive after the fee, buyback cost, due date, and how much collateral is used. It replays the lender queue, so the funded amount matches what the loan would really get, and warns (with a suggested amount) when a loan would be funded short.",
137
+ {
138
+ asset: assetRef,
139
+ collateral_amount: amount.describe("Collateral to offer, in token units, e.g. 0.5"),
140
+ loan_amount_usdc: amount.optional().describe("Loan amount before the fee. Omit to borrow the most the collateral allows."),
141
+ term
142
+ },
143
+ READ,
144
+ ({ asset, collateral_amount, loan_amount_usdc, term: t }) => bl.quoteBorrow({ asset: resolveAsset(bl, asset), collateralAmount: collateral_amount, loanAmountUsdc: loan_amount_usdc, term: t })
145
+ );
146
+ tool(
147
+ "get_loan",
148
+ "Get a loan",
149
+ "Status, collateral, buyback cost and remaining amount, due date and lenders for one loan.",
150
+ { loan_id: loanId },
151
+ READ,
152
+ async ({ loan_id }) => await bl.getLoan(loan_id) ?? { notFound: true }
153
+ );
154
+ tool(
155
+ "get_borrower_loans",
156
+ "Borrower's loans",
157
+ "Every loan a wallet has opened, with status (active, partially_repaid, repaid, defaulted), buyback remaining and time until due.",
158
+ { borrower: address },
159
+ READ,
160
+ ({ borrower }) => bl.getBorrowerLoans(getAddress(borrower))
161
+ );
162
+ tool(
163
+ "get_lender_position",
164
+ "Lender position",
165
+ "A lender's deposit, USDC in active loans, USDC available to withdraw, per-token limits, and every loan they funded with any repaid USDC or defaulted collateral they can claim.",
166
+ { lender: address },
167
+ READ,
168
+ ({ lender }) => bl.getLenderPosition(getAddress(lender))
169
+ );
170
+ tool(
171
+ "request_token_listing",
172
+ "Request a new token",
173
+ "Check whether a token is accepted as collateral. If it is not, returns a pre-filled link to the Based Loans request form for the user to open and submit. Nothing is submitted automatically.",
174
+ { token: address.describe("Token contract address on Base") },
175
+ READ,
176
+ ({ token }) => bl.requestTokenListing(token)
177
+ );
178
+ tool(
179
+ "explain_collateral_types",
180
+ "Collateral types explained",
181
+ "How Based Loans prices different kinds of collateral (regular tokens, two-hop priced tokens, staked and share tokens, escrowed tokens), with examples, and what each means for borrowers and lenders.",
182
+ {},
183
+ READ,
184
+ async () => ({ guide: COLLATERAL_TYPES_GUIDE })
185
+ );
186
+ if (opts.readOnly) return server;
187
+ tool(
188
+ "build_borrow",
189
+ "Prepare a loan",
190
+ "Returns the unsigned transactions to open a loan: an approval (only if needed) then openLoan. Includes the quote and warnings. The user's wallet must sign and send each step in order.",
191
+ {
192
+ asset: assetRef,
193
+ collateral_amount: amount,
194
+ loan_amount_usdc: amount.optional(),
195
+ term,
196
+ borrower: address.describe("Wallet that will sign; used to skip unneeded approvals and check balances"),
197
+ max_shortfall_bps: z.number().int().min(0).max(1e4).optional().describe("Max gap between requested and funded amount in basis points. Omit for the protocol default.")
198
+ },
199
+ BUILD,
200
+ ({ asset, collateral_amount, loan_amount_usdc, term: t, borrower, max_shortfall_bps }) => bl.buildBorrow({
201
+ asset: resolveAsset(bl, asset),
202
+ collateralAmount: collateral_amount,
203
+ loanAmountUsdc: loan_amount_usdc,
204
+ term: t,
205
+ borrower: getAddress(borrower),
206
+ maxShortfallBps: max_shortfall_bps
207
+ }),
208
+ BUILD_META
209
+ );
210
+ tool(
211
+ "build_buyback",
212
+ "Prepare a buyback",
213
+ "Returns the unsigned transactions to pay back a loan and get collateral back: a USDC approval (only if needed) then buyback. Omit payment_usdc to pay the full remaining amount.",
214
+ { loan_id: loanId, payment_usdc: amount.optional(), borrower: address },
215
+ BUILD,
216
+ ({ loan_id, payment_usdc, borrower }) => bl.buildBuyback({ loanId: loan_id, paymentUsdc: payment_usdc, borrower: getAddress(borrower) }),
217
+ BUILD_META
218
+ );
219
+ const limits = z.array(z.object({ asset: assetRef, limit_usdc: amount.describe("Max USDC to lend against this token; 0 removes it") })).min(1).max(50);
220
+ tool(
221
+ "build_deposit",
222
+ "Prepare a lending deposit",
223
+ "Returns the unsigned transactions to deposit USDC for lending, optionally setting per-token lending limits in the same transaction (needed before a first deposit can be lent). Check get_risk_report for each token first.",
224
+ { amount_usdc: amount, lender: address, limits: limits.optional() },
225
+ BUILD,
226
+ ({ amount_usdc, lender, limits: l }) => bl.buildDeposit({
227
+ amountUsdc: amount_usdc,
228
+ lender: getAddress(lender),
229
+ limits: l?.map((x) => ({ asset: resolveAsset(bl, x.asset), limitUsdc: x.limit_usdc }))
230
+ }),
231
+ BUILD_META
232
+ );
233
+ tool(
234
+ "build_set_limits",
235
+ "Prepare per-token lending limits",
236
+ "Returns the unsigned transaction to add, change or remove per-token lending limits. A limit cannot be set below what is already in active loans for that token.",
237
+ { limits, lender: address },
238
+ BUILD,
239
+ ({ limits: l, lender }) => bl.buildSetLimits({ limits: l.map((x) => ({ asset: resolveAsset(bl, x.asset), limitUsdc: x.limit_usdc })), lender: getAddress(lender) }),
240
+ BUILD_META
241
+ );
242
+ tool(
243
+ "build_withdraw",
244
+ "Prepare a withdrawal",
245
+ 'Returns the unsigned transaction to withdraw USDC that is not in active loans. Use "max" for everything available. as_musdc receives vault shares and skips the 0.25% withdrawal fee.',
246
+ { amount_usdc: z.union([amount, z.literal("max")]), lender: address, as_musdc: z.boolean().optional() },
247
+ BUILD,
248
+ ({ amount_usdc, lender, as_musdc }) => bl.buildWithdraw({ amountUsdc: amount_usdc, lender: getAddress(lender), asMusdc: as_musdc }),
249
+ BUILD_META
250
+ );
251
+ tool(
252
+ "build_claim_proceeds",
253
+ "Prepare a proceeds claim",
254
+ "Returns the unsigned transaction to claim repaid USDC from loans you funded (mode withdraw) or put it straight back into lending (mode redeploy). Get loan IDs from get_lender_position.",
255
+ { loan_ids: z.array(loanId).min(1).max(50), mode: z.enum(["withdraw", "redeploy"]).optional() },
256
+ BUILD,
257
+ ({ loan_ids, mode }) => bl.buildClaimProceeds({ loanIds: loan_ids, mode }),
258
+ BUILD_META
259
+ );
260
+ tool(
261
+ "build_claim_collateral",
262
+ "Prepare a collateral claim",
263
+ "Returns the unsigned transaction for a lender to claim their share of collateral from loans that passed their due date without a full buyback.",
264
+ { loan_ids: z.array(loanId).min(1).max(50) },
265
+ BUILD,
266
+ ({ loan_ids }) => bl.buildClaimCollateral({ loanIds: loan_ids }),
267
+ BUILD_META
268
+ );
269
+ tool(
270
+ "build_set_auto_redeploy",
271
+ "Prepare auto re-lend setting",
272
+ "Returns the unsigned transaction to turn automatic re-lending of repaid principal on or off.",
273
+ { enabled: z.boolean() },
274
+ BUILD,
275
+ ({ enabled }) => bl.buildSetAutoRedeploy({ enabled }),
276
+ BUILD_META
277
+ );
278
+ tool(
279
+ "simulate_transaction",
280
+ "Simulate a transaction",
281
+ "Dry-runs one prepared transaction from a wallet against the latest block and explains the failure in plain language if it would revert. Steps that depend on an earlier approval only pass after that approval is mined.",
282
+ {
283
+ to: address,
284
+ data: z.string().regex(/^0x[0-9a-fA-F]*$/),
285
+ value: z.string().regex(/^\d+$/).optional(),
286
+ from: address
287
+ },
288
+ READ,
289
+ ({ to, data, value, from }) => bl.simulate({ chainId: bl.ctx.chainId, to: getAddress(to), data, value: value ?? "0", description: "" }, getAddress(from))
290
+ );
291
+ return server;
292
+ }
293
+
294
+ export {
295
+ COLLATERAL_TYPES_GUIDE,
296
+ SERVER_NAME,
297
+ SERVER_VERSION,
298
+ createServer
299
+ };
@@ -0,0 +1,8 @@
1
+ import { ServerOptions } from './server.js';
2
+ import '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import '@basedloans/sdk';
4
+
5
+ declare function optionsFromEnv(env?: Record<string, string | undefined>): ServerOptions;
6
+ declare function createFetchHandler(opts?: ServerOptions): (request: Request, clientIp?: string) => Promise<Response>;
7
+
8
+ export { createFetchHandler, optionsFromEnv };
package/dist/fetch.js ADDED
@@ -0,0 +1,9 @@
1
+ import {
2
+ createFetchHandler,
3
+ optionsFromEnv
4
+ } from "./chunk-KSGJTKAQ.js";
5
+ import "./chunk-WAPVXQ4B.js";
6
+ export {
7
+ createFetchHandler,
8
+ optionsFromEnv
9
+ };
package/dist/http.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/http.js ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ createFetchHandler,
4
+ optionsFromEnv
5
+ } from "./chunk-KSGJTKAQ.js";
6
+ import "./chunk-WAPVXQ4B.js";
7
+
8
+ // src/http.ts
9
+ import { createServer as createHttpServer } from "http";
10
+ import { Readable } from "stream";
11
+ var PORT = Number(process.env.PORT ?? 8787);
12
+ var opts = optionsFromEnv();
13
+ var handle = createFetchHandler(opts);
14
+ var httpServer = createHttpServer(async (req, res) => {
15
+ try {
16
+ const url = `http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
17
+ const headers = new Headers();
18
+ for (const [k, v] of Object.entries(req.headers)) {
19
+ if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
20
+ else if (v != null) headers.set(k, v);
21
+ }
22
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
23
+ const request = new Request(url, {
24
+ method: req.method,
25
+ headers,
26
+ body: hasBody ? Readable.toWeb(req) : void 0,
27
+ // Required by Node's fetch implementation when streaming a request body.
28
+ ...hasBody ? { duplex: "half" } : {}
29
+ });
30
+ const response = await handle(request, req.socket.remoteAddress ?? "?");
31
+ res.writeHead(response.status, Object.fromEntries(response.headers));
32
+ if (response.body) {
33
+ for await (const chunk of response.body) res.write(chunk);
34
+ }
35
+ res.end();
36
+ } catch (e) {
37
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
38
+ res.end(JSON.stringify({ error: e.message }));
39
+ }
40
+ });
41
+ httpServer.listen(PORT, () => {
42
+ console.error(`Based Loans server on :${PORT} (MCP /mcp, API /v1${opts.readOnly ? ", read-only" : ""})`);
43
+ });
@@ -0,0 +1,15 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { BasedLoansOptions } from '@basedloans/sdk';
3
+
4
+ declare const SERVER_NAME = "basedloans";
5
+ declare const SERVER_VERSION = "0.1.1";
6
+ interface ServerOptions extends BasedLoansOptions {
7
+ /**
8
+ * Expose only read tools (no transaction builders). Use for directories that do not accept
9
+ * tools that prepare financial transactions.
10
+ */
11
+ readOnly?: boolean;
12
+ }
13
+ declare function createServer(opts?: ServerOptions): McpServer;
14
+
15
+ export { SERVER_NAME, SERVER_VERSION, type ServerOptions, createServer };
package/dist/server.js ADDED
@@ -0,0 +1,10 @@
1
+ import {
2
+ SERVER_NAME,
3
+ SERVER_VERSION,
4
+ createServer
5
+ } from "./chunk-WAPVXQ4B.js";
6
+ export {
7
+ SERVER_NAME,
8
+ SERVER_VERSION,
9
+ createServer
10
+ };
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/stdio.js ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ createServer
4
+ } from "./chunk-WAPVXQ4B.js";
5
+
6
+ // src/stdio.ts
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ var server = createServer({
9
+ rpcUrl: process.env.BASE_RPC_URL || void 0,
10
+ dataSuffix: process.env.BASEDLOANS_DATA_SUFFIX || void 0,
11
+ ...process.env.BASEDLOANS_BUILDER_CODE !== void 0 ? { builderCode: process.env.BASEDLOANS_BUILDER_CODE || null } : {},
12
+ readOnly: process.env.BASEDLOANS_READ_ONLY === "1"
13
+ });
14
+ await server.connect(new StdioServerTransport());
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@basedloans/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "MCP server for Based Loans on Base: market data, risk reports, loan quotes and unsigned borrow/lend transactions. Holds no keys.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "mcpName": "io.github.0xVarius/basedloans",
8
+ "bin": {
9
+ "basedloans-mcp": "./dist/stdio.js"
10
+ },
11
+ "main": "./dist/server.js",
12
+ "files": [
13
+ "dist",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsup src/stdio.ts src/http.ts src/server.ts src/fetch.ts --format esm --dts --clean",
19
+ "typecheck": "tsc --noEmit",
20
+ "start:http": "node dist/http.js",
21
+ "build:vercel": "esbuild deploy/vercel/src/entry.ts --bundle --platform=node --format=esm --target=node22 --outfile=deploy/vercel/api/index.js --banner:js=\"import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);\" --log-level=warning"
22
+ },
23
+ "dependencies": {
24
+ "@basedloans/sdk": "0.1.0",
25
+ "@modelcontextprotocol/sdk": "^1.32.2",
26
+ "zod": "^3.25.0"
27
+ },
28
+ "peerDependencies": {
29
+ "viem": "^2.21.0"
30
+ },
31
+ "devDependencies": {
32
+ "viem": "^2.21.0"
33
+ },
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/server.d.ts",
37
+ "import": "./dist/server.js"
38
+ },
39
+ "./fetch": {
40
+ "types": "./dist/fetch.d.ts",
41
+ "import": "./dist/fetch.js"
42
+ }
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/0xVarius/basedloans-agents.git",
47
+ "directory": "packages/mcp"
48
+ },
49
+ "homepage": "https://github.com/0xVarius/basedloans-agents/tree/main/packages/mcp#readme",
50
+ "bugs": {
51
+ "url": "https://github.com/0xVarius/basedloans-agents/issues"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }