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

# MCP Client

> Connect to MCP (Model Context Protocol) servers and use their tools as native Agentium agent tools.

# MCP Client

Agentium includes a built-in MCP client that lets your agents connect to any [Model Context Protocol](https://modelcontextprotocol.io/) server and use its tools natively — no glue code required.

<Info>
  MCP is an open protocol that standardizes how LLM applications integrate with external tools, resources, and prompts. Agentium acts as an MCP **client**, consuming tools from external MCP servers.
</Info>

***

## Installation

The MCP SDK is an optional peer dependency:

```bash theme={null}
npm install @modelcontextprotocol/sdk
```

***

## Quick Start

```typescript theme={null}
import { Agent, openai, MCPToolProvider } from "@agentium/core";

// Connect to a GitHub MCP server via stdio
const github = new MCPToolProvider({
  name: "github",
  transport: "stdio",
  command: "npx",
  args: ["-y", "@modelcontextprotocol/server-github"],
  env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
});

await github.connect();

const agent = new Agent({
  name: "dev-assistant",
  model: openai("gpt-4o"),
  instructions: "You are a developer assistant with GitHub access.",
  tools: [...await github.getTools()],
});

const result = await agent.run("What are the open issues in my repo?");
console.log(result.text);

await github.close();
```

***

## Transports

### stdio

Spawns the MCP server as a child process and communicates via stdin/stdout. Best for local MCP servers.

```typescript theme={null}
const tools = new MCPToolProvider({
  name: "filesystem",
  transport: "stdio",
  command: "npx",
  args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
});
```

<ParamField body="command" type="string" required>
  The command to spawn (e.g. `"npx"`, `"node"`, `"python"`).
</ParamField>

<ParamField body="args" type="string[]">
  Arguments for the command.
</ParamField>

<ParamField body="env" type="Record<string, string>">
  Environment variables passed to the spawned process.
</ParamField>

### HTTP (Streamable HTTP)

Connects to a remote MCP server over HTTP. Falls back to SSE transport if Streamable HTTP is not available.

```typescript theme={null}
const tools = new MCPToolProvider({
  name: "database",
  transport: "http",
  url: "http://localhost:8080/mcp",
  headers: { Authorization: "Bearer my-token" },
});
```

<ParamField body="url" type="string" required>
  The MCP server URL.
</ParamField>

<ParamField body="headers" type="Record<string, string>">
  Custom HTTP headers (e.g. for authentication).
</ParamField>

### SSE (Server-Sent Events)

For MCP servers that use separate `/sse` and `/messages` endpoints. The client opens a persistent SSE stream for receiving responses and sends JSON-RPC requests via POST. Use this when your server implements the async SSE pattern.

```typescript theme={null}
const mcp = new MCPToolProvider({
  name: "xhipment",
  transport: "sse",
  url: "http://localhost:3000/mcp/sse",
  headers: {
    "X-MCP-API-Key": "your-api-key",
  },
});

await mcp.connect();
const tools = await mcp.getTools();
```

<ParamField body="url" type="string" required>
  The SSE endpoint URL. The client reads this stream and discovers the POST endpoint for messages automatically.
</ParamField>

<ParamField body="headers" type="Record<string, string>">
  Custom HTTP headers sent on both the SSE connection and POST requests.
</ParamField>

***

## Mixing MCP and Local Tools

MCP tools are returned as standard `ToolDef[]` and can be combined with local tools:

```typescript theme={null}
import { defineTool } from "@agentium/core";
import { z } from "zod";

const localTool = defineTool({
  name: "current_time",
  description: "Returns the current date and time",
  parameters: z.object({}),
  execute: async () => new Date().toISOString(),
});

const agent = new Agent({
  name: "assistant",
  model: openai("gpt-4o"),
  tools: [
    ...await github.getTools(),    // MCP tools
    ...await dbTools.getTools(),    // Another MCP server
    localTool,                      // Local tool
  ],
});
```

***

## Multiple MCP Servers

Connect to multiple servers simultaneously. Tool names are namespaced as `{serverName}__{toolName}` to avoid collisions:

```typescript theme={null}
const github = new MCPToolProvider({ name: "github", ... });
const slack = new MCPToolProvider({ name: "slack", ... });

await Promise.all([github.connect(), slack.connect()]);

const agent = new Agent({
  name: "assistant",
  model: openai("gpt-4o"),
  tools: [
    ...await github.getTools(),  // github__create_issue, github__list_repos, ...
    ...await slack.getTools(),   // slack__send_message, slack__list_channels, ...
  ],
});
```

***

## Handling Large Tool Results

MCP servers often return bulk data (e.g. all outstanding invoices, full record sets). A single tool result can be 200KB+, which translates to 50K+ prompt tokens on the next LLM roundtrip.

Use `toolResultLimit` to automatically truncate or summarize oversized results before they reach the main model:

```typescript theme={null}
const agent = new Agent({
  name: "assistant",
  model: anthropic("claude-sonnet-4-6"),
  tools: [...await mcp.getTools()],
  toolResultLimit: {
    maxChars: 20000,
    strategy: "summarize",
    model: anthropic("claude-haiku-4-5-20251001"),
  },
});
```

This is especially important when combining `toolResultLimit` with `toolRouter` — the router selects which tools to call, and the result limit controls how much data comes back. Together they can reduce prompt tokens by 95%+.

See [Tool Result Limits](/agents/tools#tool-result-limits) for full configuration details.

***

## Dynamic Tools with `setTools()`

When MCP servers are connected or disconnected at runtime, use `agent.setTools()` to hot-swap the tool set without recreating the agent:

```typescript theme={null}
const agent = new Agent({
  name: "assistant",
  model: openai("gpt-4o"),
  tools: [],
});

// Later, after MCP servers connect...
const mcpTools = await mcp.getTools();
agent.setTools(mcpTools);

// Agent now uses the updated tools on the next run
```

***

## MCPManager (Multi-Server Lifecycle)

For managing multiple MCP servers at runtime — adding, connecting, disconnecting, and collecting tools — use `MCPManager` from `@agentium/transport`:

```typescript theme={null}
import { MCPManager } from "@agentium/transport";

const mcpManager = new MCPManager();

// Add and connect a server
mcpManager.add({
  name: "xhipment",
  transport: "sse",
  url: "http://localhost:3000/mcp/sse",
  headers: { "X-MCP-API-Key": "your-key" },
});
await mcpManager.connect("xhipment");

// Add another server
mcpManager.add({
  name: "github",
  transport: "stdio",
  command: "npx",
  args: ["-y", "@modelcontextprotocol/server-github"],
});
await mcpManager.connect("github");

// Get all tools from all connected servers
const allTools = await mcpManager.getAllTools();
agent.setTools(allTools);

// List server statuses
const servers = mcpManager.list();
// [{ id: "xhipment", status: "connected", toolCount: 54 }, ...]

// Disconnect a specific server
await mcpManager.disconnect("github");

// Clean up all
await mcpManager.closeAll();
```

| Method             | Description                                    |
| ------------------ | ---------------------------------------------- |
| `add(config, id?)` | Register a server. Returns summary.            |
| `connect(id)`      | Connect and discover tools.                    |
| `disconnect(id)`   | Disconnect a server.                           |
| `remove(id)`       | Remove a server entirely.                      |
| `getAllTools()`    | Merged `ToolDef[]` from all connected servers. |
| `getTools(id)`     | Tools from a single server.                    |
| `list()`           | All server summaries (id, status, toolCount).  |
| `has(id)`          | Check if a server is registered.               |
| `closeAll()`       | Disconnect all servers.                        |

For managing MCP servers via REST API (from a UI), see [MCP Admin](/mcp/admin).

***

## API Reference

### MCPToolProvider

<ParamField body="name" type="string" required>
  A unique name for this MCP server connection. Used to namespace tool names.
</ParamField>

<ParamField body="transport" type="'stdio' | 'http' | 'sse'" required>
  The transport protocol to use.
</ParamField>

| Method       | Description                                   |
| ------------ | --------------------------------------------- |
| `connect()`  | Connect to the MCP server and discover tools. |
| `getTools()` | Returns `ToolDef[]` — all discovered tools.   |
| `refresh()`  | Re-discover tools from the server.            |
| `close()`    | Disconnect from the server and clean up.      |

***

## Popular MCP Servers

| Server       | Install                                            |
| ------------ | -------------------------------------------------- |
| GitHub       | `npx -y @modelcontextprotocol/server-github`       |
| Filesystem   | `npx -y @modelcontextprotocol/server-filesystem`   |
| PostgreSQL   | `npx -y @modelcontextprotocol/server-postgres`     |
| Brave Search | `npx -y @modelcontextprotocol/server-brave-search` |
| Slack        | `npx -y @modelcontextprotocol/server-slack`        |

Browse all available servers at [mcp.so](https://mcp.so).
