# Build an agent (/docs/mcp/build-an-agent)

You don't need ChatGPT or Claude to use Swop's tools. Any program that speaks MCP can connect: an agent framework, a backend job, a bot. This page uses the official MCP SDKs.

<Steps>
<Step>

### Install the SDK [#install-the-sdk]

<Tabs items={['TypeScript', 'Python']} groupId="lang" persist>
<Tab value="TypeScript">
```bash
npm install @modelcontextprotocol/sdk
```
</Tab>
<Tab value="Python">
```bash
pip install mcp
```
</Tab>
</Tabs>

</Step>
<Step>

### Connect and call a public tool [#connect-and-call-a-public-tool]

No account needed for identity, stores and market data.

<Tabs items={['TypeScript', 'Python']} groupId="lang" persist>
<Tab value="TypeScript">
```ts title="agent.ts"
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const client = new Client({ name: 'my-agent', version: '1.0.0' });
await client.connect(
  new StreamableHTTPClientTransport(new URL('https://mcp.swopme.co/mcp')),
);

const { tools } = await client.listTools();
console.log(`${tools.length} tools`); // 51

const result = await client.callTool({
  name: 'swop_lookup_identity',
  arguments: { handle: 'travis.swop.id' },
});
console.log(JSON.parse(result.content[0].text).data.evmAddress);

await client.close();
```
</Tab>
<Tab value="Python">
```python title="agent.py"
import asyncio, json
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

async def main():
    async with streamablehttp_client("https://mcp.swopme.co/mcp") as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await session.list_tools()
            print(len(tools.tools), "tools")  # 51

            result = await session.call_tool("swop_lookup_identity", {"handle": "travis.swop.id"})
            print(json.loads(result.content[0].text)["data"]["evmAddress"])

asyncio.run(main())
```
</Tab>
</Tabs>

Every tool returns one `text` item holding JSON. On failure the result has `isError: true` and the text explains why.

</Step>
<Step>

### Let your model choose tools [#let-your-model-choose-tools]

Pass the `tools` list (each has `name`, `description` and a JSON Schema `inputSchema`) to your model as function definitions, and route the model's tool calls back through `callTool`. The descriptions are written for models: they say when to use each tool, which tool to call next, and when to ask the user first.

Also pass along the server's **instructions** (returned from `initialize`; `client.getInstructions()` in TypeScript). They tell the model what Swop can do for this endpoint and how to behave, including always confirming prices and payments with the user.

</Step>
<Step>

### Sign in for account tools [#sign-in-for-account-tools]

Calling an account tool without a token fails with HTTP `401` and JSON-RPC error `-32001` ("Not linked to a Swop account"). The fix is OAuth: the SDKs can run the whole flow if you give them an auth provider.

<Tabs items={['TypeScript', 'Python']} groupId="lang" persist>
<Tab value="TypeScript">
Implement the SDK's `OAuthClientProvider` interface (it stores client info and tokens, and opens the authorization URL for your user), then pass it to the transport:

```ts
const transport = new StreamableHTTPClientTransport(
  new URL('https://mcp.swopme.co/mcp'),
  { authProvider: myOAuthProvider },
);
```

On a `401`, the transport discovers Swop's authorization server, registers your client, sends the user to approve, exchanges the code with PKCE and retries. Already holding a token for one user? Send it directly:

```ts
new StreamableHTTPClientTransport(new URL('https://mcp.swopme.co/mcp'), {
  requestInit: { headers: { Authorization: `Bearer ${accessToken}` } },
});
```
</Tab>
<Tab value="Python">
The Python SDK ships an OAuth helper (`OAuthClientProvider` in `mcp.client.auth`) that plugs into the HTTP client as `auth=`. Or, if you already hold a token for one user, pass it as a header:

```python
async with streamablehttp_client(
    "https://mcp.swopme.co/mcp",
    headers={"Authorization": f"Bearer {access_token}"},
) as (read, write, _):
    ...
```
</Tab>
</Tabs>

The endpoints, token lifetimes and scopes are in [Account linking & caps](/docs/mcp/account-linking-and-caps).

</Step>
<Step>

### Handle money tools in two calls [#handle-money-tools-in-two-calls]

Money and posting tools return a **preview** first. Show it to your user, and only after they approve call again with `previewId` and `confirm: true`:

```ts
const preview = await client.callTool({
  name: 'swop_send',
  arguments: { to: 'maya.swop.id', amountUsd: 25 },
});
const { previewId, summary } = JSON.parse(preview.content[0].text);
// e.g. summary: "Send 25 USDC (~$25.00) on base to maya.swop.id (Maya)"
// Show it (and the caps in the preview) to the user. Only on their explicit yes:
await client.callTool({
  name: 'swop_send',
  arguments: { to: 'maya.swop.id', amountUsd: 25, previewId, confirm: true },
});
```

For `swop_send`, the confirm call must restate the same recipient, token, chain and amount. The exact preview fields for each tool are in the [tool reference](/docs/mcp/tool-reference).

</Step>
</Steps>

## Rules for agents that act for people [#rules-for-agents-that-act-for-people]

- **Never confirm for the user.** A preview exists so a person sees exactly what will happen.
- **Respect refusals.** Over-cap and spending-off responses return an approval link or a reason. Hand it to the user; don't retry with smaller pieces to get under a cap.
- **One user per token.** Tokens represent one Swop account. Don't share them across users.
- **Don't promise outcomes.** Trading tools can lose money. Show leverage, exposure and worst price exactly as previewed.
