> ## Documentation Index
> Fetch the complete documentation index at: https://docs.madra.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Integration for Agents

> Wire the Bazaar and StellarX402 client into an MCP-speaking agent runtime.

Agents that use the Model Context Protocol (MCP) already have a tool-call abstraction. Adding paid tools is a matter of teaching the runtime three things: how to discover tools that require payment, how to attach a payment to a tool invocation, and how to interpret rejection.

## Discovery

In the agent's tool registration phase, query the Bazaar for MCP tools:

```typescript theme={null}
import { discover } from "@stellarx402/client";

const tools = await discover({
  facilitator,
  filters: { type: "mcp", network: "stellar:pubnet" },
  limit: 100,
});

for (const tool of tools.results) {
  agent.registerTool({
    name: tool.name,
    description: `${tool.describe.description} (paid: ${tool.payment.amount} ${tool.payment.asset})`,
    inputSchema: tool.inputSchema,
    invoke: paidInvoker(tool),
  });
}
```

## Paid invocation

```typescript theme={null}
function paidInvoker(tool) {
  return async (input) => {
    await budget.assert(tool.name);
    const res = await fetchWithPayment(tool.resource, {
      wallet,
      facilitator,
      method: "POST",
      body: JSON.stringify(input),
      maxAmount: perToolMax(tool.name),
    });
    await budget.record(tool.name, res.headers.get("x-payment-amount"));
    return res.json();
  };
}
```

## Handling rejection at the tool boundary

An MCP runtime typically has a retry mechanism at the tool-call level. Do not use it for payment rejections directly, because the reactions vary by code (see [Handling Rejections](/guides/buyers/handling-rejections)). Wrap the invoker and translate rejections into tool errors the LLM can reason about:

```typescript theme={null}
try {
  return await paidInvoker(tool)(input);
} catch (err) {
  if (err.code === "insufficient_funds") throw new ToolError("budget exhausted");
  if (err.code === "resource_gone") { agent.unregisterTool(tool.name); throw new ToolError("tool no longer available"); }
  throw err;
}
```

## Related

* [Cataloging MCP Tools](/discovery/cataloging-mcp-tools)
* [MCP Tool Schemas](/api/mcp-tool-schemas)
* [Budgets & the Upto Scheme](/guides/buyers/budgets-and-upto)
