or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-modelcontextprotocol--sdk

TypeScript SDK for implementing the Model Context Protocol, enabling developers to build MCP servers and clients with support for multiple transports, tools, resources, prompts, and authentication

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@modelcontextprotocol/sdk@1.20.x

To install, run

npx @tessl/cli install tessl/npm-modelcontextprotocol--sdk@1.20.0

0

# Model Context Protocol TypeScript SDK

1

2

TypeScript implementation for building MCP servers and clients. Enables exposing context (resources, tools, prompts) to LLMs with transports, OAuth, sampling, and elicitation.

3

4

**Package**: `@modelcontextprotocol/sdk@1.20.2` | `npm install @modelcontextprotocol/sdk` | Protocol: 2025-06-18, 2025-03-26, 2024-11-05, 2024-10-07

5

6

## Quick Start

7

8

**Server:**

9

```typescript

10

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

11

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

12

import { z } from 'zod';

13

14

const server = new McpServer({ name: 'my-server', version: '1.0.0' });

15

16

server.registerTool('add', {

17

title: 'Addition Tool',

18

description: 'Add two numbers',

19

inputSchema: { a: z.number(), b: z.number() },

20

outputSchema: { result: z.number() }

21

}, async ({ a, b }) => ({

22

content: [{ type: 'text', text: String(a + b) }],

23

structuredContent: { result: a + b }

24

}));

25

26

await server.connect(new StdioServerTransport());

27

```

28

29

**Client:**

30

```typescript

31

import { Client } from '@modelcontextprotocol/sdk/client/index.js';

32

import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

33

34

const client = new Client({ name: 'my-client', version: '1.0.0' });

35

await client.connect(new StdioClientTransport({ command: 'node', args: ['server.js'] }));

36

37

const { tools } = await client.listTools();

38

const result = await client.callTool({ name: 'add', arguments: { a: 5, b: 3 } });

39

console.log(result.structuredContent); // { result: 8 }

40

```

41

42

## Core Concepts

43

44

**Server Primitives:**

45

| Primitive | Purpose | Control | Use Case |

46

|-----------|---------|---------|----------|

47

| **Tools** | Model actions | Model | Computations, APIs, side effects |

48

| **Resources** | App data | App | Config, files, data |

49

| **Prompts** | Templates | User | Slash commands, starters |

50

51

**Transports:**

52

| Transport | Use Case | Characteristics |

53

|-----------|----------|----------------|

54

| Stdio | Local/CLI | Simple, fast |

55

| StreamableHTTP | Remote/web | Stateless, scalable |

56

| WebSocket | Real-time | Low latency |

57

| InMemory | Testing | Isolated |

58

59

## Common Patterns

60

61

### File System Server

62

```typescript

63

import fs from 'fs/promises';

64

65

server.registerResource('readme', 'file:///project/README.md', {

66

title: 'Project README', mimeType: 'text/markdown'

67

}, async (uri) => ({

68

contents: [{ uri: uri.href, mimeType: 'text/markdown', text: await fs.readFile('/project/README.md', 'utf-8') }]

69

}));

70

71

server.registerTool('list-files', {

72

description: 'List files in a directory',

73

inputSchema: { path: z.string() }

74

}, async ({ path }) => ({

75

content: [{ type: 'text', text: (await fs.readdir(path)).join('\n') }]

76

}));

77

```

78

79

### API Integration Server

80

```typescript

81

server.registerTool('fetch-api', {

82

description: 'Fetch from external API',

83

inputSchema: { url: z.string().url(), method: z.enum(['GET', 'POST']).optional() }

84

}, async ({ url, method = 'GET' }) => {

85

const response = await fetch(url, { method });

86

const data = await response.json();

87

return { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data };

88

});

89

```

90

91

### Database Server

92

```typescript

93

import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';

94

95

server.registerResource('user', new ResourceTemplate('db://users/{userId}', {}), {

96

title: 'User Profile'

97

}, async (uri, { userId }) => {

98

const user = await db.getUser(userId);

99

return { contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(user) }] };

100

});

101

102

server.registerTool('query-users', {

103

description: 'Query users by criteria',

104

inputSchema: { role: z.string().optional(), active: z.boolean().optional() }

105

}, async (args) => {

106

const users = await db.queryUsers(args);

107

return {

108

content: users.map(u => ({ type: 'text', text: `${u.name} (${u.email})` })),

109

structuredContent: { users }

110

};

111

});

112

```

113

114

## API Reference

115

116

- **[Server Tools](./server-tools.md)** - Register model-controlled actions with validation

117

- **[Server Resources](./server-resources.md)** - Expose application data (static & dynamic)

118

- **[Server Prompts](./server-prompts.md)** - Reusable conversation templates

119

- **[Server Advanced](./server-advanced.md)** - Sampling, elicitation, dynamic capabilities

120

- **[Client API](./client.md)** - Consume server capabilities

121

- **[Transports](./transports.md)** - Communication protocols (Stdio, HTTP, WebSocket)

122

- **[Authentication](./authentication.md)** - OAuth 2.0 implementation

123

- **[Types](./types.md)** - TypeScript type definitions

124

125

## Critical Patterns

126

127

### Validation with Zod

128

```typescript

129

server.registerTool('safe-add', {

130

inputSchema: { a: z.number().min(0).max(1000), b: z.number().min(0).max(1000) },

131

outputSchema: { result: z.number() }

132

}, async ({ a, b }) => ({

133

content: [{ type: 'text', text: String(a + b) }],

134

structuredContent: { result: a + b }

135

}));

136

```

137

138

### Structured Output (Required when outputSchema defined)

139

```typescript

140

return {

141

content: [{ type: 'text', text: JSON.stringify(output) }],

142

structuredContent: output // Must match outputSchema

143

};

144

```

145

146

### Error Handling

147

```typescript

148

try {

149

const result = await performOperation(id);

150

return { content: [{ type: 'text', text: `Success: ${result}` }], structuredContent: { success: true, result } };

151

} catch (error) {

152

return { content: [{ type: 'text', text: `Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };

153

}

154

```

155

156

## Common Issues

157

158

**Tools not appearing:** Call `server.connect()` after registration; verify client capabilities.

159

**Transport errors:** Verify server is listening; check URLs/credentials.

160

**Validation errors:** Ensure Zod schemas match; `structuredContent` must match `outputSchema`.

161

162

## Essential Imports

163

164

```typescript

165

// Server

166

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

167

import { StdioServerTransport, StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

168

169

// Client

170

import { Client } from '@modelcontextprotocol/sdk/client/index.js';

171

import { StdioClientTransport, StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

172

173

// Types

174

import type { Tool, Resource, Prompt, CallToolResult, ReadResourceResult } from '@modelcontextprotocol/sdk/types.js';

175

176

// Error handling

177

import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';

178

throw new McpError(ErrorCode.InvalidParams, 'Message', { field: 'value' });

179

```

180