updated layout
This commit is contained in:
parent
21a38ebe74
commit
aa6c2ee2f9
3 changed files with 882 additions and 19 deletions
|
|
@ -3,6 +3,416 @@ title: "TypeScript Class Reference"
|
|||
description: "Complete TypeScript SDK class documentation"
|
||||
---
|
||||
|
||||
# TypeScript Class Reference
|
||||
## Client Classes
|
||||
|
||||
Complete TypeScript SDK class documentation
|
||||
### 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);
|
||||
});
|
||||
```
|
||||
|
|
@ -3,6 +3,459 @@ title: "TypeScript Type Definitions"
|
|||
description: "TypeScript type system documentation"
|
||||
---
|
||||
|
||||
# TypeScript Type Definitions
|
||||
## Core Protocol Types
|
||||
|
||||
TypeScript type system documentation
|
||||
### JSON-RPC Types
|
||||
|
||||
```typescript
|
||||
export const JSONRPC_VERSION = "2.0";
|
||||
|
||||
/** A uniquely identifying ID for a request in JSON-RPC */
|
||||
export type RequestId = string | number;
|
||||
|
||||
/** A request that expects a response */
|
||||
export interface JSONRPCRequest {
|
||||
jsonrpc: typeof JSONRPC_VERSION;
|
||||
id: RequestId;
|
||||
method: string;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** A notification which does not expect a response */
|
||||
export interface JSONRPCNotification {
|
||||
jsonrpc: typeof JSONRPC_VERSION;
|
||||
method: string;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** A successful (non-error) response to a request */
|
||||
export interface JSONRPCResponse {
|
||||
jsonrpc: typeof JSONRPC_VERSION;
|
||||
id: RequestId;
|
||||
result: unknown;
|
||||
}
|
||||
|
||||
/** A response to a request that indicates an error occurred */
|
||||
export interface JSONRPCError {
|
||||
jsonrpc: typeof JSONRPC_VERSION;
|
||||
id: RequestId;
|
||||
error: {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export type JSONRPCMessage =
|
||||
| JSONRPCRequest
|
||||
| JSONRPCNotification
|
||||
| JSONRPCResponse
|
||||
| JSONRPCError;
|
||||
```
|
||||
|
||||
### Message Content Types
|
||||
|
||||
```typescript
|
||||
/** Text provided to or from an LLM */
|
||||
export interface TextContent {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** An image provided to or from an LLM */
|
||||
export interface ImageContent {
|
||||
type: "image";
|
||||
data: string; // Base64-encoded
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
/** Describes a message issued to or received from an LLM API */
|
||||
export interface SamplingMessage {
|
||||
role: "user" | "assistant";
|
||||
content: TextContent | ImageContent;
|
||||
}
|
||||
|
||||
/** Progress information for long-running operations */
|
||||
export interface Progress {
|
||||
progress: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export type ProgressCallback = (progress: Progress) => void;
|
||||
```
|
||||
|
||||
### Resource Types
|
||||
|
||||
```typescript
|
||||
/** The contents of a specific resource */
|
||||
export interface ResourceContents {
|
||||
uri: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
/** Text-based resource contents */
|
||||
export interface TextResourceContents extends ResourceContents {
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Binary resource contents */
|
||||
export interface BlobResourceContents extends ResourceContents {
|
||||
blob: string; // Base64-encoded
|
||||
}
|
||||
|
||||
/** A known resource that the server is capable of reading */
|
||||
export interface Resource {
|
||||
uri: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
/** A template description for resources available on the server */
|
||||
export interface ResourceTemplate {
|
||||
uriTemplate: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Types
|
||||
|
||||
```typescript
|
||||
/** Definition for a tool the client can call */
|
||||
export interface Tool {
|
||||
name: string;
|
||||
description?: string;
|
||||
inputSchema: {
|
||||
type: "object";
|
||||
properties?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Prompt Types
|
||||
|
||||
```typescript
|
||||
/** Describes an argument that a prompt can accept */
|
||||
export interface PromptArgument {
|
||||
name: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
/** A prompt or prompt template that the server offers */
|
||||
export interface Prompt {
|
||||
name: string;
|
||||
description?: string;
|
||||
arguments?: PromptArgument[];
|
||||
}
|
||||
```
|
||||
|
||||
## Request/Response Types
|
||||
|
||||
### Resource Requests
|
||||
|
||||
```typescript
|
||||
export interface ListResourcesRequest {
|
||||
method: "resources/list";
|
||||
params?: {
|
||||
cursor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ListResourcesResult {
|
||||
resources: Resource[];
|
||||
nextCursor?: string;
|
||||
}
|
||||
|
||||
export interface ReadResourceRequest {
|
||||
method: "resources/read";
|
||||
params: {
|
||||
uri: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ReadResourceResult {
|
||||
contents: Array<TextResourceContents | BlobResourceContents>;
|
||||
}
|
||||
|
||||
export interface SubscribeRequest {
|
||||
method: "resources/subscribe";
|
||||
params: {
|
||||
uri: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface UnsubscribeRequest {
|
||||
method: "resources/unsubscribe";
|
||||
params: {
|
||||
uri: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Tool Requests
|
||||
|
||||
```typescript
|
||||
export interface ListToolsRequest {
|
||||
method: "tools/list";
|
||||
params?: {
|
||||
cursor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ListToolsResult {
|
||||
tools: Tool[];
|
||||
nextCursor?: string;
|
||||
}
|
||||
|
||||
export interface CallToolRequest {
|
||||
method: "tools/call";
|
||||
params: {
|
||||
name: string;
|
||||
arguments?: Record<string, unknown>;
|
||||
_meta?: {
|
||||
progressToken?: string | number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface CallToolResult {
|
||||
toolResult: unknown;
|
||||
}
|
||||
```
|
||||
|
||||
### Prompt Requests
|
||||
|
||||
```typescript
|
||||
export interface ListPromptsRequest {
|
||||
method: "prompts/list";
|
||||
params?: {
|
||||
cursor?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ListPromptsResult {
|
||||
prompts: Prompt[];
|
||||
nextCursor?: string;
|
||||
}
|
||||
|
||||
export interface GetPromptRequest {
|
||||
method: "prompts/get";
|
||||
params: {
|
||||
name: string;
|
||||
arguments?: Record<string, string>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GetPromptResult {
|
||||
description?: string;
|
||||
messages: SamplingMessage[];
|
||||
}
|
||||
```
|
||||
|
||||
## Protocol Types
|
||||
|
||||
### Implementation Info
|
||||
|
||||
```typescript
|
||||
export interface Implementation {
|
||||
name: string;
|
||||
version: string;
|
||||
}
|
||||
```
|
||||
|
||||
### Capability Types
|
||||
|
||||
```typescript
|
||||
export interface ResourceCapabilities {
|
||||
subscribe?: boolean;
|
||||
listChanged?: boolean;
|
||||
}
|
||||
|
||||
export interface PromptCapabilities {
|
||||
listChanged?: boolean;
|
||||
}
|
||||
|
||||
export interface ToolCapabilities {
|
||||
listChanged?: boolean;
|
||||
}
|
||||
|
||||
export interface ServerCapabilities {
|
||||
experimental?: Record<string, unknown>;
|
||||
logging?: Record<string, unknown>;
|
||||
prompts?: PromptCapabilities;
|
||||
resources?: ResourceCapabilities;
|
||||
tools?: ToolCapabilities;
|
||||
}
|
||||
|
||||
export interface ClientCapabilities {
|
||||
experimental?: Record<string, unknown>;
|
||||
sampling?: Record<string, unknown>;
|
||||
}
|
||||
```
|
||||
|
||||
### Notification Types
|
||||
|
||||
```typescript
|
||||
export interface ResourceUpdatedNotification {
|
||||
method: "notifications/resources/updated";
|
||||
params: {
|
||||
uri: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProgressNotification {
|
||||
method: "notifications/progress";
|
||||
params: Progress & {
|
||||
progressToken: string | number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface LogMessageNotification {
|
||||
method: "notifications/message";
|
||||
params: {
|
||||
level: "debug" | "info" | "warning" | "error";
|
||||
logger?: string;
|
||||
data: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export type ServerNotification =
|
||||
| ResourceUpdatedNotification
|
||||
| ProgressNotification
|
||||
| LogMessageNotification;
|
||||
```
|
||||
|
||||
## Error Types
|
||||
|
||||
```typescript
|
||||
export enum ErrorCode {
|
||||
// SDK error codes
|
||||
ConnectionClosed = -1,
|
||||
|
||||
// Standard JSON-RPC error codes
|
||||
ParseError = -32700,
|
||||
InvalidRequest = -32600,
|
||||
MethodNotFound = -32601,
|
||||
InvalidParams = -32602,
|
||||
InternalError = -32603,
|
||||
}
|
||||
|
||||
export class McpError extends Error {
|
||||
constructor(
|
||||
public readonly code: number,
|
||||
message: string,
|
||||
public readonly data?: unknown
|
||||
) {
|
||||
super(`MCP error ${code}: ${message}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Transport Types
|
||||
|
||||
```typescript
|
||||
export interface Transport {
|
||||
start(): Promise<void>;
|
||||
send(message: JSONRPCMessage): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
onclose?: () => void;
|
||||
onerror?: (error: Error) => void;
|
||||
onmessage?: (message: JSONRPCMessage) => void;
|
||||
}
|
||||
|
||||
export interface StdioServerParameters {
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
}
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Type Guards
|
||||
|
||||
```typescript
|
||||
function isTextContent(content:
|
||||
TextContent | ImageContent
|
||||
): content is TextContent {
|
||||
return content.type === "text";
|
||||
}
|
||||
|
||||
function isResourceUpdatedNotification(
|
||||
notification: ServerNotification
|
||||
): notification is ResourceUpdatedNotification {
|
||||
return notification.method === "notifications/resources/updated";
|
||||
}
|
||||
```
|
||||
|
||||
### Type Assertions
|
||||
|
||||
```typescript
|
||||
function assertResource(data: unknown): asserts data is Resource {
|
||||
if (typeof data !== "object" || data === null) {
|
||||
throw new TypeError("Expected object");
|
||||
}
|
||||
|
||||
const resource = data as Partial<Resource>;
|
||||
if (typeof resource.uri !== "string") {
|
||||
throw new TypeError("Expected string uri");
|
||||
}
|
||||
if (typeof resource.name !== "string") {
|
||||
throw new TypeError("Expected string name");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Using Generics
|
||||
|
||||
```typescript
|
||||
async function handleResourceContent<T extends ResourceContents>(
|
||||
content: T
|
||||
): Promise<string> {
|
||||
if ("text" in content) {
|
||||
return content.text;
|
||||
}
|
||||
if ("blob" in content) {
|
||||
return atob(content.blob);
|
||||
}
|
||||
throw new Error("Invalid resource content");
|
||||
}
|
||||
```
|
||||
|
||||
### Working with Union Types
|
||||
|
||||
```typescript
|
||||
function processMessage(message: SamplingMessage): string {
|
||||
const { content } = message;
|
||||
switch (content.type) {
|
||||
case "text":
|
||||
return content.text;
|
||||
case "image":
|
||||
return `Image: ${content.mimeType}`;
|
||||
default:
|
||||
const _exhaustiveCheck: never = content;
|
||||
throw new Error("Unknown content type");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Type Utilities
|
||||
|
||||
```typescript
|
||||
/** Helper type to extract request params from method name */
|
||||
type RequestParams<T extends string> = Extract<
|
||||
ClientRequest,
|
||||
{ method: T }
|
||||
>["params"];
|
||||
|
||||
/** Helper type to extract result type from schema */
|
||||
type SchemaType<T extends ZodType> = z.infer<T>;
|
||||
|
||||
/** Helper type for request handlers */
|
||||
type RequestHandler<T extends ClientRequest> = (
|
||||
request: T
|
||||
) => Promise<SchemaType<typeof ResultSchemas[T["method"]]>>;
|
||||
```
|
||||
32
mint.json
32
mint.json
|
|
@ -15,12 +15,12 @@
|
|||
"topbarLinks": [
|
||||
{
|
||||
"name": "Support",
|
||||
"url": "mailto:hi@mintlify.com"
|
||||
"url": "mailto:mcp-coc@anthropic.com"
|
||||
}
|
||||
],
|
||||
"topbarCtaButton": {
|
||||
"name": "Dashboard",
|
||||
"url": "https://dashboard.mintlify.com"
|
||||
"name": "Github",
|
||||
"url": "https://github.com/modelcontextprotocol"
|
||||
},
|
||||
"tabs": [
|
||||
{
|
||||
|
|
@ -35,14 +35,14 @@
|
|||
"url": "https://mintlify.com/docs"
|
||||
},
|
||||
{
|
||||
"name": "Community",
|
||||
"icon": "slack",
|
||||
"url": "https://mintlify.com/community"
|
||||
"name": "Python SDK",
|
||||
"icon": "python",
|
||||
"url": "https://github.com/modelcontextprotocol/python-sdk"
|
||||
},
|
||||
{
|
||||
"name": "Blog",
|
||||
"icon": "newspaper",
|
||||
"url": "https://mintlify.com/blog"
|
||||
"name": "TypeScript SDK",
|
||||
"icon": "node-js",
|
||||
"url": "https://github.com/modelcontextprotocol/python-sdk"
|
||||
}
|
||||
],
|
||||
"navigation": [
|
||||
|
|
@ -92,19 +92,19 @@
|
|||
"api-reference/client-api/tool-invocation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "TypeScript SDK",
|
||||
"pages": [
|
||||
"api-reference/typescript/class-reference",
|
||||
"api-reference/typescript/type-definitions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Python SDK",
|
||||
"pages": [
|
||||
"api-reference/python/class-reference",
|
||||
"api-reference/python/type-hints"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "TypeScript SDK",
|
||||
"pages": [
|
||||
"api-reference/typescript/class-reference",
|
||||
"api-reference/typescript/type-definitions"
|
||||
]
|
||||
}
|
||||
],
|
||||
"footerSocials": {
|
||||
|
|
|
|||
Loading…
Reference in a new issue