LayerHopDocsLaunch app (opens in a new tab)

AI agents: MCP config and tool definitions for swaps

Give an AI agent cross-chain swap quotes with LayerHop. Claude Desktop and Cursor MCP config, plus tool definitions for Anthropic and OpenAI tool use, LangChain and the Vercel AI SDK.

An AI agent can quote cross-chain swaps through LayerHop in two ways: connect the LayerHop MCP server (https://mcp.layerhop.com/mcp or npx -y @layerhop/mcp) to Claude Desktop, Cursor or another MCP client, or give your own agent thin tool wrappers over the LayerHop REST API. In both cases the agent only reads quotes and hands the user a swap link: it holds no keys and never signs.

What do I need first?#

  • For MCP: Claude Desktop, Cursor, Claude Code, ChatGPT or any MCP client. Node 18+ if you run the local server.
  • For your own agent: Node 20+, and the SDK of your model provider (@anthropic-ai/sdk, openai, ai, or @langchain/core) plus zod.
  • Optional: a LayerHop API key from the dashboard for your own rate limit and partner fee.

1. Connect the MCP server to a client#

Claude Desktop, in Settings, Developer, Edit Config (claude_desktop_config.json), then restart the app:

JSON
{
  "mcpServers": {
    "layerhop": {
      "command": "npx",
      "args": ["-y", "@layerhop/mcp"],
      "env": { "LAYERHOP_API_KEY": "" }
    }
  }
}

Cursor, in ~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project), using the hosted server:

JSON
{
  "mcpServers": {
    "layerhop": { "url": "https://mcp.layerhop.com/mcp" }
  }
}

Claude Code:

Terminal
claude mcp add --transport http layerhop https://mcp.layerhop.com/mcp

Then ask: "What is the cheapest way to move 100 USDC from Base to SOL on Solana? My Solana address is 9WzD...AWWM." The model calls get_quote and replies with the best route, every fee and a prefilled swap link. The full tool list is in AI agents (MCP).

2. Write the shared tool code#

These two tools call the REST API directly. Amounts the model sees are human decimals; the code converts them to base units with integer math using the token's decimals from GET /v1/tokens.

TypeScript
// layerhop-tools.ts
const API = "https://api.layerhop.com/v1";
const headers = { ...(process.env.LAYERHOP_API_KEY ? { "x-api-key": process.env.LAYERHOP_API_KEY } : {}) };

async function api(path: string, params?: Record<string, string>) {
  const res = await fetch(`${API}/${path}${params ? `?${new URLSearchParams(params)}` : ""}`, { headers });
  const body: any = await res.json();
  if (!res.ok) throw new Error(`${body.error?.code}: ${body.error?.message}`);
  return body;
}

async function tokenInfo(chain: string, symbol: string): Promise<{ decimals: number; symbol: string }> {
  const { tokens } = await api("tokens", { chain, q: symbol, limit: "5" });
  const t = tokens.find((x: any) => x.symbol.toLowerCase() === symbol.toLowerCase());
  if (!t) throw new Error(`Unknown token ${symbol} on ${chain}`);
  return t;
}

/** "100.5" with 6 decimals -> "100500000", no floats. */
function toBaseUnits(amount: string, decimals: number): string {
  const m = /^(\d+)(?:\.(\d+))?$/.exec(amount.trim());
  if (!m || (m[2]?.length ?? 0) > decimals) throw new Error(`Invalid amount ${amount}`);
  return (BigInt(m[1]!) * 10n ** BigInt(decimals) + BigInt((m[2] ?? "").padEnd(decimals, "0") || "0")).toString();
}

export async function getQuote(a: { fromChain: string; fromToken: string; amount: string; toChain: string; toToken: string; sender: string; recipient: string }) {
  const src = await tokenInfo(a.fromChain, a.fromToken);
  const dst = await tokenInfo(a.toChain, a.toToken);
  const { best } = await api("quote", {
    srcChain: a.fromChain, srcToken: a.fromToken, amount: toBaseUnits(a.amount, src.decimals),
    dstChain: a.toChain, dstToken: a.toToken, sender: a.sender, recipient: a.recipient,
  });
  const human = (v: string) => (Number(BigInt(v)) / 10 ** dst.decimals).toString();
  const link = `https://layerhop.com/swap?${new URLSearchParams({ srcChain: a.fromChain, srcToken: a.fromToken, dstChain: a.toChain, dstToken: a.toToken, amount: a.amount, recipient: a.recipient })}`;
  return {
    provider: best.provider,
    youReceive: `${human(best.dstAmount)} ${a.toToken}`,
    minimumReceived: `${human(best.dstAmountMin)} ${a.toToken}`,
    estimatedSeconds: best.estimatedSeconds,
    layerhopFeeBps: best.fees.ourFeeBps,
    swapLink: link, // the user reviews the live quote and signs in their own wallet
    note: "Show the fees and minimum to the user. Never ask for a private key.",
  };
}

export async function getOrderStatus(a: { provider: string; txHash: string }) {
  return api(`orders/${a.provider}/${a.txHash}`); // { state: pending | filled | refunded | failed | unknown | dropped, ... }
}

export const getQuoteJsonSchema = {
  type: "object",
  properties: {
    fromChain: { type: "string", description: "Source chain slug, e.g. base, arbitrum, solana" },
    fromToken: { type: "string", description: "Source token symbol, e.g. USDC" },
    amount: { type: "string", description: "Human amount, e.g. '100' for 100 USDC" },
    toChain: { type: "string", description: "Destination chain slug" },
    toToken: { type: "string", description: "Destination token symbol, e.g. SOL" },
    sender: { type: "string", description: "Wallet address that pays on the source chain" },
    recipient: { type: "string", description: "Address that receives on the destination chain" },
  },
  required: ["fromChain", "fromToken", "amount", "toChain", "toToken", "sender", "recipient"],
} as const;

export const orderStatusJsonSchema = {
  type: "object",
  properties: {
    provider: { type: "string", description: "Provider id from the quote, e.g. relay" },
    txHash: { type: "string", description: "Source transaction hash" },
  },
  required: ["provider", "txHash"],
} as const;

3. Use the tools with Anthropic tool use#

TypeScript
import Anthropic from "@anthropic-ai/sdk";
import { getQuote, getOrderStatus, getQuoteJsonSchema, orderStatusJsonSchema } from "./layerhop-tools";

const client = new Anthropic();
const tools = [
  { name: "get_quote", description: "Best cross-chain or same-chain swap quote from LayerHop. Returns fees, minimum received, ETA and a swap link for the user.", input_schema: getQuoteJsonSchema },
  { name: "get_order_status", description: "Status of a swap after the user sent it.", input_schema: orderStatusJsonSchema },
];
const run: Record<string, (a: any) => Promise<unknown>> = { get_quote: getQuote, get_order_status: getOrderStatus };

const messages: Anthropic.MessageParam[] = [{ role: "user", content: "Quote 100 USDC on Base to SOL on Solana. Sender 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045, recipient 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM." }];
for (;;) {
  const res = await client.messages.create({ model: process.env.ANTHROPIC_MODEL!, max_tokens: 1024, tools, messages });
  messages.push({ role: "assistant", content: res.content });
  if (res.stop_reason !== "tool_use") { console.log(res.content.find((b) => b.type === "text")?.text); break; }
  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const b of res.content) {
    if (b.type !== "tool_use") continue;
    try { results.push({ type: "tool_result", tool_use_id: b.id, content: JSON.stringify(await run[b.name]!(b.input)) }); }
    catch (e: any) { results.push({ type: "tool_result", tool_use_id: b.id, content: e.message, is_error: true }); }
  }
  messages.push({ role: "user", content: results });
}

Set ANTHROPIC_MODEL to any current Claude model id.

4. Use the tools with OpenAI function calling#

TypeScript
import OpenAI from "openai";
import { getQuote, getOrderStatus, getQuoteJsonSchema, orderStatusJsonSchema } from "./layerhop-tools";

const openai = new OpenAI();
const tools: OpenAI.Chat.ChatCompletionTool[] = [
  { type: "function", function: { name: "get_quote", description: "Best swap quote from LayerHop with fees and a swap link.", parameters: getQuoteJsonSchema as any } },
  { type: "function", function: { name: "get_order_status", description: "Status of a swap after the user sent it.", parameters: orderStatusJsonSchema as any } },
];
const run: Record<string, (a: any) => Promise<unknown>> = { get_quote: getQuote, get_order_status: getOrderStatus };

const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [{ role: "user", content: "Quote 0.5 ETH on Arbitrum to USDC on Base for 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045." }];
for (;;) {
  const res = await openai.chat.completions.create({ model: process.env.OPENAI_MODEL!, messages, tools });
  const msg = res.choices[0]!.message;
  messages.push(msg);
  if (!msg.tool_calls?.length) { console.log(msg.content); break; }
  for (const call of msg.tool_calls) {
    if (call.type !== "function") continue;
    const out = await run[call.function.name]!(JSON.parse(call.function.arguments)).catch((e: Error) => ({ error: e.message }));
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(out) });
  }
}

5. Use the tools with the Vercel AI SDK and LangChain#

TypeScript
// Vercel AI SDK
import { generateText, stepCountIs, tool } from "ai";
import { z } from "zod";
import { getQuote } from "./layerhop-tools";

const { text } = await generateText({
  model: process.env.AI_MODEL!, // e.g. "openai/gpt-5" through the AI Gateway
  tools: {
    get_quote: tool({
      description: "Best swap quote from LayerHop with fees and a swap link.",
      inputSchema: z.object({ fromChain: z.string(), fromToken: z.string(), amount: z.string(), toChain: z.string(), toToken: z.string(), sender: z.string(), recipient: z.string() }),
      execute: getQuote,
    }),
  },
  stopWhen: stepCountIs(5),
  prompt: "Quote 100 USDC on Base to SOL. Sender 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045, recipient 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM.",
});
TypeScript
// LangChain JS
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { getQuote } from "./layerhop-tools";

export const getQuoteTool = tool(getQuote, {
  name: "get_quote",
  description: "Best swap quote from LayerHop with fees and a swap link.",
  schema: z.object({ fromChain: z.string(), fromToken: z.string(), amount: z.string(), toChain: z.string(), toToken: z.string(), sender: z.string(), recipient: z.string() }),
});
// pass it to createReactAgent({ llm, tools: [getQuoteTool] }) from @langchain/langgraph/prebuilt

Prefer maintained packages? @layerhop/ai ships these tools, with validation, for the Vercel AI SDK, LangChain, OpenAI and more: see Agent frameworks.

How does it work?#

  • GET /v1/tokens?chain=&q= finds a token's decimals, and GET /v1/quote returns best with dstAmount, dstAmountMin, estimatedSeconds, fees.ourFeeBps and a quoteId (reference). Amounts are integer strings in base units.
  • The tool returns a deep link so the person reviews the live quote and signs in their own wallet. The API's POST /v1/orders returns an unsigned transaction, which belongs only in agents that already have a signer the user controls.
  • GET /v1/orders/{provider}/{id} reports pending, filled, refunded, failed, dropped or unknown (Order tracking).

Can an agent sign swaps?#

Only if you give it a signer you control. The MCP server and these wrappers never sign. Always have the agent show the output, the minimum received, every fee and the ETA, and get an explicit yes before any transaction. See Non-custodial by design.

Should I use MCP or REST wrappers?#

Use MCP when the user's own client (Claude Desktop, Cursor, ChatGPT) runs the agent: nothing to build. Use REST wrappers or @layerhop/ai when you build the agent yourself and want control of the prompt, the tools and the loop.

Next: AI agents (MCP), Agent frameworks, API reference.

Last updated