or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdclient.mdcontext.mdindex.mdprompts.mdresources.mdserver.mdtools.mdtransports.mdutilities.md

client.mddocs/

0

# Client Library

1

2

Full-featured MCP client supporting multiple transports, authentication, and advanced features like LLM sampling. The FastMCP client allows you to connect to and interact with any MCP server programmatically.

3

4

## Capabilities

5

6

### Client Class

7

8

Main client implementation for connecting to MCP servers with support for multiple transports and authentication methods.

9

10

```python { .api }

11

class Client:

12

def __init__(

13

self,

14

server_or_config: str | FastMCP | dict,

15

transport: ClientTransport | None = None,

16

auth: BearerAuth | OAuth | None = None,

17

sampling_handler: SamplingHandler | None = None,

18

elicitation_handler: ElicitationHandler | None = None,

19

timeout: float = 30.0

20

):

21

"""

22

Create a client to connect to an MCP server.

23

24

Parameters:

25

- server_or_config: Server script path, FastMCP instance, or MCP config

26

- transport: Specific transport to use (auto-detected if None)

27

- auth: Authentication for secured servers

28

- sampling_handler: Handler for server LLM sampling requests

29

- elicitation_handler: Handler for server elicitation requests

30

- timeout: Request timeout in seconds

31

"""

32

```

33

34

### Tool Operations

35

36

List and call tools available on the connected MCP server.

37

38

```python { .api }

39

async def list_tools(self) -> list[dict]:

40

"""

41

List all available tools on the server.

42

43

Returns:

44

List of tool metadata dictionaries with name, description, and schema

45

"""

46

47

async def call_tool(

48

self,

49

name: str,

50

arguments: dict | None = None

51

) -> ToolResult:

52

"""

53

Call a tool on the server.

54

55

Parameters:

56

- name: Tool name to call

57

- arguments: Tool arguments as dictionary

58

59

Returns:

60

Tool execution result with text content and optional metadata

61

"""

62

```

63

64

### Resource Operations

65

66

List and read resources available on the connected MCP server.

67

68

```python { .api }

69

async def list_resources(self) -> list[dict]:

70

"""

71

List all available resources on the server.

72

73

Returns:

74

List of resource metadata dictionaries with uri, name, description, and mime_type

75

"""

76

77

async def read_resource(self, uri: str) -> ResourceResult:

78

"""

79

Read a resource from the server.

80

81

Parameters:

82

- uri: Resource URI to read

83

84

Returns:

85

Resource content with text/binary data and metadata

86

"""

87

88

async def list_resource_templates(self) -> list[dict]:

89

"""

90

List all available resource templates on the server.

91

92

Returns:

93

List of resource template metadata with uri_template, name, and description

94

"""

95

```

96

97

### Prompt Operations

98

99

List and get prompts available on the connected MCP server.

100

101

```python { .api }

102

async def list_prompts(self) -> list[dict]:

103

"""

104

List all available prompts on the server.

105

106

Returns:

107

List of prompt metadata dictionaries with name, description, and schema

108

"""

109

110

async def get_prompt(

111

self,

112

name: str,

113

arguments: dict | None = None

114

) -> PromptResult:

115

"""

116

Get a prompt from the server.

117

118

Parameters:

119

- name: Prompt name to retrieve

120

- arguments: Prompt arguments as dictionary

121

122

Returns:

123

Prompt result with formatted messages

124

"""

125

```

126

127

### Connection Management

128

129

Context manager support for automatic connection lifecycle management.

130

131

```python { .api }

132

async def __aenter__(self) -> "Client":

133

"""Enter async context manager."""

134

135

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:

136

"""Exit async context manager."""

137

138

async def close(self) -> None:

139

"""Close the client connection."""

140

```

141

142

## Usage Examples

143

144

### Basic Client Usage

145

146

```python

147

from fastmcp import Client

148

import asyncio

149

150

async def main():

151

# Connect to a server via stdio

152

async with Client("my_server.py") as client:

153

# List available capabilities

154

tools = await client.list_tools()

155

resources = await client.list_resources()

156

prompts = await client.list_prompts()

157

158

print(f"Available tools: {[t['name'] for t in tools]}")

159

print(f"Available resources: {[r['uri'] for r in resources]}")

160

print(f"Available prompts: {[p['name'] for p in prompts]}")

161

162

# Call a tool

163

result = await client.call_tool("add", {"a": 5, "b": 3})

164

print(f"Tool result: {result.text}")

165

166

# Read a resource

167

resource = await client.read_resource("config://version")

168

print(f"Resource content: {resource.content}")

169

170

# Get a prompt

171

prompt = await client.get_prompt("summarize", {"text": "Hello world"})

172

print(f"Prompt messages: {prompt.messages}")

173

174

asyncio.run(main())

175

```

176

177

### Client with Different Transports

178

179

```python

180

from fastmcp import Client

181

182

async def stdio_client():

183

"""Connect via stdio transport."""

184

async with Client("python server.py") as client:

185

result = await client.call_tool("hello", {"name": "World"})

186

return result.text

187

188

async def sse_client():

189

"""Connect via SSE transport."""

190

async with Client("http://localhost:8000/sse") as client:

191

tools = await client.list_tools()

192

return tools

193

194

async def http_client():

195

"""Connect via HTTP transport."""

196

async with Client("http://localhost:8000/mcp") as client:

197

resources = await client.list_resources()

198

return resources

199

200

# Auto-detection also works

201

async def auto_detect():

202

"""Client auto-detects transport type."""

203

clients = [

204

Client("./server.py"), # stdio

205

Client("http://localhost:8000/sse"), # SSE

206

Client("http://localhost:8000/mcp"), # HTTP

207

]

208

209

for client in clients:

210

async with client:

211

tools = await client.list_tools()

212

print(f"Connected with {len(tools)} tools")

213

```

214

215

### Client with Authentication

216

217

```python

218

from fastmcp import Client

219

from fastmcp.client.auth import BearerAuth, OAuth

220

221

async def authenticated_client():

222

"""Connect to secured server with Bearer token."""

223

auth = BearerAuth("your-bearer-token")

224

225

async with Client(

226

"https://secure-server.com/mcp",

227

auth=auth

228

) as client:

229

result = await client.call_tool("secure_operation", {})

230

return result.text

231

232

async def oauth_client():

233

"""Connect with OAuth authentication."""

234

oauth = OAuth(

235

client_id="your-client-id",

236

client_secret="your-client-secret",

237

token_url="https://auth.example.com/token"

238

)

239

240

async with Client(

241

"https://api.example.com/mcp",

242

auth=oauth

243

) as client:

244

result = await client.call_tool("api_operation", {})

245

return result.text

246

```

247

248

### Client with LLM Sampling Handler

249

250

```python

251

from fastmcp import Client

252

253

async def sampling_handler(messages):

254

"""Handle server LLM sampling requests."""

255

# This would typically connect to your LLM

256

# For example, OpenAI GPT, Claude, etc.

257

response = "This is a sample response"

258

return {"text": response}

259

260

async def client_with_sampling():

261

"""Client that can handle server sampling requests."""

262

async with Client(

263

"intelligent_server.py",

264

sampling_handler=sampling_handler

265

) as client:

266

# Server can now request LLM completions via ctx.sample()

267

result = await client.call_tool("analyze_data", {

268

"data": "Some complex data to analyze"

269

})

270

return result.text

271

```

272

273

### Multi-Server Client Configuration

274

275

```python

276

from fastmcp import Client

277

278

async def multi_server_client():

279

"""Connect to multiple servers with unified client."""

280

config = {

281

"mcpServers": {

282

"weather": {

283

"url": "https://weather-api.example.com/mcp"

284

},

285

"assistant": {

286

"command": "python",

287

"args": ["./assistant_server.py"]

288

},

289

"database": {

290

"url": "http://localhost:8080/mcp",

291

"auth": {"type": "bearer", "token": "db-token"}

292

}

293

}

294

}

295

296

async with Client(config) as client:

297

# Tools are prefixed with server names

298

forecast = await client.call_tool(

299

"weather_get_forecast",

300

{"city": "London"}

301

)

302

303

answer = await client.call_tool(

304

"assistant_answer_question",

305

{"query": "What is MCP?"}

306

)

307

308

data = await client.call_tool(

309

"database_query",

310

{"sql": "SELECT * FROM users LIMIT 10"}

311

)

312

313

return {

314

"forecast": forecast.text,

315

"answer": answer.text,

316

"data": data.text

317

}

318

```

319

320

### In-Memory Testing with FastMCP

321

322

```python

323

from fastmcp import FastMCP, Client

324

325

async def test_server_with_client():

326

"""Test a FastMCP server using in-memory client."""

327

# Create server

328

mcp = FastMCP("Test Server")

329

330

@mcp.tool

331

def multiply(a: int, b: int) -> int:

332

"""Multiply two numbers."""

333

return a * b

334

335

# Connect via in-memory transport (no subprocess)

336

async with Client(mcp) as client:

337

# Test the server directly

338

result = await client.call_tool("multiply", {"a": 6, "b": 7})

339

assert result.text == "42"

340

341

tools = await client.list_tools()

342

assert len(tools) == 1

343

assert tools[0]["name"] == "multiply"

344

```

345

346

## Result Types

347

348

```python { .api }

349

class ToolResult:

350

"""Result from calling a tool."""

351

text: str

352

content: list[dict] | None

353

is_error: bool

354

355

class ResourceResult:

356

"""Result from reading a resource."""

357

content: str | bytes

358

mime_type: str | None

359

uri: str

360

361

class PromptResult:

362

"""Result from getting a prompt."""

363

messages: list[dict]

364

description: str | None

365

```