418 lines
No EOL
9.1 KiB
Text
418 lines
No EOL
9.1 KiB
Text
---
|
|
title: "TypeScript class reference"
|
|
description: "Complete TypeScript SDK class documentation"
|
|
---
|
|
|
|
## Client classes
|
|
|
|
### Client
|
|
|
|
The main class for implementing MCP clients in TypeScript.
|
|
|
|
```typescript
|
|
import { Client } from "@modelcontextprotocol/sdk/client";
|
|
```
|
|
|
|
#### Constructor
|
|
```typescript
|
|
constructor(clientInfo: Implementation)
|
|
```
|
|
|
|
**Parameters:**
|
|
- `clientInfo`: Implementation object containing:
|
|
- `name`: string - Name of the client
|
|
- `version`: string - Version of the client
|
|
|
|
#### Methods
|
|
|
|
##### connect()
|
|
```typescript
|
|
async connect(transport: Transport): Promise<void>
|
|
```
|
|
Connects to a server using the provided transport.
|
|
|
|
##### request()
|
|
```typescript
|
|
async request<T extends AnyZodObject>(
|
|
request: ClientRequest,
|
|
resultSchema: T,
|
|
onprogress?: ProgressCallback
|
|
): Promise<z.infer<T>>
|
|
```
|
|
Sends a request to the server and waits for a response.
|
|
|
|
##### notification()
|
|
```typescript
|
|
async notification(notification: ClientNotification): Promise<void>
|
|
```
|
|
Sends a one-way notification to the server.
|
|
|
|
##### close()
|
|
```typescript
|
|
async close(): Promise<void>
|
|
```
|
|
Closes the connection to the server.
|
|
|
|
##### getServerCapabilities()
|
|
```typescript
|
|
getServerCapabilities(): ServerCapabilities | undefined
|
|
```
|
|
Returns the server's capabilities after connection.
|
|
|
|
##### getServerVersion()
|
|
```typescript
|
|
getServerVersion(): Implementation | undefined
|
|
```
|
|
Returns the server's version information after connection.
|
|
|
|
### Transport classes
|
|
|
|
#### StdioClientTransport
|
|
```typescript
|
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio";
|
|
```
|
|
|
|
##### Constructor
|
|
```typescript
|
|
constructor(params: StdioServerParameters)
|
|
```
|
|
|
|
**Parameters:**
|
|
- `params`: Object containing:
|
|
- `command`: string - Command to execute
|
|
- `args?`: string[] - Command arguments
|
|
- `env?`: object - Environment variables
|
|
|
|
#### SSEClientTransport
|
|
```typescript
|
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse";
|
|
```
|
|
|
|
##### Constructor
|
|
```typescript
|
|
constructor(url: URL)
|
|
```
|
|
|
|
#### WebSocketClientTransport
|
|
```typescript
|
|
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket";
|
|
```
|
|
|
|
##### Constructor
|
|
```typescript
|
|
constructor(url: URL)
|
|
```
|
|
|
|
## Server classes
|
|
|
|
### Server
|
|
|
|
The main class for implementing MCP servers in TypeScript.
|
|
|
|
```typescript
|
|
import { Server } from "@modelcontextprotocol/sdk/server";
|
|
```
|
|
|
|
#### Constructor
|
|
```typescript
|
|
constructor(serverInfo: Implementation)
|
|
```
|
|
|
|
**Parameters:**
|
|
- `serverInfo`: Implementation object containing:
|
|
- `name`: string - Name of the server
|
|
- `version`: string - Version of the server
|
|
|
|
#### Methods
|
|
|
|
##### connect()
|
|
```typescript
|
|
async connect(transport: Transport): Promise<void>
|
|
```
|
|
Starts listening for client connections.
|
|
|
|
##### setRequestHandler()
|
|
```typescript
|
|
setRequestHandler<T extends ZodObject<{method: ZodLiteral<string>}>>(
|
|
requestSchema: T,
|
|
handler: (request: z.infer<T>) => ServerResult | Promise<ServerResult>
|
|
): void
|
|
```
|
|
Registers a handler for specific request types.
|
|
|
|
##### setNotificationHandler()
|
|
```typescript
|
|
setNotificationHandler<T extends ZodObject<{method: ZodLiteral<string>}>>(
|
|
notificationSchema: T,
|
|
handler: (notification: z.infer<T>) => void | Promise<void>
|
|
): void
|
|
```
|
|
Registers a handler for specific notification types.
|
|
|
|
##### notification()
|
|
```typescript
|
|
async notification(notification: ServerNotification): Promise<void>
|
|
```
|
|
Sends a notification to the client.
|
|
|
|
##### close()
|
|
```typescript
|
|
async close(): Promise<void>
|
|
```
|
|
Closes all connections.
|
|
|
|
##### getClientCapabilities()
|
|
```typescript
|
|
getClientCapabilities(): ClientCapabilities | undefined
|
|
```
|
|
Returns the client's capabilities after connection.
|
|
|
|
##### getClientVersion()
|
|
```typescript
|
|
getClientVersion(): Implementation | undefined
|
|
```
|
|
Returns the client's version information after connection.
|
|
|
|
### Transport classes
|
|
|
|
#### StdioServerTransport
|
|
```typescript
|
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
|
|
```
|
|
|
|
##### Constructor
|
|
```typescript
|
|
constructor(stdin?: Readable, stdout?: Writable)
|
|
```
|
|
|
|
#### SSEServerTransport
|
|
```typescript
|
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse";
|
|
```
|
|
|
|
##### Constructor
|
|
```typescript
|
|
constructor(endpoint: string, res: ServerResponse)
|
|
```
|
|
|
|
## Examples
|
|
|
|
### Client implementation
|
|
|
|
```typescript
|
|
import { Client } from "@modelcontextprotocol/sdk/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio";
|
|
import {
|
|
ListResourcesResultSchema,
|
|
ReadResourceResultSchema,
|
|
ListToolsResultSchema,
|
|
CallToolResultSchema
|
|
} from "@modelcontextprotocol/sdk/types";
|
|
|
|
async function main() {
|
|
// Create client
|
|
const client = new Client({
|
|
name: "example-client",
|
|
version: "1.0.0"
|
|
});
|
|
|
|
// Connect to server
|
|
const transport = new StdioClientTransport({
|
|
command: "./server",
|
|
args: ["--config", "config.json"]
|
|
});
|
|
await client.connect(transport);
|
|
|
|
try {
|
|
// List resources
|
|
const resources = await client.request(
|
|
{ method: "resources/list" },
|
|
ListResourcesResultSchema
|
|
);
|
|
console.log("Available resources:", resources);
|
|
|
|
// Read resource
|
|
const content = await client.request(
|
|
{
|
|
method: "resources/read",
|
|
params: { uri: "example://resource" }
|
|
},
|
|
ReadResourceResultSchema
|
|
);
|
|
console.log("Resource content:", content);
|
|
|
|
// List tools
|
|
const tools = await client.request(
|
|
{ method: "tools/list" },
|
|
ListToolsResultSchema
|
|
);
|
|
console.log("Available tools:", tools);
|
|
|
|
// Call tool with progress
|
|
const result = await client.request(
|
|
{
|
|
method: "tools/call",
|
|
params: {
|
|
name: "example-tool",
|
|
arguments: { param1: "value1" }
|
|
}
|
|
},
|
|
CallToolResultSchema,
|
|
(progress) => {
|
|
console.log(`Progress: ${progress.progress}/${progress.total}`);
|
|
}
|
|
);
|
|
console.log("Tool result:", result);
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
}
|
|
```
|
|
|
|
### Server implementation
|
|
|
|
```typescript
|
|
import { Server } from "@modelcontextprotocol/sdk/server";
|
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
|
|
import {
|
|
ListResourcesRequestSchema,
|
|
ReadResourceRequestSchema,
|
|
ListToolsRequestSchema,
|
|
CallToolRequestSchema
|
|
} from "@modelcontextprotocol/sdk/types";
|
|
|
|
async function main() {
|
|
// Create server
|
|
const server = new Server({
|
|
name: "example-server",
|
|
version: "1.0.0"
|
|
});
|
|
|
|
// Handle resource listing
|
|
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
return {
|
|
resources: [
|
|
{
|
|
uri: "example://resource",
|
|
name: "Example Resource",
|
|
description: "An example resource"
|
|
}
|
|
]
|
|
};
|
|
});
|
|
|
|
// Handle resource reading
|
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
if (request.params.uri === "example://resource") {
|
|
return {
|
|
contents: [
|
|
{
|
|
uri: request.params.uri,
|
|
mimeType: "text/plain",
|
|
text: "Example content"
|
|
}
|
|
]
|
|
};
|
|
}
|
|
throw new Error("Resource not found");
|
|
});
|
|
|
|
// Handle tool listing
|
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
return {
|
|
tools: [
|
|
{
|
|
name: "example-tool",
|
|
description: "An example tool",
|
|
inputSchema: {
|
|
type: "object",
|
|
properties: {
|
|
param1: { type: "string" }
|
|
}
|
|
}
|
|
}
|
|
]
|
|
};
|
|
});
|
|
|
|
// Handle tool calls
|
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
const { name, arguments: args } = request.params;
|
|
|
|
// Send progress updates
|
|
for (let i = 0; i < 5; i++) {
|
|
await server.notification({
|
|
method: "notifications/progress",
|
|
params: {
|
|
progress: i + 1,
|
|
total: 5,
|
|
progressToken: request.params._meta?.progressToken
|
|
}
|
|
});
|
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
}
|
|
|
|
return {
|
|
toolResult: `Executed ${name} with args: ${JSON.stringify(args)}`
|
|
};
|
|
});
|
|
|
|
// Start server
|
|
const transport = new StdioServerTransport();
|
|
await server.connect(transport);
|
|
}
|
|
```
|
|
|
|
## Best practices
|
|
|
|
1. **Error Handling**
|
|
```typescript
|
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
try {
|
|
const content = await readResource(request.params.uri);
|
|
return { contents: [content] };
|
|
} catch (error) {
|
|
if (error instanceof ResourceNotFoundError) {
|
|
throw new McpError(404, `Resource not found: ${request.params.uri}`);
|
|
}
|
|
throw error;
|
|
}
|
|
});
|
|
```
|
|
|
|
2. **Progress Updates**
|
|
```typescript
|
|
async function longRunningOperation(
|
|
progressToken?: string | number
|
|
): Promise<void> {
|
|
for (let i = 0; i < total; i++) {
|
|
await server.notification({
|
|
method: "notifications/progress",
|
|
params: {
|
|
progress: i,
|
|
total,
|
|
progressToken
|
|
}
|
|
});
|
|
}
|
|
}
|
|
```
|
|
|
|
3. **Resource Updates**
|
|
```typescript
|
|
async function updateResource(uri: string): Promise<void> {
|
|
// Update resource
|
|
await server.notification({
|
|
method: "notifications/resources/updated",
|
|
params: { uri }
|
|
});
|
|
}
|
|
```
|
|
|
|
4. **Cleanup**
|
|
```typescript
|
|
process.on("SIGINT", async () => {
|
|
await server.close();
|
|
process.exit(0);
|
|
});
|
|
``` |