Rename "transport" to "transports"

This commit is contained in:
Justin Spahr-Summers 2024-11-21 11:52:50 +00:00
commit 3113c1a09c
No known key found for this signature in database

View file

@ -0,0 +1,278 @@
---
title: "Transports"
description: "Learn about MCP's communication mechanisms"
---
Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.
## How transports work
An MCP transport is built on a simple message-passing architecture where both clients and servers can send messages to each other. The transport layer is responsible for:
- Establishing connections
- Sending messages
- Receiving messages
- Handling connection lifecycles
- Managing errors
- Ensuring reliable delivery
## Available transport types
MCP supports three main transport types:
### Standard input/output (stdio)
The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.
```typescript
// Server implementation
const server = new Server({
name: "example-server",
version: "1.0.0"
});
const transport = new StdioServerTransport();
await server.connect(transport);
// Client implementation
const client = new Client({
name: "example-client",
version: "1.0.0"
});
const transport = new StdioClientTransport({
command: "./server",
args: ["--option", "value"]
});
await client.connect(transport);
```
### WebSocket
WebSocket transport provides real-time, bidirectional communication over a persistent connection. This is ideal for web-based applications that need low-latency messaging.
```typescript
// Server implementation
const server = new Server({
name: "example-server",
version: "1.0.0"
});
const transport = new WebSocketServerTransport();
await server.connect(transport);
// Client implementation
const client = new Client({
name: "example-client",
version: "1.0.0"
});
const transport = new WebSocketClientTransport(
new URL("ws://localhost:3000")
);
await client.connect(transport);
```
### Server-sent events
SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. This is useful when WebSocket support isn't available.
```typescript
// Server implementation
const server = new Server({
name: "example-server",
version: "1.0.0"
});
const transport = new SSEServerTransport("/message", response);
await server.connect(transport);
// Client implementation
const client = new Client({
name: "example-client",
version: "1.0.0"
});
const transport = new SSEClientTransport(
new URL("http://localhost:3000/sse")
);
await client.connect(transport);
```
## Transport interface
All transport implementations must conform to the Transport interface:
```typescript
interface Transport {
// Start processing messages
start(): Promise<void>;
// Send a JSON-RPC message
send(message: JSONRPCMessage): Promise<void>;
// Close the connection
close(): Promise<void>;
// Callbacks
onclose?: () => void;
onerror?: (error: Error) => void;
onmessage?: (message: JSONRPCMessage) => void;
}
```
## Message format
Messages sent over MCP transport follow the JSON-RPC 2.0 specification. There are three types of messages:
### Requests
```typescript
{
jsonrpc: "2.0",
id: number | string,
method: string,
params?: object
}
```
### Responses
```typescript
{
jsonrpc: "2.0",
id: number | string,
result?: object,
error?: {
code: number,
message: string,
data?: unknown
}
}
```
### Notifications
```typescript
{
jsonrpc: "2.0",
method: string,
params?: object
}
```
## Error handling
Transport implementations should handle various error scenarios:
1. Connection errors
2. Message parsing errors
3. Protocol errors
4. Network timeouts
5. Resource cleanup
Example error handling:
```typescript
class ExampleTransport implements Transport {
async start() {
try {
// Connection logic
} catch (error) {
this.onerror?.(new Error(`Failed to connect: ${error}`));
throw error;
}
}
async send(message: JSONRPCMessage) {
try {
// Sending logic
} catch (error) {
this.onerror?.(new Error(`Failed to send message: ${error}`));
throw error;
}
}
}
```
## Best practices
When implementing or using MCP transport:
1. Handle connection lifecycle properly
2. Implement proper error handling
3. Clean up resources on connection close
4. Use appropriate timeouts
5. Validate messages before sending
6. Log transport events for debugging
7. Implement reconnection logic when appropriate
8. Handle backpressure in message queues
9. Monitor connection health
10. Implement proper security measures
## Security considerations
When implementing transport:
### Authentication and authorization
- Implement proper authentication mechanisms
- Validate client credentials
- Use secure token handling
- Implement authorization checks
### Data security
- Use TLS for network transport
- Encrypt sensitive data
- Validate message integrity
- Implement message size limits
- Sanitize input data
### Network security
- Implement rate limiting
- Use appropriate timeouts
- Handle denial of service scenarios
- Monitor for unusual patterns
- Implement proper firewall rules
## Debugging transport
Tips for debugging transport issues:
1. Enable debug logging
2. Monitor message flow
3. Check connection states
4. Validate message formats
5. Test error scenarios
6. Use network analysis tools
7. Implement health checks
8. Monitor resource usage
9. Test edge cases
10. Use proper error tracking
## Transport selection guide
Choose the appropriate transport based on your needs:
### Use stdio when
- Building command-line tools
- Implementing local integrations
- Needing simple process communication
- Working with shell scripts
### Use WebSocket when
- Real-time updates are needed
- Low latency is required
- Bidirectional communication is necessary
- Working with web applications
### Use SSE when
- Only server-to-client streaming is needed
- WebSocket support is limited
- Working with restricted networks
- Implementing simple updates