-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmcp-documentation.txt
5179 lines (4167 loc) · 144 KB
/
mcp-documentation.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Directory structure:
└── modelcontextprotocol-docs
├── docs
│ ├── tools
│ │ ├── debugging.mdx
│ │ └── inspector.mdx
│ └── concepts
│ ├── resources.mdx
│ ├── architecture.mdx
│ ├── transports.mdx
│ ├── sampling.mdx
│ ├── prompts.mdx
│ └── tools.mdx
├── .prettierignore
├── examples.mdx
├── snippets
│ └── snippet-intro.mdx
├── introduction.mdx
├── logo
├── images
├── tutorials
│ ├── building-a-client.mdx
│ ├── building-mcp-with-llms.mdx
│ └── building-a-client-node.mdx
├── CODE_OF_CONDUCT.md
├── clients.mdx
├── mint.json
├── README.md
└── quickstart.mdx
================================================
File: /docs/tools/debugging.mdx
================================================
---
title: Debugging
description: A comprehensive guide to debugging Model Context Protocol (MCP) integrations
---
Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.
<Info>
This guide is for macOS. Guides for other platforms are coming soon.
</Info>
## Debugging tools overview
MCP provides several tools for debugging at different levels:
1. **MCP Inspector**
- Interactive debugging interface
- Direct server testing
- See the [Inspector guide](/docs/tools/inspector) for details
2. **Claude Desktop Developer Tools**
- Integration testing
- Log collection
- Chrome DevTools integration
3. **Server Logging**
- Custom logging implementations
- Error tracking
- Performance monitoring
## Debugging in Claude Desktop
### Checking server status
The Claude.app interface provides basic server status information:
1. Click the <img src="/images/claude-desktop-mcp-plug-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
- Connected servers
- Available prompts and resources
2. Click the <img src="/images/claude-desktop-mcp-hammer-icon.svg" style={{display: 'inline', margin: 0, height: '1.3em'}} /> icon to view:
- Tools made available to the model
### Viewing logs
Review detailed MCP logs from Claude Desktop:
```bash
# Follow logs in real-time
tail -n 20 -f ~/Library/Logs/Claude/mcp*.log
```
The logs capture:
- Server connection events
- Configuration issues
- Runtime errors
- Message exchanges
### Using Chrome DevTools
Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:
1. Enable DevTools:
```bash
jq '.allowDevTools = true' ~/Library/Application\ Support/Claude/developer_settings.json > tmp.json \
&& mv tmp.json ~/Library/Application\ Support/Claude/developer_settings.json
```
2. Open DevTools: `Command-Option-Shift-i`
Note: You'll see two DevTools windows:
- Main content window
- App title bar window
Use the Console panel to inspect client-side errors.
Use the Network panel to inspect:
- Message payloads
- Connection timing
## Common issues
### Environment variables
MCP servers inherit only a subset of environment variables automatically, like `USER`, `HOME`, and `PATH`.
To override the default variables or provide your own, you can specify an `env` key in `claude_desktop_config.json`:
```json
{
"myserver": {
"command": "mcp-server-myapp",
"env": {
"MYAPP_API_KEY": "some_key",
}
}
}
```
### Server initialization
Common initialization problems:
1. **Path Issues**
- Incorrect server executable path
- Missing required files
- Permission problems
2. **Configuration Errors**
- Invalid JSON syntax
- Missing required fields
- Type mismatches
3. **Environment Problems**
- Missing environment variables
- Incorrect variable values
- Permission restrictions
### Connection problems
When servers fail to connect:
1. Check Claude Desktop logs
2. Verify server process is running
3. Test standalone with [Inspector](/docs/tools/inspector)
4. Verify protocol compatibility
## Implementing logging
### Server-side logging
When building a server that uses the local stdio [transport](/docs/concepts/transports), all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically.
<Warning>
Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.
</Warning>
For all [transports](/docs/concepts/transports), you can also provide logging to the client by sending a log message notification:
<Tabs>
<Tab title="Python">
```python
server.request_context.session.send_log_message(
level="info",
data="Server started successfully",
)
```
</Tab>
<Tab title="TypeScript">
```typescript
server.sendLoggingMessage({
level: "info",
data: "Server started successfully",
});
```
</Tab>
</Tabs>
Important events to log:
- Initialization steps
- Resource access
- Tool execution
- Error conditions
- Performance metrics
### Client-side logging
In client applications:
1. Enable debug logging
2. Monitor network traffic
3. Track message exchanges
4. Record error states
## Debugging workflow
### Development cycle
1. Initial Development
- Use [Inspector](/docs/tools/inspector) for basic testing
- Implement core functionality
- Add logging points
2. Integration Testing
- Test in Claude Desktop
- Monitor logs
- Check error handling
### Testing changes
To test changes efficiently:
- **Configuration changes**: Restart Claude Desktop
- **Server code changes**: Use Command-R to reload
- **Quick iteration**: Use [Inspector](/docs/tools/inspector) during development
## Best practices
### Logging strategy
1. **Structured Logging**
- Use consistent formats
- Include context
- Add timestamps
- Track request IDs
2. **Error Handling**
- Log stack traces
- Include error context
- Track error patterns
- Monitor recovery
3. **Performance Tracking**
- Log operation timing
- Monitor resource usage
- Track message sizes
- Measure latency
### Security considerations
When debugging:
1. **Sensitive Data**
- Sanitize logs
- Protect credentials
- Mask personal information
2. **Access Control**
- Verify permissions
- Check authentication
- Monitor access patterns
## Getting help
When encountering issues:
1. **First Steps**
- Check server logs
- Test with [Inspector](/docs/tools/inspector)
- Review configuration
- Verify environment
2. **Support Channels**
- GitHub issues
- GitHub discussions
3. **Providing Information**
- Log excerpts
- Configuration files
- Steps to reproduce
- Environment details
## Next steps
<CardGroup cols={2}>
<Card
title="MCP Inspector"
icon="magnifying-glass"
href="/docs/tools/inspector"
>
Learn to use the MCP Inspector
</Card>
</CardGroup>
================================================
File: /docs/tools/inspector.mdx
================================================
---
title: Inspector
description: In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers
---
The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](/docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities.
## Getting started
### Installation and basic usage
The Inspector runs directly through `npx` without requiring installation:
```bash
npx @modelcontextprotocol/inspector <command>
```
```bash
npx @modelcontextprotocol/inspector <command> <arg1> <arg2>
```
#### Inspecting servers from NPM or PyPi
A common way to start server packages from [NPM](https://npmjs.com) or [PyPi](https://pypi.com).
<Tabs>
<Tab title="NPM package">
```bash
npx -y @modelcontextprotocol/inspector npx <package-name> <args>
# For example
npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb
```
</Tab>
<Tab title="PyPi package">
```bash
npx @modelcontextprotocol/inspector uvx <package-name> <args>
# For example
npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git
```
</Tab>
</Tabs>
#### Inspecting locally developed servers
To inspect servers locally developed or downloaded as a repository, the most common
way is:
<Tabs>
<Tab title="TypeScript">
```bash
npx @modelcontextprotocol/inspector node path/to/server/index.js args...
```
</Tab>
<Tab title="Python">
```bash
npx @modelcontextprotocol/inspector \
uv \
--directory path/to/server \
run \
package-name \
args...
```
</Tab>
</Tabs>
Please carefully read any attached README for the most accurate instructions.
## Feature overview
<Frame caption="The MCP Inspector interface">
<img src="/images/mcp-inspector.png" />
</Frame>
The Inspector provides several features for interacting with your MCP server:
### Server connection pane
- Allows selecting the [transport](/docs/concepts/transports) for connecting to the server
- For local servers, supports customizing the command-line arguments and environment
### Resources tab
- Lists all available resources
- Shows resource metadata (MIME types, descriptions)
- Allows resource content inspection
- Supports subscription testing
### Prompts tab
- Displays available prompt templates
- Shows prompt arguments and descriptions
- Enables prompt testing with custom arguments
- Previews generated messages
### Tools tab
- Lists available tools
- Shows tool schemas and descriptions
- Enables tool testing with custom inputs
- Displays tool execution results
### Notifications pane
- Presents all logs recorded from the server
- Shows notifications received from the server
## Best practices
### Development workflow
1. Start Development
- Launch Inspector with your server
- Verify basic connectivity
- Check capability negotiation
2. Iterative testing
- Make server changes
- Rebuild the server
- Reconnect the Inspector
- Test affected features
- Monitor messages
3. Test edge cases
- Invalid inputs
- Missing prompt arguments
- Concurrent operations
- Verify error handling and error responses
## Next steps
<CardGroup cols={2}>
<Card
title="Inspector Repository"
icon="github"
href="https://github.com/modelcontextprotocol/inspector"
>
Check out the MCP Inspector source code
</Card>
<Card
title="Debugging Guide"
icon="bug"
href="/docs/tools/debugging"
>
Learn about broader debugging strategies
</Card>
</CardGroup>
================================================
File: /docs/concepts/resources.mdx
================================================
---
title: "Resources"
description: "Expose data and content from your servers to LLMs"
---
Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.
<Note>
Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used.
Different MCP clients may handle resources differently. For example:
- Claude Desktop currently requires users to explicitly select resources before they can be used
- Other clients might automatically select resources based on heuristics
- Some implementations may even allow the AI model itself to determine which resources to use
Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a **model-controlled** primitive such as [Tools](./tools).
</Note>
## Overview
Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
- File contents
- Database records
- API responses
- Live system data
- Screenshots and images
- Log files
- And more
Each resource is identified by a unique URI and can contain either text or binary data.
## Resource URIs
Resources are identified using URIs that follow this format:
```
[protocol]://[host]/[path]
```
For example:
- `file:///home/user/documents/report.pdf`
- `postgres://database/customers/schema`
- `screen://localhost/display1`
The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
## Resource types
Resources can contain two types of content:
### Text resources
Text resources contain UTF-8 encoded text data. These are suitable for:
- Source code
- Configuration files
- Log files
- JSON/XML data
- Plain text
### Binary resources
Binary resources contain raw binary data encoded in base64. These are suitable for:
- Images
- PDFs
- Audio files
- Video files
- Other non-text formats
## Resource discovery
Clients can discover available resources through two main methods:
### Direct resources
Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes:
```typescript
{
uri: string; // Unique identifier for the resource
name: string; // Human-readable name
description?: string; // Optional description
mimeType?: string; // Optional MIME type
}
```
### Resource templates
For dynamic resources, servers can expose [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) that clients can use to construct valid resource URIs:
```typescript
{
uriTemplate: string; // URI template following RFC 6570
name: string; // Human-readable name for this type
description?: string; // Optional description
mimeType?: string; // Optional MIME type for all matching resources
}
```
## Reading resources
To read a resource, clients make a `resources/read` request with the resource URI.
The server responds with a list of resource contents:
```typescript
{
contents: [
{
uri: string; // The URI of the resource
mimeType?: string; // Optional MIME type
// One of:
text?: string; // For text resources
blob?: string; // For binary resources (base64 encoded)
}
]
}
```
<Tip>
Servers may return multiple resources in response to one `resources/read` request. This could be used, for example, to return a list of files inside a directory when the directory is read.
</Tip>
## Resource updates
MCP supports real-time updates for resources through two mechanisms:
### List changes
Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification.
### Content changes
Clients can subscribe to updates for specific resources:
1. Client sends `resources/subscribe` with resource URI
2. Server sends `notifications/resources/updated` when the resource changes
3. Client can fetch latest content with `resources/read`
4. Client can unsubscribe with `resources/unsubscribe`
## Example implementation
Here's a simple example of implementing resource support in an MCP server:
<Tabs>
<Tab title="TypeScript">
```typescript
const server = new Server({
name: "example-server",
version: "1.0.0"
}, {
capabilities: {
resources: {}
}
});
// List available resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "file:///logs/app.log",
name: "Application Logs",
mimeType: "text/plain"
}
]
};
});
// Read resource contents
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
if (uri === "file:///logs/app.log") {
const logContents = await readLogFile();
return {
contents: [
{
uri,
mimeType: "text/plain",
text: logContents
}
]
};
}
throw new Error("Resource not found");
});
```
</Tab>
<Tab title="Python">
```python
app = Server("example-server")
@app.list_resources()
async def list_resources() -> list[types.Resource]:
return [
types.Resource(
uri="file:///logs/app.log",
name="Application Logs",
mimeType="text/plain"
)
]
@app.read_resource()
async def read_resource(uri: AnyUrl) -> str:
if str(uri) == "file:///logs/app.log":
log_contents = await read_log_file()
return log_contents
raise ValueError("Resource not found")
# Start server
async with stdio_server() as streams:
await app.run(
streams[0],
streams[1],
app.create_initialization_options()
)
```
</Tab>
</Tabs>
## Best practices
When implementing resource support:
1. Use clear, descriptive resource names and URIs
2. Include helpful descriptions to guide LLM understanding
3. Set appropriate MIME types when known
4. Implement resource templates for dynamic content
5. Use subscriptions for frequently changing resources
6. Handle errors gracefully with clear error messages
7. Consider pagination for large resource lists
8. Cache resource contents when appropriate
9. Validate URIs before processing
10. Document your custom URI schemes
## Security considerations
When exposing resources:
- Validate all resource URIs
- Implement appropriate access controls
- Sanitize file paths to prevent directory traversal
- Be cautious with binary data handling
- Consider rate limiting for resource reads
- Audit resource access
- Encrypt sensitive data in transit
- Validate MIME types
- Implement timeouts for long-running reads
- Handle resource cleanup appropriately
================================================
File: /docs/concepts/architecture.mdx
================================================
---
title: "Core architecture"
description: "Understand how MCP connects clients, servers, and LLMs"
---
The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.
## Overview
MCP follows a client-server architecture where:
- **Hosts** are LLM applications (like Claude Desktop or IDEs) that initiate connections
- **Clients** maintain 1:1 connections with servers, inside the host application
- **Servers** provide context, tools, and prompts to clients
```mermaid
flowchart LR
subgraph " Host (e.g., Claude Desktop) "
client1[MCP Client]
client2[MCP Client]
end
subgraph "Server Process"
server1[MCP Server]
end
subgraph "Server Process"
server2[MCP Server]
end
client1 <-->|Transport Layer| server1
client2 <-->|Transport Layer| server2
```
## Core components
### Protocol layer
The protocol layer handles message framing, request/response linking, and high-level communication patterns.
<Tabs>
<Tab title="TypeScript">
```typescript
class Protocol<Request, Notification, Result> {
// Handle incoming requests
setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
// Handle incoming notifications
setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
// Send requests and await responses
request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
// Send one-way notifications
notification(notification: Notification): Promise<void>
}
```
</Tab>
<Tab title="Python">
```python
class Session(BaseSession[RequestT, NotificationT, ResultT]):
async def send_request(
self,
request: RequestT,
result_type: type[Result]
) -> Result:
"""
Send request and wait for response. Raises McpError if response contains error.
"""
# Request handling implementation
async def send_notification(
self,
notification: NotificationT
) -> None:
"""Send one-way notification that doesn't expect response."""
# Notification handling implementation
async def _received_request(
self,
responder: RequestResponder[ReceiveRequestT, ResultT]
) -> None:
"""Handle incoming request from other side."""
# Request handling implementation
async def _received_notification(
self,
notification: ReceiveNotificationT
) -> None:
"""Handle incoming notification from other side."""
# Notification handling implementation
```
</Tab>
</Tabs>
Key classes include:
* `Protocol`
* `Client`
* `Server`
### Transport layer
The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
1. **Stdio transport**
- Uses standard input/output for communication
- Ideal for local processes
2. **HTTP with SSE transport**
- Uses Server-Sent Events for server-to-client messages
- HTTP POST for client-to-server messages
All transports use [JSON-RPC](https://www.jsonrpc.org/) 2.0 to exchange messages. See the [specification](https://spec.modelcontextprotocol.io) for detailed information about the Model Context Protocol message format.
### Message types
MCP has these main types of messages:
1. **Requests** expect a response from the other side:
```typescript
interface Request {
method: string;
params?: { ... };
}
```
2. **Notifications** are one-way messages that don't expect a response:
```typescript
interface Notification {
method: string;
params?: { ... };
}
```
3. **Results** are successful responses to requests:
```typescript
interface Result {
[key: string]: unknown;
}
```
4. **Errors** indicate that a request failed:
```typescript
interface Error {
code: number;
message: string;
data?: unknown;
}
```
## Connection lifecycle
### 1. Initialization
```mermaid
sequenceDiagram
participant Client
participant Server
Client->>Server: initialize request
Server->>Client: initialize response
Client->>Server: initialized notification
Note over Client,Server: Connection ready for use
```
1. Client sends `initialize` request with protocol version and capabilities
2. Server responds with its protocol version and capabilities
3. Client sends `initialized` notification as acknowledgment
4. Normal message exchange begins
### 2. Message exchange
After initialization, the following patterns are supported:
- **Request-Response**: Client or server sends requests, the other responds
- **Notifications**: Either party sends one-way messages
### 3. Termination
Either party can terminate the connection:
- Clean shutdown via `close()`
- Transport disconnection
- Error conditions
## Error handling
MCP defines these standard error codes:
```typescript
enum ErrorCode {
// Standard JSON-RPC error codes
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603
}
```
SDKs and applications can define their own error codes above -32000.
Errors are propagated through:
- Error responses to requests
- Error events on transports
- Protocol-level error handlers
## Implementation example
Here's a basic example of implementing an MCP server:
<Tabs>
<Tab title="TypeScript">
```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "example-server",
version: "1.0.0"
}, {
capabilities: {
resources: {}
}
});
// Handle requests
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "example://resource",
name: "Example Resource"
}
]
};
});
// Connect transport
const transport = new StdioServerTransport();
await server.connect(transport);
```
</Tab>
<Tab title="Python">
```python
import asyncio
import mcp.types as types
from mcp.server import Server
from mcp.server.stdio import stdio_server
app = Server("example-server")
@app.list_resources()
async def list_resources() -> list[types.Resource]:
return [
types.Resource(
uri="example://resource",
name="Example Resource"
)
]
async def main():
async with stdio_server() as streams:
await app.run(
streams[0],
streams[1],
app.create_initialization_options()
)
if __name__ == "__main__":
asyncio.run(main)
```
</Tab>
</Tabs>
## Best practices
### Transport selection
1. **Local communication**
- Use stdio transport for local processes
- Efficient for same-machine communication
- Simple process management
2. **Remote communication**
- Use SSE for scenarios requiring HTTP compatibility
- Consider security implications including authentication and authorization
### Message handling
1. **Request processing**
- Validate inputs thoroughly
- Use type-safe schemas