or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auth.mdcli.mdclient.mdfastmcp-server.mdindex.mdlowlevel-server.mdtransport.mdtypes.md

types.mddocs/

0

# Types and Protocol

1

2

Complete MCP protocol type definitions including requests, responses, notifications, capabilities, and data models. These types define the structure and behavior of the Model Context Protocol, enabling type-safe communication between clients and servers.

3

4

## Capabilities

5

6

### Protocol Constants

7

8

Core protocol version and error code constants.

9

10

```python { .api }

11

LATEST_PROTOCOL_VERSION: str = "2025-06-18"

12

DEFAULT_NEGOTIATED_VERSION: str = "2025-03-26"

13

14

# JSON-RPC Error Codes

15

CONNECTION_CLOSED: int = -32000

16

PARSE_ERROR: int = -32700

17

INVALID_REQUEST: int = -32600

18

METHOD_NOT_FOUND: int = -32601

19

INVALID_PARAMS: int = -32602

20

INTERNAL_ERROR: int = -32603

21

```

22

23

### Type Aliases

24

25

Common type aliases used throughout the protocol.

26

27

```python { .api }

28

ProgressToken = str | int

29

Cursor = str

30

Role = Literal["user", "assistant"]

31

RequestId = int | str

32

```

33

34

### Core Protocol Types

35

36

Base classes for JSON-RPC communication and MCP protocol structure.

37

38

```python { .api }

39

class JSONRPCRequest(BaseModel):

40

"""Base JSON-RPC request."""

41

jsonrpc: str = "2.0"

42

id: RequestId

43

method: str

44

params: dict[str, Any] | None = None

45

46

class JSONRPCResponse(BaseModel):

47

"""Base JSON-RPC response."""

48

jsonrpc: str = "2.0"

49

id: RequestId

50

result: Any | None = None

51

error: JSONRPCError | None = None

52

53

class JSONRPCError(BaseModel):

54

"""JSON-RPC error object."""

55

code: int

56

message: str

57

data: Any | None = None

58

59

class Request(BaseModel):

60

"""Base MCP request."""

61

method: str

62

params: dict[str, Any] | None = None

63

64

class Notification(BaseModel):

65

"""Base MCP notification."""

66

method: str

67

params: dict[str, Any] | None = None

68

69

class ErrorData(BaseModel):

70

"""MCP error data structure."""

71

code: int

72

message: str

73

data: Any | None = None

74

75

class Implementation(BaseModel):

76

"""Client or server implementation metadata."""

77

name: str

78

version: str

79

80

class EmptyResult(BaseModel):

81

"""A response that indicates success but carries no data."""

82

pass

83

```

84

85

### Initialization Protocol

86

87

Types for protocol initialization and capability negotiation.

88

89

```python { .api }

90

class InitializeRequest(BaseModel):

91

"""Protocol initialization request."""

92

protocolVersion: str

93

capabilities: ClientCapabilities

94

clientInfo: Implementation

95

96

class InitializeResult(BaseModel):

97

"""Protocol initialization response."""

98

protocolVersion: str

99

capabilities: ServerCapabilities

100

serverInfo: Implementation

101

instructions: str | None = None

102

103

class InitializedNotification(BaseModel):

104

"""Protocol initialization completion notification."""

105

method: Literal["notifications/initialized"] = "notifications/initialized"

106

107

class ClientCapabilities(BaseModel):

108

"""Client capability declarations."""

109

experimental: dict[str, Any] | None = None

110

sampling: dict[str, Any] | None = None

111

roots: RootsCapability | None = None

112

113

class ServerCapabilities(BaseModel):

114

"""Server capability declarations."""

115

experimental: dict[str, Any] | None = None

116

logging: dict[str, Any] | None = None

117

prompts: PromptsCapability | None = None

118

resources: ResourcesCapability | None = None

119

tools: ToolsCapability | None = None

120

121

class PromptsCapability(BaseModel):

122

"""Prompts capability settings."""

123

listChanged: bool | None = None

124

125

class ResourcesCapability(BaseModel):

126

"""Resources capability settings."""

127

subscribe: bool | None = None

128

listChanged: bool | None = None

129

130

class ToolsCapability(BaseModel):

131

"""Tools capability settings."""

132

listChanged: bool | None = None

133

134

class RootsCapability(BaseModel):

135

"""Roots capability settings."""

136

listChanged: bool | None = None

137

```

138

139

### Tool Operations

140

141

Types for tool listing, execution, and management.

142

143

```python { .api }

144

class Tool(BaseModel):

145

"""Tool definition."""

146

name: str

147

description: str | None = None

148

inputSchema: dict[str, Any]

149

150

class ListToolsRequest(BaseModel):

151

"""List available tools request."""

152

method: Literal["tools/list"] = "tools/list"

153

params: dict[str, Any] | None = None

154

155

class ListToolsResult(BaseModel):

156

"""List available tools response."""

157

tools: list[Tool]

158

nextCursor: str | None = None

159

160

class CallToolRequest(BaseModel):

161

"""Tool execution request."""

162

method: Literal["tools/call"] = "tools/call"

163

params: dict[str, Any]

164

165

class CallToolResult(BaseModel):

166

"""Tool execution response."""

167

content: list[ContentBlock]

168

isError: bool | None = None

169

```

170

171

### Resource Operations

172

173

Types for resource listing, reading, and subscription management.

174

175

```python { .api }

176

class Resource(BaseModel):

177

"""Resource definition."""

178

uri: AnyUrl

179

name: str

180

description: str | None = None

181

mimeType: str | None = None

182

183

class ResourceTemplate(BaseModel):

184

"""Resource template with URI pattern."""

185

uriTemplate: str

186

name: str

187

description: str | None = None

188

mimeType: str | None = None

189

190

class ListResourcesRequest(BaseModel):

191

"""List available resources request."""

192

method: Literal["resources/list"] = "resources/list"

193

params: dict[str, Any] | None = None

194

195

class ListResourcesResult(BaseModel):

196

"""List available resources response."""

197

resources: list[Resource]

198

nextCursor: str | None = None

199

200

class ListResourceTemplatesResult(BaseModel):

201

"""List available resource templates response."""

202

resourceTemplates: list[ResourceTemplate]

203

nextCursor: str | None = None

204

205

class ReadResourceRequest(BaseModel):

206

"""Read resource content request."""

207

method: Literal["resources/read"] = "resources/read"

208

params: dict[str, Any]

209

210

class ReadResourceResult(BaseModel):

211

"""Read resource content response."""

212

contents: list[ContentBlock]

213

214

class SubscribeRequest(BaseModel):

215

"""Subscribe to resource updates request."""

216

method: Literal["resources/subscribe"] = "resources/subscribe"

217

params: dict[str, Any]

218

219

class UnsubscribeRequest(BaseModel):

220

"""Unsubscribe from resource updates request."""

221

method: Literal["resources/unsubscribe"] = "resources/unsubscribe"

222

params: dict[str, Any]

223

224

class ResourceUpdatedNotification(BaseModel):

225

"""Resource update notification."""

226

method: Literal["notifications/resources/updated"] = "notifications/resources/updated"

227

params: dict[str, Any]

228

```

229

230

### Content Types

231

232

Types for different content formats and data structures.

233

234

```python { .api }

235

class TextContent(BaseModel):

236

"""Text content block."""

237

type: Literal["text"] = "text"

238

text: str

239

240

class ImageContent(BaseModel):

241

"""Image content block."""

242

type: Literal["image"] = "image"

243

data: str # Base64 encoded image data

244

mimeType: str

245

246

class AudioContent(BaseModel):

247

"""Audio content block."""

248

type: Literal["audio"] = "audio"

249

data: str # Base64 encoded audio data

250

mimeType: str

251

252

class EmbeddedResource(BaseModel):

253

"""Embedded resource content."""

254

type: Literal["resource"] = "resource"

255

resource: ResourceContents

256

257

class ResourceLink(BaseModel):

258

"""Resource link reference."""

259

type: Literal["resource"] = "resource"

260

uri: AnyUrl

261

262

class ResourceContents(BaseModel):

263

"""Resource content wrapper."""

264

uri: AnyUrl

265

mimeType: str | None = None

266

text: str | None = None

267

blob: str | None = None # Base64 encoded binary data

268

269

ContentBlock = TextContent | ImageContent | AudioContent | EmbeddedResource | ResourceLink

270

```

271

272

### Prompt Operations

273

274

Types for prompt templates, retrieval, and message handling.

275

276

```python { .api }

277

class Prompt(BaseModel):

278

"""Prompt template definition."""

279

name: str

280

description: str | None = None

281

arguments: list[PromptArgument] | None = None

282

283

class PromptArgument(BaseModel):

284

"""Prompt template argument."""

285

name: str

286

description: str | None = None

287

required: bool | None = None

288

289

class ListPromptsRequest(BaseModel):

290

"""List available prompts request."""

291

method: Literal["prompts/list"] = "prompts/list"

292

params: dict[str, Any] | None = None

293

294

class ListPromptsResult(BaseModel):

295

"""List available prompts response."""

296

prompts: list[Prompt]

297

nextCursor: str | None = None

298

299

class GetPromptRequest(BaseModel):

300

"""Get prompt content request."""

301

method: Literal["prompts/get"] = "prompts/get"

302

params: dict[str, Any]

303

304

class GetPromptResult(BaseModel):

305

"""Get prompt content response."""

306

description: str | None = None

307

messages: list[PromptMessage]

308

309

class PromptMessage(BaseModel):

310

"""Prompt message with role and content."""

311

role: Role

312

content: ContentBlock

313

```

314

315

### Progress and Notifications

316

317

Types for progress tracking and server notifications.

318

319

```python { .api }

320

class ProgressNotification(BaseModel):

321

"""Progress update notification."""

322

method: Literal["notifications/progress"] = "notifications/progress"

323

params: ProgressNotificationParams

324

325

class ProgressNotificationParams(BaseModel):

326

"""Progress notification parameters."""

327

progressToken: ProgressToken

328

progress: float

329

total: float | None = None

330

331

class LoggingMessageNotification(BaseModel):

332

"""Logging message notification."""

333

method: Literal["notifications/message"] = "notifications/message"

334

params: dict[str, Any]

335

336

class LoggingLevel(str, Enum):

337

"""Logging level enumeration."""

338

DEBUG = "debug"

339

INFO = "info"

340

NOTICE = "notice"

341

WARNING = "warning"

342

ERROR = "error"

343

CRITICAL = "critical"

344

ALERT = "alert"

345

EMERGENCY = "emergency"

346

347

class SetLevelRequest(BaseModel):

348

"""Set logging level request."""

349

method: Literal["logging/setLevel"] = "logging/setLevel"

350

params: dict[str, Any]

351

```

352

353

### Sampling and LLM Integration

354

355

Types for LLM sampling requests and message creation.

356

357

```python { .api }

358

class CreateMessageRequest(BaseModel):

359

"""Create LLM message request."""

360

method: Literal["sampling/createMessage"] = "sampling/createMessage"

361

params: dict[str, Any]

362

363

class CreateMessageResult(BaseModel):

364

"""Create LLM message response."""

365

role: Role

366

content: ContentBlock

367

model: str

368

stopReason: StopReason | None = None

369

370

class SamplingMessage(BaseModel):

371

"""Message for LLM sampling."""

372

role: Role

373

content: ContentBlock

374

375

class ModelPreferences(BaseModel):

376

"""LLM model preferences."""

377

hints: list[ModelHint] | None = None

378

costPriority: float | None = None

379

speedPriority: float | None = None

380

intelligencePriority: float | None = None

381

382

class ModelHint(BaseModel):

383

"""LLM model hint."""

384

name: str | None = None

385

386

class StopReason(str, Enum):

387

"""Sampling stop reason."""

388

endTurn = "endTurn"

389

stopSequence = "stopSequence"

390

maxTokens = "maxTokens"

391

```

392

393

### Completions

394

395

Types for completion suggestions and text completions.

396

397

```python { .api }

398

class CompleteRequest(BaseModel):

399

"""Completion request."""

400

method: Literal["completion/complete"] = "completion/complete"

401

params: dict[str, Any]

402

403

class CompleteResult(BaseModel):

404

"""Completion response."""

405

completion: Completion

406

407

class Completion(BaseModel):

408

"""Completion suggestion."""

409

values: list[str]

410

total: int | None = None

411

hasMore: bool | None = None

412

413

class CompletionArgument(BaseModel):

414

"""Completion argument context."""

415

name: str

416

value: str

417

418

class CompletionReference(BaseModel):

419

"""Reference for completion requests."""

420

type: str # "resource" or "prompt"

421

uri: str | None = None

422

name: str | None = None

423

```

424

425

### Type Unions

426

427

Union types for protocol messages and results.

428

429

```python { .api }

430

# Client-side unions

431

ClientRequest = (

432

InitializeRequest |

433

ListToolsRequest |

434

CallToolRequest |

435

ListResourcesRequest |

436

ReadResourceRequest |

437

SubscribeRequest |

438

UnsubscribeRequest |

439

ListPromptsRequest |

440

GetPromptRequest |

441

SetLevelRequest |

442

CompleteRequest

443

)

444

445

ClientResult = (

446

InitializeResult |

447

ListToolsResult |

448

CallToolResult |

449

ListResourcesResult |

450

ReadResourceResult |

451

ListPromptsResult |

452

GetPromptResult |

453

CompleteResult

454

)

455

456

ClientNotification = (

457

InitializedNotification |

458

ProgressNotification |

459

LoggingMessageNotification

460

)

461

462

# Server-side unions

463

ServerRequest = CreateMessageRequest

464

ServerResult = CreateMessageResult

465

ServerNotification = ResourceUpdatedNotification

466

```

467

468

### Exception Types

469

470

Exception classes for MCP protocol errors.

471

472

```python { .api }

473

class McpError(Exception):

474

"""MCP protocol exception."""

475

476

def __init__(

477

self,

478

message: str,

479

code: int = INTERNAL_ERROR,

480

data: Any | None = None

481

):

482

"""

483

Initialize MCP error.

484

485

Parameters:

486

- message: Error message

487

- code: Error code (JSON-RPC error code)

488

- data: Additional error data

489

"""

490

super().__init__(message)

491

self.code = code

492

self.data = data

493

494

def to_error_data(self) -> ErrorData:

495

"""Convert to ErrorData structure."""

496

return ErrorData(

497

code=self.code,

498

message=str(self),

499

data=self.data

500

)

501

```

502

503

## Usage Examples

504

505

### Type-Safe Tool Definition

506

507

```python

508

from mcp import Tool, CallToolResult, TextContent

509

from pydantic import BaseModel

510

511

# Define tool input schema using Pydantic

512

class CalculatorInput(BaseModel):

513

operation: str

514

a: float

515

b: float

516

517

# Create tool with proper typing

518

calculator_tool = Tool(

519

name="calculator",

520

description="Perform basic math operations",

521

inputSchema=CalculatorInput.model_json_schema()

522

)

523

524

# Type-safe tool handler

525

async def handle_calculator(name: str, arguments: dict) -> CallToolResult:

526

# Validate input using Pydantic

527

input_data = CalculatorInput.model_validate(arguments)

528

529

# Perform calculation

530

if input_data.operation == "add":

531

result = input_data.a + input_data.b

532

elif input_data.operation == "multiply":

533

result = input_data.a * input_data.b

534

else:

535

raise ValueError(f"Unknown operation: {input_data.operation}")

536

537

# Return typed result

538

return CallToolResult(

539

content=[TextContent(type="text", text=str(result))]

540

)

541

```

542

543

### Custom Content Types

544

545

```python

546

from mcp import ContentBlock, BaseModel

547

from typing import Literal

548

549

# Define custom content type

550

class ChartContent(BaseModel):

551

"""Custom chart content type."""

552

type: Literal["chart"] = "chart"

553

chart_type: str # "bar", "line", "pie", etc.

554

data: dict[str, Any]

555

options: dict[str, Any] | None = None

556

557

# Use in tool responses

558

async def generate_chart() -> list[ContentBlock]:

559

chart = ChartContent(

560

chart_type="bar",

561

data={

562

"labels": ["A", "B", "C"],

563

"values": [10, 20, 15]

564

},

565

options={"title": "Sample Chart"}

566

)

567

568

return [chart]

569

```